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 |
---|---|---|---|---|
graph_map.rs
|
use typed_map::TypedMemoryMap;
pub struct GraphMMap {
nodes: TypedMemoryMap<u64>,
edges: TypedMemoryMap<u32>,
}
impl GraphMMap {
#[inline(always)]
pub fn nodes(&self) -> usize { self.nodes[..].len() }
#[inline(always)]
pub fn
|
(&self, node: usize) -> &[u32] {
let nodes = &self.nodes[..];
if node + 1 < nodes.len() {
let start = nodes[node] as usize;
let limit = nodes[node+1] as usize;
&self.edges[..][start..limit]
}
else { &[] }
}
pub fn new(prefix: &str) -> GraphMMap {
GraphMMap {
nodes: TypedMemoryMap::new(format!("{}.offsets", prefix)),
edges: TypedMemoryMap::new(format!("{}.targets", prefix)),
}
}
}
|
edges
|
identifier_name
|
graph_map.rs
|
use typed_map::TypedMemoryMap;
pub struct GraphMMap {
nodes: TypedMemoryMap<u64>,
edges: TypedMemoryMap<u32>,
}
impl GraphMMap {
#[inline(always)]
pub fn nodes(&self) -> usize { self.nodes[..].len() }
#[inline(always)]
pub fn edges(&self, node: usize) -> &[u32] {
let nodes = &self.nodes[..];
if node + 1 < nodes.len()
|
else { &[] }
}
pub fn new(prefix: &str) -> GraphMMap {
GraphMMap {
nodes: TypedMemoryMap::new(format!("{}.offsets", prefix)),
edges: TypedMemoryMap::new(format!("{}.targets", prefix)),
}
}
}
|
{
let start = nodes[node] as usize;
let limit = nodes[node+1] as usize;
&self.edges[..][start..limit]
}
|
conditional_block
|
TestNativeAtanh.rs
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma version(1)
#pragma rs java_package_name(android.renderscript.cts)
// Don't edit this file! It is auto-generated by frameworks/rs/api/gen_runtime.
float __attribute__((kernel)) testNativeAtanhFloatFloat(float inIn) {
|
}
float2 __attribute__((kernel)) testNativeAtanhFloat2Float2(float2 inIn) {
return native_atanh(inIn);
}
float3 __attribute__((kernel)) testNativeAtanhFloat3Float3(float3 inIn) {
return native_atanh(inIn);
}
float4 __attribute__((kernel)) testNativeAtanhFloat4Float4(float4 inIn) {
return native_atanh(inIn);
}
|
return native_atanh(inIn);
|
random_line_split
|
javascript.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// The rust-book JavaScript in string form.
pub static JAVASCRIPT: &'static str = r#"
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("toggle-nav").onclick = toggleNav;
function toggleNav() {
var toc = document.getElementById("toc");
var pagewrapper = document.getElementById("page-wrapper");
toggleClass(toc, "mobile-hidden");
toggleClass(pagewrapper, "mobile-hidden");
};
function toggleClass(el, className) {
// from http://youmightnotneedjquery.com/
if (el.classList) {
el.classList.toggle(className);
} else {
var classes = el.className.split(' ');
var existingIndex = classes.indexOf(className);
if (existingIndex >= 0) {
classes.splice(existingIndex, 1);
} else {
classes.push(className);
|
});
</script>
"#;
|
}
el.className = classes.join(' ');
}
}
|
random_line_split
|
zhtta2.rs
|
None => "",
};
debug!("Requested path: [{}]", path_obj.as_str().expect("error"));
debug!("Requested path: [{}]", path_str);
//maybe spawn new threads here to deal with each request
if path_str.as_slice().eq("./") {
debug!("===== Counter Page request =====");
//send count of visitors to method with counter page
WebServer::respond_with_counter_page(stream, count);
debug!("=====Terminated connection from [{}].=====", peer_name);
} else if!path_obj.exists() || path_obj.is_dir() {
debug!("===== Error page request =====");
WebServer::respond_with_error_page(stream, &path_obj);
debug!("=====Terminated connection from [{}].=====", peer_name);
} else if ext_str == "shtml" { // Dynamic web pages.
debug!("===== Dynamic Page request =====");
WebServer::respond_with_dynamic_page(stream, &path_obj);
debug!("=====Terminated connection from [{}].=====", peer_name);
} else {
debug!("===== Static Page request =====");
WebServer::enqueue_static_file_request(stream, &path_obj, stream_map_arc, request_queue_arc, notify_chan);
}
}
});
}
});
}
fn respond_with_error_page(stream: std::old_io::net::tcp::TcpStream, path: &Path) {
let mut stream = stream;
let msg: String= format!("Cannot open: {}", path.as_str().expect("invalid path"));
stream.write(HTTP_BAD.as_bytes());
stream.write(msg.as_bytes());
}
// Safe visitor counter.
fn respond_with_counter_page(stream: std::old_io::net::tcp::TcpStream, local_count: usize) {
let mut stream = stream;
let response: String =
format!("{}{}<h1>Greetings, Krusty!</h1><h2>Visitor count: {}</h2></body></html>\r\n",
HTTP_OK, COUNTER_STYLE,
local_count);
debug!("Responding to counter request");
stream.write(response.as_bytes());
}
// TODO: Streaming file.
// TODO: Application-layer file caching.
fn respond_with_static_file(stream: std::old_io::net::tcp::TcpStream, path: &Path, cache: Arc<Mutex<HashMap<String, Vec<u8>>>>, being_read: Arc<Mutex<HashMap<String, String>>>) {
let mut timer = Timer::new().unwrap();
//boolean saying whether file in cache or not
let mut was_cached = 0;
let mut file_reader: File;
//first, get the map that stores all the files in cache, acquire lock, and set boolean indicating whether or not it was in cache
{
let mut cache_map = cache.lock().unwrap();
//path as string is key for cached file
let fname = path.as_str().unwrap();
//if file is in cache, set was_cached to "true" (1)
if cache_map.contains_key(fname) {
println!("in cache");
was_cached = 1;
}
}
let fname = path.as_str().unwrap();
let f_string = fname.to_string();
let read_val = "reading".to_string();
let mut being_read_bool = 0;
//if file was not in the cache, but is in process of being read
//by another thread, other threads should busy wait for file to be
//put in cache
{
let mut reading = being_read.lock().unwrap();
if reading.contains_key(fname) {
println!("file currently being read from disk");
being_read_bool = 1;
}
}
//if file was not in cache, but is currently being read from disk
//other threads trying to get the file should spin until in cache
if was_cached == 0 && being_read_bool == 1
{
while being_read_bool == 1 {
{
//within busy wait, check being_read periodically
let mut reading = being_read.lock().unwrap();
if!reading.contains_key(fname)
{
//when no longer being read, set being_read to false
being_read_bool = 0;
was_cached = 1; //and, the file is now in cache
//println!("still being read...");
}
}
//sleep me so it's not constantly checking the counter
timer.sleep(Duration::milliseconds(10));
}
}
//if file wasn't in cache, read from disk
if was_cached == 0 {
//was not cached, but about to be read from disk- put in being_read
{
let mut reading = being_read.lock().unwrap();
let f_string2 = fname.to_string();
reading.insert(f_string2, read_val);
}
//{
//let mut cache_map = cache.lock().unwrap();
//read from disk
println!("NOT in cache");
file_reader = File::open(path).unwrap();
let file_stats = file_reader.stat();
let file_size = file_stats.unwrap().size;
let mut reader = BufferedReader::new(file_reader);
let mut stream = stream;
stream.write(HTTP_OK.as_bytes());
//now stream file and also append it into contents- this can
//take a while especially for bigger files, but this does not
//happen within a lock, so other threads can run concurrently
//with this reading
let mut contents: Vec<u8> = Vec::with_capacity(file_size as usize);
for line in reader.lines().filter_map(|result| result.ok()) {
let l2 = line.clone();
let mut line_vec: Vec<u8> = line.into_bytes();
contents.append(&mut line_vec);
let _ = stream.write_all(l2.as_bytes());
}
//after read from disk, acquire lock and put file in cache
{
let mut cache_map = cache.lock().unwrap();
cache_map.insert(f_string, contents);
was_cached = 1;
//this file is no longer in the process of being read
let mut reading = being_read.lock().unwrap();
reading.remove(fname);
being_read_bool = 1;
}
}
//file was in cache- read it out of the cache
else{
let fname = path.as_str().unwrap();
println!("read from cache");
//acquire lock to read file out of cache
{
let mut cache_map = cache.lock().unwrap();
let mut file_reader_option = cache_map.get(fname);
let contents = file_reader_option.unwrap();
let mut stream = stream;
stream.write(HTTP_OK.as_bytes());
stream.write(contents.as_slice());
}
}
}
//Server-side gashing.
fn respond_with_dynamic_page(stream: std::old_io::net::tcp::TcpStream, path: &Path) {
// for now, just serve as static file
//WebServer::respond_with_static_file(stream, path);
let mut stream = stream;
let response = HTTP_OK;
//let mut resp: &str = "";
//let resp_str: String = ("").to_string();
let mut file = BufferedReader::new(File::open(path));
stream.write(response.as_bytes()); //start the stream with HTTP_OK
for line in file.lines(){
let l = line.unwrap();
let l_str: String = l.to_string();
let l_split = l_str.split_str("<!--#exec");
let l_vec = l_split.collect::<Vec<&str>>();
if l_vec.len() > 1 { //if there was an embedded shell command
//println!("shell command");
stream.write(l_vec[0].as_bytes());
let middle = l_vec[1];
let mid_split = middle.split_str("-->");
let mid_vec = mid_split.collect::<Vec<&str>>();
let in_quotes = mid_vec[0];
let openq_split = in_quotes.split_str("\"");
let openq_vec = openq_split.collect::<Vec<&str>>();
//println!("{}", openq_vec[1]);
//cmd for gash is in openq_vec[1]
let command = openq_vec[1];
//code below prints out results of Shell's running of embedded command
let cmd_result: Receiver<gash::Packet> = gash::Shell::new("").run_cmdline(command);
loop{
let test: gash::Packet = match cmd_result.recv(){
Err(why) => {break;},
Ok(res) => {res},
};
stream.write(test.to_string().as_bytes());
if test.end_of_stream {
break;
}
}
if l_vec.len() > 2 { //if there was more AFTER the embedded shell command
stream.write(l_vec[2].as_bytes());
}
} else { //if there was no embedded shell command, just write line
stream.write(l.as_bytes());
}
}
}
// TODO: Smarter Scheduling.
fn enqueue_static_file_request(stream: std::old_io::net::tcp::TcpStream, path_obj: &Path, stream_map_arc: Arc<Mutex<HashMap<String, std::old_io::net::tcp::TcpStream>>>, req_queue_arc: Arc<Mutex<BinaryHeap<HTTP_Request>>>, notify_chan: Sender<()>) {
// Save stream in hashmap for later response.
let mut stream = stream;
let peer_name = WebServer::get_peer_name(&mut stream);
let (stream_tx, stream_rx) = channel();
stream_tx.send(stream);
let stream = match stream_rx.recv(){
Ok(s) => s,
Err(e) => panic!("There was an error while receiving from the stream channel! {}", e),
};
let local_stream_map = stream_map_arc.clone();
{ // make sure we request the lock inside a block with different scope, so that we give it back at the end of that block
let mut local_stream_map = local_stream_map.lock().unwrap();
local_stream_map.insert(peer_name.clone(), stream);
}
// Enqueue the HTTP request.
// TOCHECK: it was ~path_obj.clone(), make sure in which order are ~ and clone() executed
let size = path_obj.stat().unwrap().size;
let req = HTTP_Request { peer_name: peer_name.clone(), path: path_obj.clone(), size: size };
let (req_tx, req_rx) = channel();
req_tx.send(req);
debug!("Waiting for queue mutex lock.");
let local_req_queue = req_queue_arc.clone();
{ // make sure we request the lock inside a block with different scope, so that we give it back at the end of that block
let mut local_req_queue = local_req_queue.lock().unwrap();
let req: HTTP_Request = match req_rx.recv(){
Ok(s) => s,
Err(e) => panic!("There was an error while receiving from the request channel! {}", e),
};
local_req_queue.push(req);
debug!("A new request enqueued, now the length of queue is {}.", local_req_queue.len());
notify_chan.send(()); // Send incoming notification to responder task.
}
}
// TODO: Smarter Scheduling.
fn dequeue_static_file_request(&mut self) {
let req_queue_get = self.request_queue_arc.clone();
let stream_map_get = self.stream_map_arc.clone();
// Receiver<> cannot be sent to another task. So we have to make this task as the main task that can access self.notify_rx.
let (request_tx, request_rx) = channel();
let mut thread_count = Arc::new(Mutex::new(0)); //count how many threads are running for tasks
let mut counter = 0;
let mut timer = Timer::new().unwrap();
loop
{
self.notify_rx.recv(); // waiting for new request enqueued.
{ // make sure we request the lock inside a block with different scope, so that we give it back at the end of that block
let mut req_queue = req_queue_get.lock().unwrap();
if req_queue.len() > 0 {
let req = req_queue.pop();
debug!("A new request dequeued, now the length of queue is {}.", req_queue.len());
request_tx.send(req);
}
}
let request = match request_rx.recv(){
Ok(s) => s.unwrap(),
Err(e) => panic!("There was an error while receiving from the request channel! {}", e),
};
// Get stream from hashmap.
let (stream_tx, stream_rx) = channel();
{ // make sure we request the lock inside a block with different scope, so that we give it back at the end of that block
let mut stream_map = stream_map_get.lock().unwrap();
let r2 = &request.peer_name;
//let r3 = &request.path;
//println!("next req is {:?}", r3);
let stream = stream_map.remove(r2).expect("no option tcpstream");
stream_tx.send(stream);
}
// TODO: Spawning more tasks to respond the dequeued requests concurrently. You may need a semophore to control the concurrency.
//let tcount = thread_count.clone();
//let mut count = tcount.lock().unwrap();
//println!("times thru loop: {}", loopct);
//println!("counter is {}", counter);
//check the count of currently running threads
{
counter = *(thread_count.lock().unwrap());
println!("init {} - {}", counter, thread_limit);
}
//if count is greater than or equal to limit, busy wait
while counter >= thread_limit {
{
//within busy wait, check the counter periodically
counter = *(thread_count.lock().unwrap());
//println!("waiting {} - {}", counter, thread_limit);
}
//sleep me so it's not constantly checking the counter
timer.sleep(Duration::milliseconds(10));
}
let cache = self.cached_files_arc.clone();
let being_read = self.being_read_arc.clone();
{
{
let mut c =thread_count.lock().unwrap(); //lock the count so it can be incremented
*c += 1;
println!("INC: threads running is {}", *c);
}
let tc = thread_count.clone();
Thread::spawn(move || {
let stream = match stream_rx.recv(){
Ok(s) => s,
Err(e) => panic!("There was an error while receiving from the stream channel! {}", e),
};
//println!("threads running is {}", thread_count);
let r = &request.path;
WebServer::respond_with_static_file(stream, r, cache, being_read);
// Close stream automatically.
debug!("=====Terminated connection from [{:?}].=====", r);
{
let mut d = tc.lock().unwrap(); //lock the count so it can be decremented
*d -= 1;
println!("DEC: threads running is {}", *d);
}
});
}
}
}
fn get_peer_name(stream: &mut std::old_io::net::tcp::TcpStream) -> String{
match stream.peer_name(){
Ok(s) => {format!("{}:{}", s.ip, s.port)}
Err(e) => {panic!("Error while getting the stream name! {}", e)}
}
}
}
fn get_args() -> (String, usize, String) {
fn print_usage(program: &str) {
println!("Usage: {} [options]", program);
println!("--ip \tIP address, \"{}\" by default.", IP);
println!("--port \tport number, \"{}\" by default.", PORT);
println!("--www \tworking directory, \"{}\" by default", WWW_DIR);
println!("-h --help \tUsage");
}
/* Begin processing program arguments and initiate the parameters. */
let args = os::args();
let program = args[0].clone();
let opts = [
getopts::optopt("", "ip", "The IP address to bind to", "IP"),
getopts::optopt("", "port", "The Port to bind to", "PORT"),
getopts::optopt("", "www", "The www directory", "WWW_DIR"),
getopts::optflag("h", "help", "Display help"),
];
let matches = match getopts::getopts(args.tail(), &opts) {
Ok(m) => { m }
Err(f) => { panic!(f.to_err_msg()) }
};
if matches.opt_present("h") || matches.opt_present("help") {
print_usage(program.as_slice());
unsafe { libc::exit(1); }
}
let ip_str = if matches.opt_present("ip") {
matches.opt_str("ip").expect("invalid ip address?").to_owned()
} else {
IP.to_owned()
};
let port:usize = if matches.opt_present("port") {
let input_port = matches.opt_str("port").expect("Invalid port number?").trim().parse::<usize>().ok();
match input_port {
Some(port) => port,
None => panic!("Invalid port number?"),
}
} else {
PORT
};
let www_dir_str = if matches.opt_present("www") {
matches.opt_str("www").expect("invalid www argument?")
} else { WWW_DIR.to_owned() };
(ip_str, port, www_dir_str)
}
fn
|
main
|
identifier_name
|
|
zhtta2.rs
|
.com/mozilla/rust/issues/12139)
peer_name: String,
path: Path,
size: u64,
}
//need to make it a min heap
impl PartialEq for HTTP_Request {
fn eq(&self, other: &Self) -> bool{
other.size == self.size
}
}
impl Eq for HTTP_Request {}
impl PartialOrd for HTTP_Request {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
other.size.partial_cmp(&self.size)
}
}
impl Ord for HTTP_Request {
fn cmp(&self, other: &Self) -> Ordering {
other.size.cmp(&self.size)
}
}
struct WebServer {
ip: String,
port: usize,
www_dir_path: Path,
request_queue_arc: Arc<Mutex<BinaryHeap<HTTP_Request>>>,
stream_map_arc: Arc<Mutex<HashMap<String, std::old_io::net::tcp::TcpStream>>>,
//make an arc containing a Map to store files- this acts as a cache
cached_files_arc: Arc<Mutex<HashMap<String, Vec<u8>>>>,
being_read_arc: Arc<Mutex<HashMap<String, String>>>, //for files in process of being read
notify_rx: Receiver<()>,
notify_tx: Sender<()>,
}
impl WebServer {
fn new(ip: String, port: usize, www_dir: String) -> WebServer {
let (notify_tx, notify_rx) = channel();
let www_dir_path = Path::new(www_dir);
os::change_dir(&www_dir_path);
WebServer {
ip:ip,
port: port,
www_dir_path: www_dir_path,
request_queue_arc: Arc::new(Mutex::new(BinaryHeap::new())),
stream_map_arc: Arc::new(Mutex::new(HashMap::new())),
cached_files_arc: Arc::new(Mutex::new(HashMap::new())),
being_read_arc: Arc::new(Mutex::new(HashMap::new())),
notify_rx: notify_rx,
notify_tx: notify_tx,
}
}
fn run(&mut self) {
self.listen();
self.dequeue_static_file_request();
}
fn listen(&mut self) {
let addr = String::from_str(format!("{}:{}", self.ip, self.port).as_slice());
let www_dir_path_str = self.www_dir_path.clone();
let request_queue_arc = self.request_queue_arc.clone(); //tasks to schedule- want it to be a priority queue if static file, put in request queue and handles it single-threadedly
let notify_tx = self.notify_tx.clone();
let stream_map_arc = self.stream_map_arc.clone();
Thread::spawn(move|| {
let listener = std::old_io::TcpListener::bind(addr.as_slice()).unwrap();
let mut acceptor = listener.listen().unwrap();
println!("{} listening on {} (serving from: {}).",
SERVER_NAME, addr, www_dir_path_str.as_str().unwrap());
let mut visits = 0; //initialize visitor count as 0
for stream_raw in acceptor.incoming() {
visits += 1; //increment visits by 1 for every incoming request
let count = visits; //make Arc holding current num visitors
let (queue_tx, queue_rx) = channel();
queue_tx.send(request_queue_arc.clone());
let notify_chan = notify_tx.clone();
let stream_map_arc = stream_map_arc.clone();
// Spawn a task to handle the connection.
Thread::spawn(move|| {
//println!("visitor count is {}", local_count);
let request_queue_arc = queue_rx.recv().unwrap();
let mut stream = match stream_raw {
Ok(s) => {s}
Err(e) => { panic!("Error getting the listener stream! {}", e) }
};
let peer_name = WebServer::get_peer_name(&mut stream);
debug!("Got connection from {}", peer_name);
let mut buf: [u8;500] = [0;500];
stream.read(&mut buf);
|
let req_group: Vec<&str> = request_str.splitn(3,'').collect();
if req_group.len() > 2 {
let path_str = ".".to_string() + req_group[1];
let mut path_obj = os::getcwd().unwrap();
path_obj.push(path_str.clone());
let ext_str = match path_obj.extension_str() {
Some(e) => e,
None => "",
};
debug!("Requested path: [{}]", path_obj.as_str().expect("error"));
debug!("Requested path: [{}]", path_str);
//maybe spawn new threads here to deal with each request
if path_str.as_slice().eq("./") {
debug!("===== Counter Page request =====");
//send count of visitors to method with counter page
WebServer::respond_with_counter_page(stream, count);
debug!("=====Terminated connection from [{}].=====", peer_name);
} else if!path_obj.exists() || path_obj.is_dir() {
debug!("===== Error page request =====");
WebServer::respond_with_error_page(stream, &path_obj);
debug!("=====Terminated connection from [{}].=====", peer_name);
} else if ext_str == "shtml" { // Dynamic web pages.
debug!("===== Dynamic Page request =====");
WebServer::respond_with_dynamic_page(stream, &path_obj);
debug!("=====Terminated connection from [{}].=====", peer_name);
} else {
debug!("===== Static Page request =====");
WebServer::enqueue_static_file_request(stream, &path_obj, stream_map_arc, request_queue_arc, notify_chan);
}
}
});
}
});
}
fn respond_with_error_page(stream: std::old_io::net::tcp::TcpStream, path: &Path) {
let mut stream = stream;
let msg: String= format!("Cannot open: {}", path.as_str().expect("invalid path"));
stream.write(HTTP_BAD.as_bytes());
stream.write(msg.as_bytes());
}
// Safe visitor counter.
fn respond_with_counter_page(stream: std::old_io::net::tcp::TcpStream, local_count: usize) {
let mut stream = stream;
let response: String =
format!("{}{}<h1>Greetings, Krusty!</h1><h2>Visitor count: {}</h2></body></html>\r\n",
HTTP_OK, COUNTER_STYLE,
local_count);
debug!("Responding to counter request");
stream.write(response.as_bytes());
}
// TODO: Streaming file.
// TODO: Application-layer file caching.
fn respond_with_static_file(stream: std::old_io::net::tcp::TcpStream, path: &Path, cache: Arc<Mutex<HashMap<String, Vec<u8>>>>, being_read: Arc<Mutex<HashMap<String, String>>>) {
let mut timer = Timer::new().unwrap();
//boolean saying whether file in cache or not
let mut was_cached = 0;
let mut file_reader: File;
//first, get the map that stores all the files in cache, acquire lock, and set boolean indicating whether or not it was in cache
{
let mut cache_map = cache.lock().unwrap();
//path as string is key for cached file
let fname = path.as_str().unwrap();
//if file is in cache, set was_cached to "true" (1)
if cache_map.contains_key(fname) {
println!("in cache");
was_cached = 1;
}
}
let fname = path.as_str().unwrap();
let f_string = fname.to_string();
let read_val = "reading".to_string();
let mut being_read_bool = 0;
//if file was not in the cache, but is in process of being read
//by another thread, other threads should busy wait for file to be
//put in cache
{
let mut reading = being_read.lock().unwrap();
if reading.contains_key(fname) {
println!("file currently being read from disk");
being_read_bool = 1;
}
}
//if file was not in cache, but is currently being read from disk
//other threads trying to get the file should spin until in cache
if was_cached == 0 && being_read_bool == 1
{
while being_read_bool == 1 {
{
//within busy wait, check being_read periodically
let mut reading = being_read.lock().unwrap();
if!reading.contains_key(fname)
{
//when no longer being read, set being_read to false
being_read_bool = 0;
was_cached = 1; //and, the file is now in cache
//println!("still being read...");
}
}
//sleep me so it's not constantly checking the counter
timer.sleep(Duration::milliseconds(10));
}
}
//if file wasn't in cache, read from disk
if was_cached == 0 {
//was not cached, but about to be read from disk- put in being_read
{
let mut reading = being_read.lock().unwrap();
let f_string2 = fname.to_string();
reading.insert(f_string2, read_val);
}
//{
//let mut cache_map = cache.lock().unwrap();
//read from disk
println!("NOT in cache");
file_reader = File::open(path).unwrap();
let file_stats = file_reader.stat();
let file_size = file_stats.unwrap().size;
let mut reader = BufferedReader::new(file_reader);
let mut stream = stream;
stream.write(HTTP_OK.as_bytes());
//now stream file and also append it into contents- this can
//take a while especially for bigger files, but this does not
//happen within a lock, so other threads can run concurrently
//with this reading
let mut contents: Vec<u8> = Vec::with_capacity(file_size as usize);
for line in reader.lines().filter_map(|result| result.ok()) {
let l2 = line.clone();
let mut line_vec: Vec<u8> = line.into_bytes();
contents.append(&mut line_vec);
let _ = stream.write_all(l2.as_bytes());
}
//after read from disk, acquire lock and put file in cache
{
let mut cache_map = cache.lock().unwrap();
cache_map.insert(f_string, contents);
was_cached = 1;
//this file is no longer in the process of being read
let mut reading = being_read.lock().unwrap();
reading.remove(fname);
being_read_bool = 1;
}
}
//file was in cache- read it out of the cache
else{
let fname = path.as_str().unwrap();
println!("read from cache");
//acquire lock to read file out of cache
{
let mut cache_map = cache.lock().unwrap();
let mut file_reader_option = cache_map.get(fname);
let contents = file_reader_option.unwrap();
let mut stream = stream;
stream.write(HTTP_OK.as_bytes());
stream.write(contents.as_slice());
}
}
}
//Server-side gashing.
fn respond_with_dynamic_page(stream: std::old_io::net::tcp::TcpStream, path: &Path) {
// for now, just serve as static file
//WebServer::respond_with_static_file(stream, path);
let mut stream = stream;
let response = HTTP_OK;
//let mut resp: &str = "";
//let resp_str: String = ("").to_string();
let mut file = BufferedReader::new(File::open(path));
stream.write(response.as_bytes()); //start the stream with HTTP_OK
for line in file.lines(){
let l = line.unwrap();
let l_str: String = l.to_string();
let l_split = l_str.split_str("<!--#exec");
let l_vec = l_split.collect::<Vec<&str>>();
if l_vec.len() > 1 { //if there was an embedded shell command
//println!("shell command");
stream.write(l_vec[0].as_bytes());
let middle = l_vec[1];
let mid_split = middle.split_str("-->");
let mid_vec = mid_split.collect::<Vec<&str>>();
let in_quotes = mid_vec[0];
let openq_split = in_quotes.split_str("\"");
let openq_vec = openq_split.collect::<Vec<&str>>();
//println!("{}", openq_vec[1]);
//cmd for gash is in openq_vec[1]
let command = openq_vec[1];
//code below prints out results of Shell's running of embedded command
let cmd_result: Receiver<gash::Packet> = gash::Shell::new("").run_cmdline(command);
loop{
let test: gash::Packet = match cmd_result.recv(){
Err(why) => {break;},
Ok(res) => {res},
};
stream.write(test.to_string().as_bytes());
if test.end_of_stream {
break;
}
}
if l_vec.len() > 2 { //if there was more AFTER the embedded shell command
stream.write(l_vec[2].as_bytes());
}
} else { //if there was no embedded shell command, just write line
stream.write(l.as_bytes());
}
}
}
// TODO: Smarter Scheduling.
fn enqueue_static_file_request(stream: std::old_io::net::tcp::TcpStream, path_obj: &Path, stream_map_arc: Arc<Mutex<HashMap<String, std::old_io::net::tcp::TcpStream>>>, req_queue_arc: Arc<Mutex<BinaryHeap<HTTP_Request>>>, notify_chan: Sender<()>) {
// Save stream in hashmap for later response.
let mut stream = stream;
let peer_name = WebServer::get_peer_name(&mut stream);
let (stream_tx, stream_rx) = channel();
stream_tx.send(stream);
let stream = match stream_rx.recv(){
Ok(s) => s,
Err(e) => panic!("There was an error while receiving from the stream channel! {}", e),
};
let local_stream_map = stream_map_arc.clone();
{ // make sure we request the lock inside a block with different scope, so that we give it back at the end of that block
let mut local_stream_map = local_stream_map.lock().unwrap();
local_stream_map.insert(peer_name.clone(), stream);
}
// Enqueue the HTTP request.
// TOCHECK: it was ~path_obj.clone(), make sure in which order are ~ and clone() executed
let size = path_obj.stat().unwrap().size;
let req = HTTP_Request { peer_name: peer_name.clone(), path: path_obj.clone(), size: size };
let (req_tx, req_rx) = channel();
req_tx.send(req);
debug!("Waiting for queue mutex lock.");
let local_req_queue = req_queue_arc.clone();
{ // make sure we request the lock inside a block with different scope, so that we give it back at the end of that block
let mut local_req_queue = local_req_queue.lock().unwrap();
let req: HTTP_Request = match req_rx.recv(){
Ok(s) => s,
Err(e) => panic!("There was an error while receiving from the request channel! {}", e),
};
local_req_queue.push(req);
debug!("A new request enqueued, now the length of queue is {}.", local_req_queue.len());
notify_chan.send(()); // Send incoming notification to responder task.
}
}
// TODO: Smarter Scheduling.
fn dequeue_static_file_request(&mut self) {
let req_queue_get = self.request_queue_arc.clone();
let stream_map_get = self.stream_map_arc.clone();
// Receiver<> cannot be sent to another task. So we have to make this task as the main task that can access self.notify_rx.
let (request_tx, request_rx) = channel();
let mut thread_count = Arc::new(Mutex::new(0)); //count how many threads are running for tasks
let mut counter = 0;
let mut timer = Timer::new().unwrap();
loop
{
self.notify_rx.recv(); // waiting for new request enqueued.
{ // make sure we request the lock inside a block with different scope, so that we give it back at the end of that block
let mut req_queue = req_queue_get.lock().unwrap();
if req_queue.len() > 0 {
let req = req_queue.pop();
debug!("A new request dequeued, now the length of queue is {}.", req_queue.len());
request_tx.send(req);
}
}
let request = match request_rx.recv(){
Ok(s) => s.unwrap(),
Err(e) => panic!("There was an error while receiving from the request channel! {}", e),
};
// Get stream from hashmap.
let (stream_tx, stream_rx) = channel();
{ // make sure we request the lock inside a block with different scope, so that we give it back at the end of that block
let mut stream_map = stream_map_get.lock().unwrap();
let r2 = &request.peer_name;
//let r3 = &request.path;
//println!("next req is {:?}", r3);
let stream = stream_map.remove(r2).expect("no option tcpstream");
stream_tx.send(stream);
}
|
let request_str = match str::from_utf8(&buf){
Ok(s) => s,
Err(e)=> panic!("Error reading from the listener stream! {}", e),
};
debug!("Request:\n{}", request_str);
|
random_line_split
|
zhtta2.rs
|
/issues/12139)
peer_name: String,
path: Path,
size: u64,
}
//need to make it a min heap
impl PartialEq for HTTP_Request {
fn eq(&self, other: &Self) -> bool{
other.size == self.size
}
}
impl Eq for HTTP_Request {}
impl PartialOrd for HTTP_Request {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
other.size.partial_cmp(&self.size)
}
}
impl Ord for HTTP_Request {
fn cmp(&self, other: &Self) -> Ordering {
other.size.cmp(&self.size)
}
}
struct WebServer {
ip: String,
port: usize,
www_dir_path: Path,
request_queue_arc: Arc<Mutex<BinaryHeap<HTTP_Request>>>,
stream_map_arc: Arc<Mutex<HashMap<String, std::old_io::net::tcp::TcpStream>>>,
//make an arc containing a Map to store files- this acts as a cache
cached_files_arc: Arc<Mutex<HashMap<String, Vec<u8>>>>,
being_read_arc: Arc<Mutex<HashMap<String, String>>>, //for files in process of being read
notify_rx: Receiver<()>,
notify_tx: Sender<()>,
}
impl WebServer {
fn new(ip: String, port: usize, www_dir: String) -> WebServer {
let (notify_tx, notify_rx) = channel();
let www_dir_path = Path::new(www_dir);
os::change_dir(&www_dir_path);
WebServer {
ip:ip,
port: port,
www_dir_path: www_dir_path,
request_queue_arc: Arc::new(Mutex::new(BinaryHeap::new())),
stream_map_arc: Arc::new(Mutex::new(HashMap::new())),
cached_files_arc: Arc::new(Mutex::new(HashMap::new())),
being_read_arc: Arc::new(Mutex::new(HashMap::new())),
notify_rx: notify_rx,
notify_tx: notify_tx,
}
}
fn run(&mut self) {
self.listen();
self.dequeue_static_file_request();
}
fn listen(&mut self)
|
let notify_chan = notify_tx.clone();
let stream_map_arc = stream_map_arc.clone();
// Spawn a task to handle the connection.
Thread::spawn(move|| {
//println!("visitor count is {}", local_count);
let request_queue_arc = queue_rx.recv().unwrap();
let mut stream = match stream_raw {
Ok(s) => {s}
Err(e) => { panic!("Error getting the listener stream! {}", e) }
};
let peer_name = WebServer::get_peer_name(&mut stream);
debug!("Got connection from {}", peer_name);
let mut buf: [u8;500] = [0;500];
stream.read(&mut buf);
let request_str = match str::from_utf8(&buf){
Ok(s) => s,
Err(e)=> panic!("Error reading from the listener stream! {}", e),
};
debug!("Request:\n{}", request_str);
let req_group: Vec<&str> = request_str.splitn(3,'').collect();
if req_group.len() > 2 {
let path_str = ".".to_string() + req_group[1];
let mut path_obj = os::getcwd().unwrap();
path_obj.push(path_str.clone());
let ext_str = match path_obj.extension_str() {
Some(e) => e,
None => "",
};
debug!("Requested path: [{}]", path_obj.as_str().expect("error"));
debug!("Requested path: [{}]", path_str);
//maybe spawn new threads here to deal with each request
if path_str.as_slice().eq("./") {
debug!("===== Counter Page request =====");
//send count of visitors to method with counter page
WebServer::respond_with_counter_page(stream, count);
debug!("=====Terminated connection from [{}].=====", peer_name);
} else if!path_obj.exists() || path_obj.is_dir() {
debug!("===== Error page request =====");
WebServer::respond_with_error_page(stream, &path_obj);
debug!("=====Terminated connection from [{}].=====", peer_name);
} else if ext_str == "shtml" { // Dynamic web pages.
debug!("===== Dynamic Page request =====");
WebServer::respond_with_dynamic_page(stream, &path_obj);
debug!("=====Terminated connection from [{}].=====", peer_name);
} else {
debug!("===== Static Page request =====");
WebServer::enqueue_static_file_request(stream, &path_obj, stream_map_arc, request_queue_arc, notify_chan);
}
}
});
}
});
}
fn respond_with_error_page(stream: std::old_io::net::tcp::TcpStream, path: &Path) {
let mut stream = stream;
let msg: String= format!("Cannot open: {}", path.as_str().expect("invalid path"));
stream.write(HTTP_BAD.as_bytes());
stream.write(msg.as_bytes());
}
// Safe visitor counter.
fn respond_with_counter_page(stream: std::old_io::net::tcp::TcpStream, local_count: usize) {
let mut stream = stream;
let response: String =
format!("{}{}<h1>Greetings, Krusty!</h1><h2>Visitor count: {}</h2></body></html>\r\n",
HTTP_OK, COUNTER_STYLE,
local_count);
debug!("Responding to counter request");
stream.write(response.as_bytes());
}
// TODO: Streaming file.
// TODO: Application-layer file caching.
fn respond_with_static_file(stream: std::old_io::net::tcp::TcpStream, path: &Path, cache: Arc<Mutex<HashMap<String, Vec<u8>>>>, being_read: Arc<Mutex<HashMap<String, String>>>) {
let mut timer = Timer::new().unwrap();
//boolean saying whether file in cache or not
let mut was_cached = 0;
let mut file_reader: File;
//first, get the map that stores all the files in cache, acquire lock, and set boolean indicating whether or not it was in cache
{
let mut cache_map = cache.lock().unwrap();
//path as string is key for cached file
let fname = path.as_str().unwrap();
//if file is in cache, set was_cached to "true" (1)
if cache_map.contains_key(fname) {
println!("in cache");
was_cached = 1;
}
}
let fname = path.as_str().unwrap();
let f_string = fname.to_string();
let read_val = "reading".to_string();
let mut being_read_bool = 0;
//if file was not in the cache, but is in process of being read
//by another thread, other threads should busy wait for file to be
//put in cache
{
let mut reading = being_read.lock().unwrap();
if reading.contains_key(fname) {
println!("file currently being read from disk");
being_read_bool = 1;
}
}
//if file was not in cache, but is currently being read from disk
//other threads trying to get the file should spin until in cache
if was_cached == 0 && being_read_bool == 1
{
while being_read_bool == 1 {
{
//within busy wait, check being_read periodically
let mut reading = being_read.lock().unwrap();
if!reading.contains_key(fname)
{
//when no longer being read, set being_read to false
being_read_bool = 0;
was_cached = 1; //and, the file is now in cache
//println!("still being read...");
}
}
//sleep me so it's not constantly checking the counter
timer.sleep(Duration::milliseconds(10));
}
}
//if file wasn't in cache, read from disk
if was_cached == 0 {
//was not cached, but about to be read from disk- put in being_read
{
let mut reading = being_read.lock().unwrap();
let f_string2 = fname.to_string();
reading.insert(f_string2, read_val);
}
//{
//let mut cache_map = cache.lock().unwrap();
//read from disk
println!("NOT in cache");
file_reader = File::open(path).unwrap();
let file_stats = file_reader.stat();
let file_size = file_stats.unwrap().size;
let mut reader = BufferedReader::new(file_reader);
let mut stream = stream;
stream.write(HTTP_OK.as_bytes());
//now stream file and also append it into contents- this can
//take a while especially for bigger files, but this does not
//happen within a lock, so other threads can run concurrently
//with this reading
let mut contents: Vec<u8> = Vec::with_capacity(file_size as usize);
for line in reader.lines().filter_map(|result| result.ok()) {
let l2 = line.clone();
let mut line_vec: Vec<u8> = line.into_bytes();
contents.append(&mut line_vec);
let _ = stream.write_all(l2.as_bytes());
}
//after read from disk, acquire lock and put file in cache
{
let mut cache_map = cache.lock().unwrap();
cache_map.insert(f_string, contents);
was_cached = 1;
//this file is no longer in the process of being read
let mut reading = being_read.lock().unwrap();
reading.remove(fname);
being_read_bool = 1;
}
}
//file was in cache- read it out of the cache
else{
let fname = path.as_str().unwrap();
println!("read from cache");
//acquire lock to read file out of cache
{
let mut cache_map = cache.lock().unwrap();
let mut file_reader_option = cache_map.get(fname);
let contents = file_reader_option.unwrap();
let mut stream = stream;
stream.write(HTTP_OK.as_bytes());
stream.write(contents.as_slice());
}
}
}
//Server-side gashing.
fn respond_with_dynamic_page(stream: std::old_io::net::tcp::TcpStream, path: &Path) {
// for now, just serve as static file
//WebServer::respond_with_static_file(stream, path);
let mut stream = stream;
let response = HTTP_OK;
//let mut resp: &str = "";
//let resp_str: String = ("").to_string();
let mut file = BufferedReader::new(File::open(path));
stream.write(response.as_bytes()); //start the stream with HTTP_OK
for line in file.lines(){
let l = line.unwrap();
let l_str: String = l.to_string();
let l_split = l_str.split_str("<!--#exec");
let l_vec = l_split.collect::<Vec<&str>>();
if l_vec.len() > 1 { //if there was an embedded shell command
//println!("shell command");
stream.write(l_vec[0].as_bytes());
let middle = l_vec[1];
let mid_split = middle.split_str("-->");
let mid_vec = mid_split.collect::<Vec<&str>>();
let in_quotes = mid_vec[0];
let openq_split = in_quotes.split_str("\"");
let openq_vec = openq_split.collect::<Vec<&str>>();
//println!("{}", openq_vec[1]);
//cmd for gash is in openq_vec[1]
let command = openq_vec[1];
//code below prints out results of Shell's running of embedded command
let cmd_result: Receiver<gash::Packet> = gash::Shell::new("").run_cmdline(command);
loop{
let test: gash::Packet = match cmd_result.recv(){
Err(why) => {break;},
Ok(res) => {res},
};
stream.write(test.to_string().as_bytes());
if test.end_of_stream {
break;
}
}
if l_vec.len() > 2 { //if there was more AFTER the embedded shell command
stream.write(l_vec[2].as_bytes());
}
} else { //if there was no embedded shell command, just write line
stream.write(l.as_bytes());
}
}
}
// TODO: Smarter Scheduling.
fn enqueue_static_file_request(stream: std::old_io::net::tcp::TcpStream, path_obj: &Path, stream_map_arc: Arc<Mutex<HashMap<String, std::old_io::net::tcp::TcpStream>>>, req_queue_arc: Arc<Mutex<BinaryHeap<HTTP_Request>>>, notify_chan: Sender<()>) {
// Save stream in hashmap for later response.
let mut stream = stream;
let peer_name = WebServer::get_peer_name(&mut stream);
let (stream_tx, stream_rx) = channel();
stream_tx.send(stream);
let stream = match stream_rx.recv(){
Ok(s) => s,
Err(e) => panic!("There was an error while receiving from the stream channel! {}", e),
};
let local_stream_map = stream_map_arc.clone();
{ // make sure we request the lock inside a block with different scope, so that we give it back at the end of that block
let mut local_stream_map = local_stream_map.lock().unwrap();
local_stream_map.insert(peer_name.clone(), stream);
}
// Enqueue the HTTP request.
// TOCHECK: it was ~path_obj.clone(), make sure in which order are ~ and clone() executed
let size = path_obj.stat().unwrap().size;
let req = HTTP_Request { peer_name: peer_name.clone(), path: path_obj.clone(), size: size };
let (req_tx, req_rx) = channel();
req_tx.send(req);
debug!("Waiting for queue mutex lock.");
let local_req_queue = req_queue_arc.clone();
{ // make sure we request the lock inside a block with different scope, so that we give it back at the end of that block
let mut local_req_queue = local_req_queue.lock().unwrap();
let req: HTTP_Request = match req_rx.recv(){
Ok(s) => s,
Err(e) => panic!("There was an error while receiving from the request channel! {}", e),
};
local_req_queue.push(req);
debug!("A new request enqueued, now the length of queue is {}.", local_req_queue.len());
notify_chan.send(()); // Send incoming notification to responder task.
}
}
// TODO: Smarter Scheduling.
fn dequeue_static_file_request(&mut self) {
let req_queue_get = self.request_queue_arc.clone();
let stream_map_get = self.stream_map_arc.clone();
// Receiver<> cannot be sent to another task. So we have to make this task as the main task that can access self.notify_rx.
let (request_tx, request_rx) = channel();
let mut thread_count = Arc::new(Mutex::new(0)); //count how many threads are running for tasks
let mut counter = 0;
let mut timer = Timer::new().unwrap();
loop
{
self.notify_rx.recv(); // waiting for new request enqueued.
{ // make sure we request the lock inside a block with different scope, so that we give it back at the end of that block
let mut req_queue = req_queue_get.lock().unwrap();
if req_queue.len() > 0 {
let req = req_queue.pop();
debug!("A new request dequeued, now the length of queue is {}.", req_queue.len());
request_tx.send(req);
}
}
let request = match request_rx.recv(){
Ok(s) => s.unwrap(),
Err(e) => panic!("There was an error while receiving from the request channel! {}", e),
};
// Get stream from hashmap.
let (stream_tx, stream_rx) = channel();
{ // make sure we request the lock inside a block with different scope, so that we give it back at the end of that block
let mut stream_map = stream_map_get.lock().unwrap();
let r2 = &request.peer_name;
//let r3 = &request.path;
//println!("next req is {:?}", r3);
let stream = stream_map.remove(r2).expect("no option tcpstream");
stream_tx.send(stream);
|
{
let addr = String::from_str(format!("{}:{}", self.ip, self.port).as_slice());
let www_dir_path_str = self.www_dir_path.clone();
let request_queue_arc = self.request_queue_arc.clone(); //tasks to schedule- want it to be a priority queue if static file, put in request queue and handles it single-threadedly
let notify_tx = self.notify_tx.clone();
let stream_map_arc = self.stream_map_arc.clone();
Thread::spawn(move|| {
let listener = std::old_io::TcpListener::bind(addr.as_slice()).unwrap();
let mut acceptor = listener.listen().unwrap();
println!("{} listening on {} (serving from: {}).",
SERVER_NAME, addr, www_dir_path_str.as_str().unwrap());
let mut visits = 0; //initialize visitor count as 0
for stream_raw in acceptor.incoming() {
visits += 1; //increment visits by 1 for every incoming request
let count = visits; //make Arc holding current num visitors
let (queue_tx, queue_rx) = channel();
queue_tx.send(request_queue_arc.clone());
|
identifier_body
|
saturating_square.rs
|
use malachite_base::num::basic::integers::PrimitiveInt;
|
use malachite_base_test_util::generators::{signed_gen, unsigned_gen};
#[test]
fn test_saturating_square() {
fn test<T: PrimitiveInt>(x: T, out: T) {
assert_eq!(x.saturating_square(), out);
let mut x = x;
x.saturating_square_assign();
assert_eq!(x, out);
}
test::<u8>(0, 0);
test::<i16>(1, 1);
test::<u32>(2, 4);
test::<i64>(3, 9);
test::<u128>(10, 100);
test::<isize>(123, 15129);
test::<u32>(1000, 1000000);
test::<i16>(-1, 1);
test::<i32>(-2, 4);
test::<i64>(-3, 9);
test::<i128>(-10, 100);
test::<isize>(-123, 15129);
test::<i32>(-1000, 1000000);
test::<u16>(1000, u16::MAX);
test::<i16>(-1000, i16::MAX);
}
fn saturating_square_properties_helper_unsigned<T: PrimitiveUnsigned>() {
unsigned_gen::<T>().test_properties(|x| {
let mut square = x;
square.saturating_square_assign();
assert_eq!(square, x.saturating_square());
assert_eq!(square, x.saturating_pow(2));
assert!(square >= x);
if square < T::MAX {
assert_eq!(square, x.square());
}
});
}
fn saturating_square_properties_helper_signed<T: PrimitiveSigned>() {
signed_gen::<T>().test_properties(|x| {
let mut square = x;
square.saturating_square_assign();
assert_eq!(square, x.saturating_square());
assert_eq!(square, x.saturating_pow(2));
if square > T::MIN && square < T::MAX {
assert_eq!(square, x.square());
}
});
}
#[test]
fn saturating_square_properties() {
apply_fn_to_unsigneds!(saturating_square_properties_helper_unsigned);
apply_fn_to_signeds!(saturating_square_properties_helper_signed);
}
|
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
|
random_line_split
|
saturating_square.rs
|
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{signed_gen, unsigned_gen};
#[test]
fn test_saturating_square() {
fn test<T: PrimitiveInt>(x: T, out: T) {
assert_eq!(x.saturating_square(), out);
let mut x = x;
x.saturating_square_assign();
assert_eq!(x, out);
}
test::<u8>(0, 0);
test::<i16>(1, 1);
test::<u32>(2, 4);
test::<i64>(3, 9);
test::<u128>(10, 100);
test::<isize>(123, 15129);
test::<u32>(1000, 1000000);
test::<i16>(-1, 1);
test::<i32>(-2, 4);
test::<i64>(-3, 9);
test::<i128>(-10, 100);
test::<isize>(-123, 15129);
test::<i32>(-1000, 1000000);
test::<u16>(1000, u16::MAX);
test::<i16>(-1000, i16::MAX);
}
fn saturating_square_properties_helper_unsigned<T: PrimitiveUnsigned>() {
unsigned_gen::<T>().test_properties(|x| {
let mut square = x;
square.saturating_square_assign();
assert_eq!(square, x.saturating_square());
assert_eq!(square, x.saturating_pow(2));
assert!(square >= x);
if square < T::MAX {
assert_eq!(square, x.square());
}
});
}
fn saturating_square_properties_helper_signed<T: PrimitiveSigned>()
|
#[test]
fn saturating_square_properties() {
apply_fn_to_unsigneds!(saturating_square_properties_helper_unsigned);
apply_fn_to_signeds!(saturating_square_properties_helper_signed);
}
|
{
signed_gen::<T>().test_properties(|x| {
let mut square = x;
square.saturating_square_assign();
assert_eq!(square, x.saturating_square());
assert_eq!(square, x.saturating_pow(2));
if square > T::MIN && square < T::MAX {
assert_eq!(square, x.square());
}
});
}
|
identifier_body
|
saturating_square.rs
|
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{signed_gen, unsigned_gen};
#[test]
fn test_saturating_square() {
fn test<T: PrimitiveInt>(x: T, out: T) {
assert_eq!(x.saturating_square(), out);
let mut x = x;
x.saturating_square_assign();
assert_eq!(x, out);
}
test::<u8>(0, 0);
test::<i16>(1, 1);
test::<u32>(2, 4);
test::<i64>(3, 9);
test::<u128>(10, 100);
test::<isize>(123, 15129);
test::<u32>(1000, 1000000);
test::<i16>(-1, 1);
test::<i32>(-2, 4);
test::<i64>(-3, 9);
test::<i128>(-10, 100);
test::<isize>(-123, 15129);
test::<i32>(-1000, 1000000);
test::<u16>(1000, u16::MAX);
test::<i16>(-1000, i16::MAX);
}
fn saturating_square_properties_helper_unsigned<T: PrimitiveUnsigned>() {
unsigned_gen::<T>().test_properties(|x| {
let mut square = x;
square.saturating_square_assign();
assert_eq!(square, x.saturating_square());
assert_eq!(square, x.saturating_pow(2));
assert!(square >= x);
if square < T::MAX
|
});
}
fn saturating_square_properties_helper_signed<T: PrimitiveSigned>() {
signed_gen::<T>().test_properties(|x| {
let mut square = x;
square.saturating_square_assign();
assert_eq!(square, x.saturating_square());
assert_eq!(square, x.saturating_pow(2));
if square > T::MIN && square < T::MAX {
assert_eq!(square, x.square());
}
});
}
#[test]
fn saturating_square_properties() {
apply_fn_to_unsigneds!(saturating_square_properties_helper_unsigned);
apply_fn_to_signeds!(saturating_square_properties_helper_signed);
}
|
{
assert_eq!(square, x.square());
}
|
conditional_block
|
saturating_square.rs
|
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::signeds::PrimitiveSigned;
use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{signed_gen, unsigned_gen};
#[test]
fn test_saturating_square() {
fn test<T: PrimitiveInt>(x: T, out: T) {
assert_eq!(x.saturating_square(), out);
let mut x = x;
x.saturating_square_assign();
assert_eq!(x, out);
}
test::<u8>(0, 0);
test::<i16>(1, 1);
test::<u32>(2, 4);
test::<i64>(3, 9);
test::<u128>(10, 100);
test::<isize>(123, 15129);
test::<u32>(1000, 1000000);
test::<i16>(-1, 1);
test::<i32>(-2, 4);
test::<i64>(-3, 9);
test::<i128>(-10, 100);
test::<isize>(-123, 15129);
test::<i32>(-1000, 1000000);
test::<u16>(1000, u16::MAX);
test::<i16>(-1000, i16::MAX);
}
fn saturating_square_properties_helper_unsigned<T: PrimitiveUnsigned>() {
unsigned_gen::<T>().test_properties(|x| {
let mut square = x;
square.saturating_square_assign();
assert_eq!(square, x.saturating_square());
assert_eq!(square, x.saturating_pow(2));
assert!(square >= x);
if square < T::MAX {
assert_eq!(square, x.square());
}
});
}
fn saturating_square_properties_helper_signed<T: PrimitiveSigned>() {
signed_gen::<T>().test_properties(|x| {
let mut square = x;
square.saturating_square_assign();
assert_eq!(square, x.saturating_square());
assert_eq!(square, x.saturating_pow(2));
if square > T::MIN && square < T::MAX {
assert_eq!(square, x.square());
}
});
}
#[test]
fn
|
() {
apply_fn_to_unsigneds!(saturating_square_properties_helper_unsigned);
apply_fn_to_signeds!(saturating_square_properties_helper_signed);
}
|
saturating_square_properties
|
identifier_name
|
program.rs
|
use num_bigint::BigInt;
use std::rc::Rc;
use std::ops::Range;
use std::collections::HashMap;
use label::Label;
pub use ::Program;
#[derive(Debug, Clone)]
pub struct SourceLoc {
pub line: usize,
pub column: usize,
|
#[derive(Debug, Clone)]
pub enum Command {
Push {value: Integer},
PushBig {value: BigInteger},
Duplicate,
Copy {index: usize},
Swap,
Discard,
Slide {amount: usize},
Add,
Subtract,
Multiply,
Divide,
Modulo,
Set,
Get,
Label,
Call {index: usize},
Jump {index: usize},
JumpIfZero {index: usize},
JumpIfNegative {index: usize},
EndSubroutine,
EndProgram,
PrintChar,
PrintNum,
InputChar,
InputNum
}
pub type Integer = isize;
pub type BigInteger = BigInt;
#[derive(Debug, Clone)]
pub enum SizedInteger {
Big(BigInteger),
Small(Integer)
}
impl Program {
/// Remove source location information from the program.
pub fn strip(&mut self) {
self.source = None;
self.locs = None;
}
/// Rewrites labels to ensure the resulting program is as small as possible.
pub fn minify(&mut self) {
// get the source locs, otherwise, invent some new sourcelocs.
let locs = if let Some(ref mut locs) = self.locs {
locs
} else {
self.locs = Some(self.commands.iter().map(|_| SourceLoc {line: 0, column: 0, span: 0..0, label: None}).collect());
self.locs.as_mut().unwrap()
};
// create an index => times_used map
let mut label_count = HashMap::new();
for (i, op) in self.commands.iter().enumerate() {
match *op {
Command::Label => *label_count.entry(i + 1).or_insert(0) += 1,
Command::Call {index}
| Command::Jump {index}
| Command::JumpIfZero {index}
| Command::JumpIfNegative {index} => *label_count.entry(index).or_insert(0) += 1,
_ => ()
}
}
// turn the map into a list of (index, times_used) that is sorted by times_used
let mut label_count: Vec<_> = label_count.into_iter().collect();
label_count.sort_by_key(|&(_, w)| w);
// create an allocator that produces unique labels, starting from the smallest possible label
let mut length = 0usize;
let mut value = 0usize;
let mut new_label = || {
// create label
let mut label = Label::new();
for i in 0..length {
label.push(value & (1 << i)!= 0);
}
// increment state
value += 1;
if value == (1 << length) {
length += 1;
value = 0;
}
Rc::new(label)
};
// from the sorted list, create a map of index => new_label
let label_map: HashMap<_, _> = label_count.iter().rev().map(|&(i, _)| (i, new_label())).collect();
// and edit locs using them.
for ((i, op), loc) in self.commands.iter().enumerate().zip(locs) {
match *op {
Command::Label => loc.label = Some(label_map[&(i + 1)].clone()),
Command::Call {index}
| Command::Jump {index}
| Command::JumpIfZero {index}
| Command::JumpIfNegative {index} => loc.label = Some(label_map[&index].clone()),
_ => ()
}
}
}
}
|
pub span: Range<usize>,
pub label: Option<Rc<Label>>
}
|
random_line_split
|
program.rs
|
use num_bigint::BigInt;
use std::rc::Rc;
use std::ops::Range;
use std::collections::HashMap;
use label::Label;
pub use ::Program;
#[derive(Debug, Clone)]
pub struct SourceLoc {
pub line: usize,
pub column: usize,
pub span: Range<usize>,
pub label: Option<Rc<Label>>
}
#[derive(Debug, Clone)]
pub enum Command {
Push {value: Integer},
PushBig {value: BigInteger},
Duplicate,
Copy {index: usize},
Swap,
Discard,
Slide {amount: usize},
Add,
Subtract,
Multiply,
Divide,
Modulo,
Set,
Get,
Label,
Call {index: usize},
Jump {index: usize},
JumpIfZero {index: usize},
JumpIfNegative {index: usize},
EndSubroutine,
EndProgram,
PrintChar,
PrintNum,
InputChar,
InputNum
}
pub type Integer = isize;
pub type BigInteger = BigInt;
#[derive(Debug, Clone)]
pub enum SizedInteger {
Big(BigInteger),
Small(Integer)
}
impl Program {
/// Remove source location information from the program.
pub fn strip(&mut self) {
self.source = None;
self.locs = None;
}
/// Rewrites labels to ensure the resulting program is as small as possible.
pub fn minify(&mut self)
|
}
// turn the map into a list of (index, times_used) that is sorted by times_used
let mut label_count: Vec<_> = label_count.into_iter().collect();
label_count.sort_by_key(|&(_, w)| w);
// create an allocator that produces unique labels, starting from the smallest possible label
let mut length = 0usize;
let mut value = 0usize;
let mut new_label = || {
// create label
let mut label = Label::new();
for i in 0..length {
label.push(value & (1 << i)!= 0);
}
// increment state
value += 1;
if value == (1 << length) {
length += 1;
value = 0;
}
Rc::new(label)
};
// from the sorted list, create a map of index => new_label
let label_map: HashMap<_, _> = label_count.iter().rev().map(|&(i, _)| (i, new_label())).collect();
// and edit locs using them.
for ((i, op), loc) in self.commands.iter().enumerate().zip(locs) {
match *op {
Command::Label => loc.label = Some(label_map[&(i + 1)].clone()),
Command::Call {index}
| Command::Jump {index}
| Command::JumpIfZero {index}
| Command::JumpIfNegative {index} => loc.label = Some(label_map[&index].clone()),
_ => ()
}
}
}
}
|
{
// get the source locs, otherwise, invent some new sourcelocs.
let locs = if let Some(ref mut locs) = self.locs {
locs
} else {
self.locs = Some(self.commands.iter().map(|_| SourceLoc {line: 0, column: 0, span: 0..0, label: None}).collect());
self.locs.as_mut().unwrap()
};
// create an index => times_used map
let mut label_count = HashMap::new();
for (i, op) in self.commands.iter().enumerate() {
match *op {
Command::Label => *label_count.entry(i + 1).or_insert(0) += 1,
Command::Call {index}
| Command::Jump {index}
| Command::JumpIfZero {index}
| Command::JumpIfNegative {index} => *label_count.entry(index).or_insert(0) += 1,
_ => ()
}
|
identifier_body
|
program.rs
|
use num_bigint::BigInt;
use std::rc::Rc;
use std::ops::Range;
use std::collections::HashMap;
use label::Label;
pub use ::Program;
#[derive(Debug, Clone)]
pub struct SourceLoc {
pub line: usize,
pub column: usize,
pub span: Range<usize>,
pub label: Option<Rc<Label>>
}
#[derive(Debug, Clone)]
pub enum
|
{
Push {value: Integer},
PushBig {value: BigInteger},
Duplicate,
Copy {index: usize},
Swap,
Discard,
Slide {amount: usize},
Add,
Subtract,
Multiply,
Divide,
Modulo,
Set,
Get,
Label,
Call {index: usize},
Jump {index: usize},
JumpIfZero {index: usize},
JumpIfNegative {index: usize},
EndSubroutine,
EndProgram,
PrintChar,
PrintNum,
InputChar,
InputNum
}
pub type Integer = isize;
pub type BigInteger = BigInt;
#[derive(Debug, Clone)]
pub enum SizedInteger {
Big(BigInteger),
Small(Integer)
}
impl Program {
/// Remove source location information from the program.
pub fn strip(&mut self) {
self.source = None;
self.locs = None;
}
/// Rewrites labels to ensure the resulting program is as small as possible.
pub fn minify(&mut self) {
// get the source locs, otherwise, invent some new sourcelocs.
let locs = if let Some(ref mut locs) = self.locs {
locs
} else {
self.locs = Some(self.commands.iter().map(|_| SourceLoc {line: 0, column: 0, span: 0..0, label: None}).collect());
self.locs.as_mut().unwrap()
};
// create an index => times_used map
let mut label_count = HashMap::new();
for (i, op) in self.commands.iter().enumerate() {
match *op {
Command::Label => *label_count.entry(i + 1).or_insert(0) += 1,
Command::Call {index}
| Command::Jump {index}
| Command::JumpIfZero {index}
| Command::JumpIfNegative {index} => *label_count.entry(index).or_insert(0) += 1,
_ => ()
}
}
// turn the map into a list of (index, times_used) that is sorted by times_used
let mut label_count: Vec<_> = label_count.into_iter().collect();
label_count.sort_by_key(|&(_, w)| w);
// create an allocator that produces unique labels, starting from the smallest possible label
let mut length = 0usize;
let mut value = 0usize;
let mut new_label = || {
// create label
let mut label = Label::new();
for i in 0..length {
label.push(value & (1 << i)!= 0);
}
// increment state
value += 1;
if value == (1 << length) {
length += 1;
value = 0;
}
Rc::new(label)
};
// from the sorted list, create a map of index => new_label
let label_map: HashMap<_, _> = label_count.iter().rev().map(|&(i, _)| (i, new_label())).collect();
// and edit locs using them.
for ((i, op), loc) in self.commands.iter().enumerate().zip(locs) {
match *op {
Command::Label => loc.label = Some(label_map[&(i + 1)].clone()),
Command::Call {index}
| Command::Jump {index}
| Command::JumpIfZero {index}
| Command::JumpIfNegative {index} => loc.label = Some(label_map[&index].clone()),
_ => ()
}
}
}
}
|
Command
|
identifier_name
|
bios.rs
|
/* SPDX-License-Identifier: GPL-2.0-only */
use crate::consts::x86::*;
use crate::utils::round_up_4k;
use crate::MachVMBlock;
use std::mem::size_of;
use std::num::Wrapping;
// https://uefi.org/sites/default/files/resources/ACPI_6_3_May16.pdf
// Table 5-27 RSDP Structure
#[repr(packed)]
#[derive(Default)]
pub struct AcpiTableRsdp {
pub signature: [u8; 8], /* ACPI signature, contains "RSD PTR " */
pub checksum: u8, /* ACPI 1.0 checksum */
pub oem_id: [u8; 6], /* OEM identification */
pub revision: u8, /* Must be (0) for ACPI 1.0 or (2) for ACPI 2.0+ */
pub rsdt_physical_address: u32, /* 32-bit physical address of the RSDT */
pub length: u32, /* Table length in bytes, including header (ACPI 2.0+) */
pub xsdt_physical_address: u64, /* 64-bit physical address of the XSDT (ACPI 2.0+) */
pub extended_checksum: u8, /* Checksum of entire table (ACPI 2.0+) */
pub reserved: [u8; 3], /* Reserved, must be zero */
}
pub const ACPI_RSDP_CHECKSUM_LENGTH: usize = 20;
pub const ACPI_RSDP_XCHECKSUM_LENGTH: usize = 36;
pub const ACPI_RSDP_CHECKSUM_OFFSET: usize = 8;
pub const ACPI_RSDP_XCHECKSUM_OFFSET: usize = 32;
#[repr(packed)]
#[derive(Default)]
pub struct AcpiTableHeader {
pub signature: [u8; 4], /* ASCII table signature */
pub length: u32, /* Length of table in bytes, including this header */
pub revision: u8, /* ACPI Specification minor version number */
pub checksum: u8, /* To make sum of entire table == 0 */
pub oem_id: [u8; 6], /* ASCII OEM identification */
pub oem_table_id: [u8; 8], /* ASCII OEM table identification */
pub oem_revision: u32, /* OEM revision number */
pub asl_compiler_id: [u8; 4], /* ASCII ASL compiler vendor ID */
pub asl_compiler_revision: u32, /* ASL compiler version */
}
pub const ACPI_TABLE_HEADER_CHECKSUM_OFFSET: usize = 9;
impl AcpiTableHeader {
pub fn new() -> Self {
AcpiTableHeader {
revision: 2,
checksum: 0,
oem_id: *b"AKAROS",
oem_table_id: *b"ALPHABET",
oem_revision: 0,
asl_compiler_id: *b"RON ",
asl_compiler_revision: 0,
..Default::default()
}
}
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiTableXsdt {
pub header: AcpiTableHeader, /* Common ACPI table header */
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiGenericAddress {
pub space_id: u8, /* Address space where pub struct or register exists */
pub bit_width: u8, /* Size in bits of given register */
pub bit_offset: u8, /* Bit offset within the register */
pub access_width: u8, /* Minimum Access size (ACPI 3.0) */
pub address: u64, /* 64-bit address of pub struct or register */
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiTableFadt {
pub header: AcpiTableHeader, /* Common ACPI table header */
pub facs: u32, /* 32-bit physical address of FACS */
pub dsdt: u32, /* 32-bit physical address of DSDT */
pub model: u8, /* System Interrupt Model (ACPI 1.0) - not used in ACPI 2.0+ */
pub preferred_profile: u8, /* Conveys preferred power management profile to OSPM. */
pub sci_interrupt: u16, /* System vector of SCI interrupt */
pub smi_command: u32, /* 32-bit Port address of SMI command port */
pub acpi_enable: u8, /* Value to write to SMI_CMD to enable ACPI */
pub acpi_disable: u8, /* Value to write to SMI_CMD to disable ACPI */
pub s4_bios_request: u8, /* Value to write to SMI_CMD to enter S4BIOS state */
pub pstate_control: u8, /* Processor performance state control */
pub pm1a_event_block: u32, /* 32-bit port address of Power Mgt 1a Event Reg Blk */
pub pm1b_event_block: u32, /* 32-bit port address of Power Mgt 1b Event Reg Blk */
pub pm1a_control_block: u32, /* 32-bit port address of Power Mgt 1a Control Reg Blk */
pub pm1b_control_block: u32, /* 32-bit port address of Power Mgt 1b Control Reg Blk */
pub pm2_control_block: u32, /* 32-bit port address of Power Mgt 2 Control Reg Blk */
pub pm_timer_block: u32, /* 32-bit port address of Power Mgt Timer Ctrl Reg Blk */
pub gpe0_block: u32, /* 32-bit port address of General Purpose Event 0 Reg Blk */
pub gpe1_block: u32, /* 32-bit port address of General Purpose Event 1 Reg Blk */
pub pm1_event_length: u8, /* Byte Length of ports at pm1x_event_block */
pub pm1_control_length: u8, /* Byte Length of ports at pm1x_control_block */
pub pm2_control_length: u8, /* Byte Length of ports at pm2_control_block */
pub pm_timer_length: u8, /* Byte Length of ports at pm_timer_block */
pub gpe0_block_length: u8, /* Byte Length of ports at gpe0_block */
pub gpe1_block_length: u8, /* Byte Length of ports at gpe1_block */
pub gpe1_base: u8, /* Offset in GPE number space where GPE1 events start */
pub cst_control: u8, /* Support for the _CST object and C-States change notification */
pub c2_latency: u16, /* Worst case HW latency to enter/exit C2 state */
pub c3_latency: u16, /* Worst case HW latency to enter/exit C3 state */
pub flush_size: u16, /* Processor memory cache line width, in bytes */
pub flush_stride: u16, /* Number of flush strides that need to be read */
pub duty_offset: u8, /* Processor duty cycle index in processor P_CNT reg */
pub duty_width: u8, /* Processor duty cycle value bit width in P_CNT register */
pub day_alarm: u8, /* Index to day-of-month alarm in RTC CMOS RAM */
pub month_alarm: u8, /* Index to month-of-year alarm in RTC CMOS RAM */
pub century: u8, /* Index to century in RTC CMOS RAM */
pub boot_flags: u16, /* IA-PC Boot Architecture Flags (see below for individual flags) */
pub reserved: u8, /* Reserved, must be zero */
pub flags: u32, /* Miscellaneous flag bits (see below for individual flags) */
pub reset_register: AcpiGenericAddress, /* 64-bit address of the Reset register */
pub reset_value: u8, /* Value to write to the reset_register port to reset the system */
pub arm_boot_flags: u16, /* ARM-Specific Boot Flags (see below for individual flags) (ACPI 5.1) */
pub minor_revision: u8, /* FADT Minor Revision (ACPI 5.1) */
pub xfacs: u64, /* 64-bit physical address of FACS */
pub xdsdt: u64, /* 64-bit physical address of DSDT */
pub xpm1a_event_block: AcpiGenericAddress, /* 64-bit Extended Power Mgt 1a Event Reg Blk address */
pub xpm1b_event_block: AcpiGenericAddress, /* 64-bit Extended Power Mgt 1b Event Reg Blk address */
pub xpm1a_control_block: AcpiGenericAddress, /* 64-bit Extended Power Mgt 1a Control Reg Blk address */
pub xpm1b_control_block: AcpiGenericAddress, /* 64-bit Extended Power Mgt 1b Control Reg Blk address */
pub xpm2_control_block: AcpiGenericAddress, /* 64-bit Extended Power Mgt 2 Control Reg Blk address */
pub xpm_timer_block: AcpiGenericAddress, /* 64-bit Extended Power Mgt Timer Ctrl Reg Blk address */
pub xgpe0_block: AcpiGenericAddress, /* 64-bit Extended General Purpose Event 0 Reg Blk address */
pub xgpe1_block: AcpiGenericAddress, /* 64-bit Extended General Purpose Event 1 Reg Blk address */
pub sleep_control: AcpiGenericAddress, /* 64-bit Sleep Control register (ACPI 5.0) */
pub sleep_status: AcpiGenericAddress, /* 64-bit Sleep Status register (ACPI 5.0) */
pub hypervisor_id: u64, /* Hypervisor Vendor ID (ACPI 6.0) */
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiTableMadt {
pub header: AcpiTableHeader, /* Common ACPI table header */
pub address: u32, /* Physical address of local APIC */
pub flags: u32,
}
#[repr(packed)]
#[derive(Default)]
|
pub length: u8,
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiMadtLocalApic {
pub header: AcpiSubtableHader,
pub processor_id: u8, /* ACPI processor id */
pub id: u8, /* Processor's local APIC id */
pub lapic_flags: u32,
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiMadtIoApic {
pub header: AcpiSubtableHader,
pub id: u8, /* I/O APIC ID */
pub reserved: u8, /* reserved - must be zero */
pub address: u32, /* APIC physical address */
pub global_irq_base: u32, /* Global system interrupt where INTI lines start */
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiMadtLocalX2apic {
pub header: AcpiSubtableHader,
pub reserved: u16, /* reserved - must be zero */
pub local_apic_id: u32, /* Processor x2APIC ID */
pub lapic_flags: u32,
pub uid: u32, /* ACPI processor UID */
}
/*
*
* Intel ACPI Component Architecture
* ASL Optimizing Compiler version 20140214-64 [Mar 29 2014]
* Copyright (c) 2000 - 2014 Intel Corporation
*
* Compilation of "vmm_acpi_dsdt.dsl" - Fri Apr 1 13:34:26 2016
*
*/
/*
*
* Based on the example at osdev wiki wiki.osdev.org/AML,
* and the other example in http://www.acpi.info/DOWNLOADS/ACPI_5_Errata%20A.pdf
* on page 194
*
* Compiled with `iasl -sc input_file.dsl`
*/
/*
* 9: DefinitionBlock (
* 10: "vmm_acpi_dsdt.aml", // Output AML Filename : String
* 11: "DSDT", // Signature : String
* 12: 0x2, // DSDT Compliance Revision : ByteConst
* 13: "MIKE", // OEMID : String
* 14: "DSDTTBL", // TABLE ID : String
* 15: 0x0 // OEM Revision : DWordConst
* 16: ){}
*/
pub const DSDT_DSDTTBL_HEADER: [u8; 36] = [
0x44, 0x53, 0x44, 0x54, 0x24, 0x00, 0x00, 0x00, /* 00000000 "DSDT$..." */
0x02, 0xF3, 0x4D, 0x49, 0x4B, 0x45, 0x00, 0x00, /* 00000008 "..MIKE.." */
0x44, 0x53, 0x44, 0x54, 0x54, 0x42, 0x4C, 0x00, /* 00000010 "DSDTTBL." */
0x00, 0x00, 0x00, 0x00, 0x49, 0x4E, 0x54, 0x4C, /* 00000018 "....INTL" */
0x14, 0x02, 0x14, 0x20, /* 00000020 "... " */
];
#[inline]
fn gencsum(data: &[u8]) -> u8 {
(!data.iter().map(|x| Wrapping(*x)).sum::<Wrapping<u8>>() + Wrapping(1)).0
}
#[inline]
fn acpi_tb_checksum(data: &[u8]) -> u8 {
data.iter().map(|x| Wrapping(*x)).sum::<Wrapping<u8>>().0
}
const SIG_RSDP: [u8; 8] = *b"RSD PTR ";
const SIG_XSDT: [u8; 4] = *b"XSDT";
const SIG_FADT: [u8; 4] = *b"FACP";
const SIG_MADT: [u8; 4] = *b"APIC";
const MADT_LOCAL_APIC: u8 = 0;
const MADT_IO_APIC: u8 = 1;
const MADT_LOCAL_X2APIC: u8 = 9;
/// Setup the BIOS tables in the low memory
///
/// `start` is the base address of the BIOS tables in the physical address space
/// of the guest. `low_mem` is a host virtual memory block which is mapped to
/// the lowest memory of the guest. `cores` is the number of logical CPUs of the guest.
/// Total number of bytes occupied by the BIOS tables is returned.
pub fn setup_bios_tables(start: usize, low_mem: &mut MachVMBlock, cores: u32) -> usize {
// calculate offsets first
// variables with suffix `_offset` mean the offset in `low_mem`. They are
// also the guest physical address of the corresponding tables, since `low_mem` is
// mapped to the lowest memory of the guest's physical address space.
let rsdp_offset = start;
let xsdt_offset = rsdp_offset + size_of::<AcpiTableRsdp>();
let xsdt_entry_offset = xsdt_offset + size_of::<AcpiTableHeader>();
const NUM_XSDT_ENTRIES: usize = 8;
let fadt_offset = xsdt_entry_offset + NUM_XSDT_ENTRIES * size_of::<u64>();
let dsdt_offset = fadt_offset + size_of::<AcpiTableFadt>();
let madt_offset = dsdt_offset + DSDT_DSDTTBL_HEADER.len();
let madt_local_apic_offset = madt_offset + size_of::<AcpiTableMadt>();
let io_apic_offset = madt_local_apic_offset + cores as usize * size_of::<AcpiMadtLocalApic>();
let local_x2apic_offset = io_apic_offset + size_of::<AcpiMadtIoApic>();
let total_size =
local_x2apic_offset + cores as usize * size_of::<AcpiMadtLocalX2apic>() - start;
// setup rsdp
let rdsp = AcpiTableRsdp {
signature: SIG_RSDP,
revision: 2,
length: 36,
xsdt_physical_address: xsdt_offset as u64,
..Default::default()
};
low_mem.write(rdsp, rsdp_offset, 0);
low_mem[rsdp_offset + ACPI_RSDP_CHECKSUM_OFFSET] =
gencsum(&low_mem[rsdp_offset..(rsdp_offset + ACPI_RSDP_CHECKSUM_LENGTH)]);
debug_assert_eq!(
acpi_tb_checksum(&low_mem[rsdp_offset..(rsdp_offset + ACPI_RSDP_CHECKSUM_LENGTH)]),
0
);
low_mem[rsdp_offset + ACPI_RSDP_XCHECKSUM_OFFSET] =
gencsum(&low_mem[rsdp_offset..(rsdp_offset + ACPI_RSDP_XCHECKSUM_LENGTH)]);
debug_assert_eq!(
acpi_tb_checksum(&low_mem[rsdp_offset..(rsdp_offset + ACPI_RSDP_XCHECKSUM_LENGTH)]),
0
);
// xsdt
let xsdt_total_length = size_of::<AcpiTableHeader>() + size_of::<u64>() * NUM_XSDT_ENTRIES;
let xsdt = AcpiTableHeader {
signature: SIG_XSDT,
length: xsdt_total_length as u32,
..AcpiTableHeader::new()
};
low_mem.write(xsdt, xsdt_offset, 0);
// xsdt entries
let mut xsdt_entries: [u64; NUM_XSDT_ENTRIES] = [0; NUM_XSDT_ENTRIES];
xsdt_entries[0] = fadt_offset as u64;
xsdt_entries[3] = madt_offset as u64;
low_mem.write(xsdt_entries, xsdt_entry_offset, 0);
low_mem[xsdt_offset + ACPI_TABLE_HEADER_CHECKSUM_OFFSET] =
gencsum(&low_mem[xsdt_offset..(xsdt_offset + xsdt_total_length)]);
debug_assert_eq!(
acpi_tb_checksum(&low_mem[xsdt_offset..(xsdt_offset + xsdt_total_length)]),
0
);
// fadt
let fadt = AcpiTableFadt {
header: AcpiTableHeader {
signature: SIG_FADT,
length: size_of::<AcpiTableFadt>() as u32,
..AcpiTableHeader::new()
},
xdsdt: dsdt_offset as u64,
..Default::default()
};
low_mem.write(fadt, fadt_offset, 0);
low_mem[fadt_offset + ACPI_TABLE_HEADER_CHECKSUM_OFFSET] =
gencsum(&low_mem[fadt_offset..(fadt_offset + size_of::<AcpiTableFadt>())]);
debug_assert_eq!(
acpi_tb_checksum(&low_mem[fadt_offset..(fadt_offset + size_of::<AcpiTableFadt>())]),
0
);
// dsdt
low_mem.write(DSDT_DSDTTBL_HEADER, dsdt_offset, 0);
// madt
let madt_total_length = size_of::<AcpiTableMadt>()
+ size_of::<AcpiMadtIoApic>()
+ cores as usize * (size_of::<AcpiMadtLocalApic>() + size_of::<AcpiMadtLocalX2apic>());
let madt = AcpiTableMadt {
header: AcpiTableHeader {
signature: SIG_MADT,
length: madt_total_length as u32,
..AcpiTableHeader::new()
},
address: APIC_BASE as u32,
flags: 0,
..Default::default()
};
low_mem.write(madt, madt_offset, 0);
// local apic
for i in 0..cores {
let lapic = AcpiMadtLocalApic {
header: AcpiSubtableHader {
r#type: MADT_LOCAL_APIC,
length: size_of::<AcpiMadtLocalApic>() as u8,
},
processor_id: i as u8,
id: i as u8,
lapic_flags: 1,
};
low_mem.write(lapic, madt_local_apic_offset, i as usize)
}
// io apiic
let io_apic = AcpiMadtIoApic {
header: AcpiSubtableHader {
r#type: MADT_IO_APIC,
length: size_of::<AcpiMadtIoApic>() as u8,
},
id: 0,
address: IO_APIC_BASE as u32,
global_irq_base: 0,
..Default::default()
};
low_mem.write(io_apic, io_apic_offset, 0);
// local x2apic
for i in 0..cores {
let x2apic = AcpiMadtLocalX2apic {
header: AcpiSubtableHader {
r#type: MADT_LOCAL_X2APIC,
length: size_of::<AcpiMadtLocalX2apic>() as u8,
},
local_apic_id: i,
uid: i,
lapic_flags: 1,
..Default::default()
};
low_mem.write(x2apic, local_x2apic_offset, i as usize)
}
low_mem[madt_offset + ACPI_TABLE_HEADER_CHECKSUM_OFFSET] =
gencsum(&low_mem[madt_offset..(madt_offset + madt_total_length)]);
debug_assert_eq!(
acpi_tb_checksum(&low_mem[madt_offset..(madt_offset + madt_total_length)]),
0
);
round_up_4k(total_size)
}
|
pub struct AcpiSubtableHader {
pub r#type: u8,
|
random_line_split
|
bios.rs
|
/* SPDX-License-Identifier: GPL-2.0-only */
use crate::consts::x86::*;
use crate::utils::round_up_4k;
use crate::MachVMBlock;
use std::mem::size_of;
use std::num::Wrapping;
// https://uefi.org/sites/default/files/resources/ACPI_6_3_May16.pdf
// Table 5-27 RSDP Structure
#[repr(packed)]
#[derive(Default)]
pub struct AcpiTableRsdp {
pub signature: [u8; 8], /* ACPI signature, contains "RSD PTR " */
pub checksum: u8, /* ACPI 1.0 checksum */
pub oem_id: [u8; 6], /* OEM identification */
pub revision: u8, /* Must be (0) for ACPI 1.0 or (2) for ACPI 2.0+ */
pub rsdt_physical_address: u32, /* 32-bit physical address of the RSDT */
pub length: u32, /* Table length in bytes, including header (ACPI 2.0+) */
pub xsdt_physical_address: u64, /* 64-bit physical address of the XSDT (ACPI 2.0+) */
pub extended_checksum: u8, /* Checksum of entire table (ACPI 2.0+) */
pub reserved: [u8; 3], /* Reserved, must be zero */
}
pub const ACPI_RSDP_CHECKSUM_LENGTH: usize = 20;
pub const ACPI_RSDP_XCHECKSUM_LENGTH: usize = 36;
pub const ACPI_RSDP_CHECKSUM_OFFSET: usize = 8;
pub const ACPI_RSDP_XCHECKSUM_OFFSET: usize = 32;
#[repr(packed)]
#[derive(Default)]
pub struct AcpiTableHeader {
pub signature: [u8; 4], /* ASCII table signature */
pub length: u32, /* Length of table in bytes, including this header */
pub revision: u8, /* ACPI Specification minor version number */
pub checksum: u8, /* To make sum of entire table == 0 */
pub oem_id: [u8; 6], /* ASCII OEM identification */
pub oem_table_id: [u8; 8], /* ASCII OEM table identification */
pub oem_revision: u32, /* OEM revision number */
pub asl_compiler_id: [u8; 4], /* ASCII ASL compiler vendor ID */
pub asl_compiler_revision: u32, /* ASL compiler version */
}
pub const ACPI_TABLE_HEADER_CHECKSUM_OFFSET: usize = 9;
impl AcpiTableHeader {
pub fn new() -> Self {
AcpiTableHeader {
revision: 2,
checksum: 0,
oem_id: *b"AKAROS",
oem_table_id: *b"ALPHABET",
oem_revision: 0,
asl_compiler_id: *b"RON ",
asl_compiler_revision: 0,
..Default::default()
}
}
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiTableXsdt {
pub header: AcpiTableHeader, /* Common ACPI table header */
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiGenericAddress {
pub space_id: u8, /* Address space where pub struct or register exists */
pub bit_width: u8, /* Size in bits of given register */
pub bit_offset: u8, /* Bit offset within the register */
pub access_width: u8, /* Minimum Access size (ACPI 3.0) */
pub address: u64, /* 64-bit address of pub struct or register */
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiTableFadt {
pub header: AcpiTableHeader, /* Common ACPI table header */
pub facs: u32, /* 32-bit physical address of FACS */
pub dsdt: u32, /* 32-bit physical address of DSDT */
pub model: u8, /* System Interrupt Model (ACPI 1.0) - not used in ACPI 2.0+ */
pub preferred_profile: u8, /* Conveys preferred power management profile to OSPM. */
pub sci_interrupt: u16, /* System vector of SCI interrupt */
pub smi_command: u32, /* 32-bit Port address of SMI command port */
pub acpi_enable: u8, /* Value to write to SMI_CMD to enable ACPI */
pub acpi_disable: u8, /* Value to write to SMI_CMD to disable ACPI */
pub s4_bios_request: u8, /* Value to write to SMI_CMD to enter S4BIOS state */
pub pstate_control: u8, /* Processor performance state control */
pub pm1a_event_block: u32, /* 32-bit port address of Power Mgt 1a Event Reg Blk */
pub pm1b_event_block: u32, /* 32-bit port address of Power Mgt 1b Event Reg Blk */
pub pm1a_control_block: u32, /* 32-bit port address of Power Mgt 1a Control Reg Blk */
pub pm1b_control_block: u32, /* 32-bit port address of Power Mgt 1b Control Reg Blk */
pub pm2_control_block: u32, /* 32-bit port address of Power Mgt 2 Control Reg Blk */
pub pm_timer_block: u32, /* 32-bit port address of Power Mgt Timer Ctrl Reg Blk */
pub gpe0_block: u32, /* 32-bit port address of General Purpose Event 0 Reg Blk */
pub gpe1_block: u32, /* 32-bit port address of General Purpose Event 1 Reg Blk */
pub pm1_event_length: u8, /* Byte Length of ports at pm1x_event_block */
pub pm1_control_length: u8, /* Byte Length of ports at pm1x_control_block */
pub pm2_control_length: u8, /* Byte Length of ports at pm2_control_block */
pub pm_timer_length: u8, /* Byte Length of ports at pm_timer_block */
pub gpe0_block_length: u8, /* Byte Length of ports at gpe0_block */
pub gpe1_block_length: u8, /* Byte Length of ports at gpe1_block */
pub gpe1_base: u8, /* Offset in GPE number space where GPE1 events start */
pub cst_control: u8, /* Support for the _CST object and C-States change notification */
pub c2_latency: u16, /* Worst case HW latency to enter/exit C2 state */
pub c3_latency: u16, /* Worst case HW latency to enter/exit C3 state */
pub flush_size: u16, /* Processor memory cache line width, in bytes */
pub flush_stride: u16, /* Number of flush strides that need to be read */
pub duty_offset: u8, /* Processor duty cycle index in processor P_CNT reg */
pub duty_width: u8, /* Processor duty cycle value bit width in P_CNT register */
pub day_alarm: u8, /* Index to day-of-month alarm in RTC CMOS RAM */
pub month_alarm: u8, /* Index to month-of-year alarm in RTC CMOS RAM */
pub century: u8, /* Index to century in RTC CMOS RAM */
pub boot_flags: u16, /* IA-PC Boot Architecture Flags (see below for individual flags) */
pub reserved: u8, /* Reserved, must be zero */
pub flags: u32, /* Miscellaneous flag bits (see below for individual flags) */
pub reset_register: AcpiGenericAddress, /* 64-bit address of the Reset register */
pub reset_value: u8, /* Value to write to the reset_register port to reset the system */
pub arm_boot_flags: u16, /* ARM-Specific Boot Flags (see below for individual flags) (ACPI 5.1) */
pub minor_revision: u8, /* FADT Minor Revision (ACPI 5.1) */
pub xfacs: u64, /* 64-bit physical address of FACS */
pub xdsdt: u64, /* 64-bit physical address of DSDT */
pub xpm1a_event_block: AcpiGenericAddress, /* 64-bit Extended Power Mgt 1a Event Reg Blk address */
pub xpm1b_event_block: AcpiGenericAddress, /* 64-bit Extended Power Mgt 1b Event Reg Blk address */
pub xpm1a_control_block: AcpiGenericAddress, /* 64-bit Extended Power Mgt 1a Control Reg Blk address */
pub xpm1b_control_block: AcpiGenericAddress, /* 64-bit Extended Power Mgt 1b Control Reg Blk address */
pub xpm2_control_block: AcpiGenericAddress, /* 64-bit Extended Power Mgt 2 Control Reg Blk address */
pub xpm_timer_block: AcpiGenericAddress, /* 64-bit Extended Power Mgt Timer Ctrl Reg Blk address */
pub xgpe0_block: AcpiGenericAddress, /* 64-bit Extended General Purpose Event 0 Reg Blk address */
pub xgpe1_block: AcpiGenericAddress, /* 64-bit Extended General Purpose Event 1 Reg Blk address */
pub sleep_control: AcpiGenericAddress, /* 64-bit Sleep Control register (ACPI 5.0) */
pub sleep_status: AcpiGenericAddress, /* 64-bit Sleep Status register (ACPI 5.0) */
pub hypervisor_id: u64, /* Hypervisor Vendor ID (ACPI 6.0) */
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiTableMadt {
pub header: AcpiTableHeader, /* Common ACPI table header */
pub address: u32, /* Physical address of local APIC */
pub flags: u32,
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiSubtableHader {
pub r#type: u8,
pub length: u8,
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiMadtLocalApic {
pub header: AcpiSubtableHader,
pub processor_id: u8, /* ACPI processor id */
pub id: u8, /* Processor's local APIC id */
pub lapic_flags: u32,
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiMadtIoApic {
pub header: AcpiSubtableHader,
pub id: u8, /* I/O APIC ID */
pub reserved: u8, /* reserved - must be zero */
pub address: u32, /* APIC physical address */
pub global_irq_base: u32, /* Global system interrupt where INTI lines start */
}
#[repr(packed)]
#[derive(Default)]
pub struct AcpiMadtLocalX2apic {
pub header: AcpiSubtableHader,
pub reserved: u16, /* reserved - must be zero */
pub local_apic_id: u32, /* Processor x2APIC ID */
pub lapic_flags: u32,
pub uid: u32, /* ACPI processor UID */
}
/*
*
* Intel ACPI Component Architecture
* ASL Optimizing Compiler version 20140214-64 [Mar 29 2014]
* Copyright (c) 2000 - 2014 Intel Corporation
*
* Compilation of "vmm_acpi_dsdt.dsl" - Fri Apr 1 13:34:26 2016
*
*/
/*
*
* Based on the example at osdev wiki wiki.osdev.org/AML,
* and the other example in http://www.acpi.info/DOWNLOADS/ACPI_5_Errata%20A.pdf
* on page 194
*
* Compiled with `iasl -sc input_file.dsl`
*/
/*
* 9: DefinitionBlock (
* 10: "vmm_acpi_dsdt.aml", // Output AML Filename : String
* 11: "DSDT", // Signature : String
* 12: 0x2, // DSDT Compliance Revision : ByteConst
* 13: "MIKE", // OEMID : String
* 14: "DSDTTBL", // TABLE ID : String
* 15: 0x0 // OEM Revision : DWordConst
* 16: ){}
*/
pub const DSDT_DSDTTBL_HEADER: [u8; 36] = [
0x44, 0x53, 0x44, 0x54, 0x24, 0x00, 0x00, 0x00, /* 00000000 "DSDT$..." */
0x02, 0xF3, 0x4D, 0x49, 0x4B, 0x45, 0x00, 0x00, /* 00000008 "..MIKE.." */
0x44, 0x53, 0x44, 0x54, 0x54, 0x42, 0x4C, 0x00, /* 00000010 "DSDTTBL." */
0x00, 0x00, 0x00, 0x00, 0x49, 0x4E, 0x54, 0x4C, /* 00000018 "....INTL" */
0x14, 0x02, 0x14, 0x20, /* 00000020 "... " */
];
#[inline]
fn gencsum(data: &[u8]) -> u8 {
(!data.iter().map(|x| Wrapping(*x)).sum::<Wrapping<u8>>() + Wrapping(1)).0
}
#[inline]
fn
|
(data: &[u8]) -> u8 {
data.iter().map(|x| Wrapping(*x)).sum::<Wrapping<u8>>().0
}
const SIG_RSDP: [u8; 8] = *b"RSD PTR ";
const SIG_XSDT: [u8; 4] = *b"XSDT";
const SIG_FADT: [u8; 4] = *b"FACP";
const SIG_MADT: [u8; 4] = *b"APIC";
const MADT_LOCAL_APIC: u8 = 0;
const MADT_IO_APIC: u8 = 1;
const MADT_LOCAL_X2APIC: u8 = 9;
/// Setup the BIOS tables in the low memory
///
/// `start` is the base address of the BIOS tables in the physical address space
/// of the guest. `low_mem` is a host virtual memory block which is mapped to
/// the lowest memory of the guest. `cores` is the number of logical CPUs of the guest.
/// Total number of bytes occupied by the BIOS tables is returned.
pub fn setup_bios_tables(start: usize, low_mem: &mut MachVMBlock, cores: u32) -> usize {
// calculate offsets first
// variables with suffix `_offset` mean the offset in `low_mem`. They are
// also the guest physical address of the corresponding tables, since `low_mem` is
// mapped to the lowest memory of the guest's physical address space.
let rsdp_offset = start;
let xsdt_offset = rsdp_offset + size_of::<AcpiTableRsdp>();
let xsdt_entry_offset = xsdt_offset + size_of::<AcpiTableHeader>();
const NUM_XSDT_ENTRIES: usize = 8;
let fadt_offset = xsdt_entry_offset + NUM_XSDT_ENTRIES * size_of::<u64>();
let dsdt_offset = fadt_offset + size_of::<AcpiTableFadt>();
let madt_offset = dsdt_offset + DSDT_DSDTTBL_HEADER.len();
let madt_local_apic_offset = madt_offset + size_of::<AcpiTableMadt>();
let io_apic_offset = madt_local_apic_offset + cores as usize * size_of::<AcpiMadtLocalApic>();
let local_x2apic_offset = io_apic_offset + size_of::<AcpiMadtIoApic>();
let total_size =
local_x2apic_offset + cores as usize * size_of::<AcpiMadtLocalX2apic>() - start;
// setup rsdp
let rdsp = AcpiTableRsdp {
signature: SIG_RSDP,
revision: 2,
length: 36,
xsdt_physical_address: xsdt_offset as u64,
..Default::default()
};
low_mem.write(rdsp, rsdp_offset, 0);
low_mem[rsdp_offset + ACPI_RSDP_CHECKSUM_OFFSET] =
gencsum(&low_mem[rsdp_offset..(rsdp_offset + ACPI_RSDP_CHECKSUM_LENGTH)]);
debug_assert_eq!(
acpi_tb_checksum(&low_mem[rsdp_offset..(rsdp_offset + ACPI_RSDP_CHECKSUM_LENGTH)]),
0
);
low_mem[rsdp_offset + ACPI_RSDP_XCHECKSUM_OFFSET] =
gencsum(&low_mem[rsdp_offset..(rsdp_offset + ACPI_RSDP_XCHECKSUM_LENGTH)]);
debug_assert_eq!(
acpi_tb_checksum(&low_mem[rsdp_offset..(rsdp_offset + ACPI_RSDP_XCHECKSUM_LENGTH)]),
0
);
// xsdt
let xsdt_total_length = size_of::<AcpiTableHeader>() + size_of::<u64>() * NUM_XSDT_ENTRIES;
let xsdt = AcpiTableHeader {
signature: SIG_XSDT,
length: xsdt_total_length as u32,
..AcpiTableHeader::new()
};
low_mem.write(xsdt, xsdt_offset, 0);
// xsdt entries
let mut xsdt_entries: [u64; NUM_XSDT_ENTRIES] = [0; NUM_XSDT_ENTRIES];
xsdt_entries[0] = fadt_offset as u64;
xsdt_entries[3] = madt_offset as u64;
low_mem.write(xsdt_entries, xsdt_entry_offset, 0);
low_mem[xsdt_offset + ACPI_TABLE_HEADER_CHECKSUM_OFFSET] =
gencsum(&low_mem[xsdt_offset..(xsdt_offset + xsdt_total_length)]);
debug_assert_eq!(
acpi_tb_checksum(&low_mem[xsdt_offset..(xsdt_offset + xsdt_total_length)]),
0
);
// fadt
let fadt = AcpiTableFadt {
header: AcpiTableHeader {
signature: SIG_FADT,
length: size_of::<AcpiTableFadt>() as u32,
..AcpiTableHeader::new()
},
xdsdt: dsdt_offset as u64,
..Default::default()
};
low_mem.write(fadt, fadt_offset, 0);
low_mem[fadt_offset + ACPI_TABLE_HEADER_CHECKSUM_OFFSET] =
gencsum(&low_mem[fadt_offset..(fadt_offset + size_of::<AcpiTableFadt>())]);
debug_assert_eq!(
acpi_tb_checksum(&low_mem[fadt_offset..(fadt_offset + size_of::<AcpiTableFadt>())]),
0
);
// dsdt
low_mem.write(DSDT_DSDTTBL_HEADER, dsdt_offset, 0);
// madt
let madt_total_length = size_of::<AcpiTableMadt>()
+ size_of::<AcpiMadtIoApic>()
+ cores as usize * (size_of::<AcpiMadtLocalApic>() + size_of::<AcpiMadtLocalX2apic>());
let madt = AcpiTableMadt {
header: AcpiTableHeader {
signature: SIG_MADT,
length: madt_total_length as u32,
..AcpiTableHeader::new()
},
address: APIC_BASE as u32,
flags: 0,
..Default::default()
};
low_mem.write(madt, madt_offset, 0);
// local apic
for i in 0..cores {
let lapic = AcpiMadtLocalApic {
header: AcpiSubtableHader {
r#type: MADT_LOCAL_APIC,
length: size_of::<AcpiMadtLocalApic>() as u8,
},
processor_id: i as u8,
id: i as u8,
lapic_flags: 1,
};
low_mem.write(lapic, madt_local_apic_offset, i as usize)
}
// io apiic
let io_apic = AcpiMadtIoApic {
header: AcpiSubtableHader {
r#type: MADT_IO_APIC,
length: size_of::<AcpiMadtIoApic>() as u8,
},
id: 0,
address: IO_APIC_BASE as u32,
global_irq_base: 0,
..Default::default()
};
low_mem.write(io_apic, io_apic_offset, 0);
// local x2apic
for i in 0..cores {
let x2apic = AcpiMadtLocalX2apic {
header: AcpiSubtableHader {
r#type: MADT_LOCAL_X2APIC,
length: size_of::<AcpiMadtLocalX2apic>() as u8,
},
local_apic_id: i,
uid: i,
lapic_flags: 1,
..Default::default()
};
low_mem.write(x2apic, local_x2apic_offset, i as usize)
}
low_mem[madt_offset + ACPI_TABLE_HEADER_CHECKSUM_OFFSET] =
gencsum(&low_mem[madt_offset..(madt_offset + madt_total_length)]);
debug_assert_eq!(
acpi_tb_checksum(&low_mem[madt_offset..(madt_offset + madt_total_length)]),
0
);
round_up_4k(total_size)
}
|
acpi_tb_checksum
|
identifier_name
|
performance.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::PerformanceBinding;
use dom::bindings::codegen::Bindings::PerformanceBinding::PerformanceMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::num::Finite;
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::performancetiming::{PerformanceTiming, PerformanceTimingHelpers};
use dom::window::Window;
use time;
pub type DOMHighResTimeStamp = Finite<f64>;
#[dom_struct]
pub struct
|
{
reflector_: Reflector,
timing: JS<PerformanceTiming>,
}
impl Performance {
fn new_inherited(window: JSRef<Window>,
navigation_start: u64,
navigation_start_precise: f64) -> Performance {
Performance {
reflector_: Reflector::new(),
timing: JS::from_rooted(PerformanceTiming::new(window,
navigation_start,
navigation_start_precise)),
}
}
pub fn new(window: JSRef<Window>,
navigation_start: u64,
navigation_start_precise: f64) -> Temporary<Performance> {
reflect_dom_object(box Performance::new_inherited(window,
navigation_start,
navigation_start_precise),
GlobalRef::Window(window),
PerformanceBinding::Wrap)
}
}
impl<'a> PerformanceMethods for JSRef<'a, Performance> {
fn Timing(self) -> Temporary<PerformanceTiming> {
Temporary::new(self.timing.clone())
}
// https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HighResolutionTime/Overview.html#dom-performance-now
fn Now(self) -> DOMHighResTimeStamp {
let navStart = self.timing.root().r().NavigationStartPrecise();
let now = (time::precise_time_ns() as f64 - navStart) * 1000000 as f64;
Finite::wrap(now)
}
}
|
Performance
|
identifier_name
|
performance.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::PerformanceBinding;
use dom::bindings::codegen::Bindings::PerformanceBinding::PerformanceMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::num::Finite;
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::performancetiming::{PerformanceTiming, PerformanceTimingHelpers};
use dom::window::Window;
use time;
pub type DOMHighResTimeStamp = Finite<f64>;
#[dom_struct]
pub struct Performance {
reflector_: Reflector,
timing: JS<PerformanceTiming>,
}
|
navigation_start: u64,
navigation_start_precise: f64) -> Performance {
Performance {
reflector_: Reflector::new(),
timing: JS::from_rooted(PerformanceTiming::new(window,
navigation_start,
navigation_start_precise)),
}
}
pub fn new(window: JSRef<Window>,
navigation_start: u64,
navigation_start_precise: f64) -> Temporary<Performance> {
reflect_dom_object(box Performance::new_inherited(window,
navigation_start,
navigation_start_precise),
GlobalRef::Window(window),
PerformanceBinding::Wrap)
}
}
impl<'a> PerformanceMethods for JSRef<'a, Performance> {
fn Timing(self) -> Temporary<PerformanceTiming> {
Temporary::new(self.timing.clone())
}
// https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HighResolutionTime/Overview.html#dom-performance-now
fn Now(self) -> DOMHighResTimeStamp {
let navStart = self.timing.root().r().NavigationStartPrecise();
let now = (time::precise_time_ns() as f64 - navStart) * 1000000 as f64;
Finite::wrap(now)
}
}
|
impl Performance {
fn new_inherited(window: JSRef<Window>,
|
random_line_split
|
performance.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::PerformanceBinding;
use dom::bindings::codegen::Bindings::PerformanceBinding::PerformanceMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::num::Finite;
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::performancetiming::{PerformanceTiming, PerformanceTimingHelpers};
use dom::window::Window;
use time;
pub type DOMHighResTimeStamp = Finite<f64>;
#[dom_struct]
pub struct Performance {
reflector_: Reflector,
timing: JS<PerformanceTiming>,
}
impl Performance {
fn new_inherited(window: JSRef<Window>,
navigation_start: u64,
navigation_start_precise: f64) -> Performance {
Performance {
reflector_: Reflector::new(),
timing: JS::from_rooted(PerformanceTiming::new(window,
navigation_start,
navigation_start_precise)),
}
}
pub fn new(window: JSRef<Window>,
navigation_start: u64,
navigation_start_precise: f64) -> Temporary<Performance>
|
}
impl<'a> PerformanceMethods for JSRef<'a, Performance> {
fn Timing(self) -> Temporary<PerformanceTiming> {
Temporary::new(self.timing.clone())
}
// https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HighResolutionTime/Overview.html#dom-performance-now
fn Now(self) -> DOMHighResTimeStamp {
let navStart = self.timing.root().r().NavigationStartPrecise();
let now = (time::precise_time_ns() as f64 - navStart) * 1000000 as f64;
Finite::wrap(now)
}
}
|
{
reflect_dom_object(box Performance::new_inherited(window,
navigation_start,
navigation_start_precise),
GlobalRef::Window(window),
PerformanceBinding::Wrap)
}
|
identifier_body
|
deque.rs
|
the comment on `swap_buffer`
// FIXME: all atomic operations in this module use a SeqCst ordering. That is
// probably overkill
use core::prelude::*;
use alloc::arc::Arc;
use alloc::heap::{allocate, deallocate};
use alloc::owned::Box;
use collections::Vec;
use core::kinds::marker;
use core::mem::{forget, min_align_of, size_of, transmute};
use core::ptr;
use rustrt::exclusive::Exclusive;
use atomics::{AtomicInt, AtomicPtr, SeqCst};
// Once the queue is less than 1/K full, then it will be downsized. Note that
// the deque requires that this number be less than 2.
static K: int = 4;
// Minimum number of bits that a buffer size should be. No buffer will resize to
// under this value, and all deques will initially contain a buffer of this
// size.
//
// The size in question is 1 << MIN_BITS
static MIN_BITS: uint = 7;
struct Deque<T> {
bottom: AtomicInt,
top: AtomicInt,
array: AtomicPtr<Buffer<T>>,
pool: BufferPool<T>,
}
/// Worker half of the work-stealing deque. This worker has exclusive access to
/// one side of the deque, and uses `push` and `pop` method to manipulate it.
///
/// There may only be one worker per deque.
pub struct Worker<T> {
deque: Arc<Deque<T>>,
noshare: marker::NoShare,
}
/// The stealing half of the work-stealing deque. Stealers have access to the
/// opposite end of the deque from the worker, and they only have access to the
/// `steal` method.
pub struct Stealer<T> {
deque: Arc<Deque<T>>,
noshare: marker::NoShare,
}
/// When stealing some data, this is an enumeration of the possible outcomes.
#[deriving(PartialEq, Show)]
pub enum Stolen<T> {
/// The deque was empty at the time of stealing
Empty,
/// The stealer lost the race for stealing data, and a retry may return more
/// data.
Abort,
/// The stealer has successfully stolen some data.
Data(T),
}
/// The allocation pool for buffers used by work-stealing deques. Right now this
/// structure is used for reclamation of memory after it is no longer in use by
/// deques.
///
/// This data structure is protected by a mutex, but it is rarely used. Deques
/// will only use this structure when allocating a new buffer or deallocating a
/// previous one.
pub struct BufferPool<T> {
pool: Arc<Exclusive<Vec<Box<Buffer<T>>>>>,
}
/// An internal buffer used by the chase-lev deque. This structure is actually
/// implemented as a circular buffer, and is used as the intermediate storage of
/// the data in the deque.
///
/// This type is implemented with *T instead of Vec<T> for two reasons:
///
/// 1. There is nothing safe about using this buffer. This easily allows the
/// same value to be read twice in to rust, and there is nothing to
/// prevent this. The usage by the deque must ensure that one of the
/// values is forgotten. Furthermore, we only ever want to manually run
/// destructors for values in this buffer (on drop) because the bounds
/// are defined by the deque it's owned by.
///
/// 2. We can certainly avoid bounds checks using *T instead of Vec<T>, although
/// LLVM is probably pretty good at doing this already.
struct Buffer<T> {
storage: *const T,
log_size: uint,
}
impl<T: Send> BufferPool<T> {
/// Allocates a new buffer pool which in turn can be used to allocate new
/// deques.
pub fn new() -> BufferPool<T> {
BufferPool { pool: Arc::new(Exclusive::new(Vec::new())) }
}
/// Allocates a new work-stealing deque which will send/receiving memory to
/// and from this buffer pool.
pub fn deque(&self) -> (Worker<T>, Stealer<T>) {
let a = Arc::new(Deque::new(self.clone()));
let b = a.clone();
(Worker { deque: a, noshare: marker::NoShare },
Stealer { deque: b, noshare: marker::NoShare })
}
fn alloc(&mut self, bits: uint) -> Box<Buffer<T>> {
unsafe {
let mut pool = self.pool.lock();
match pool.iter().position(|x| x.size() >= (1 << bits)) {
Some(i) => pool.remove(i).unwrap(),
None => box Buffer::new(bits)
}
}
}
fn free(&self, buf: Box<Buffer<T>>) {
unsafe {
let mut pool = self.pool.lock();
match pool.iter().position(|v| v.size() > buf.size()) {
Some(i) => pool.insert(i, buf),
None => pool.push(buf),
}
}
}
}
impl<T: Send> Clone for BufferPool<T> {
fn clone(&self) -> BufferPool<T> { BufferPool { pool: self.pool.clone() } }
}
impl<T: Send> Worker<T> {
/// Pushes data onto the front of this work queue.
pub fn push(&self, t: T)
|
/// Pops data off the front of the work queue, returning `None` on an empty
/// queue.
pub fn pop(&self) -> Option<T> {
unsafe { self.deque.pop() }
}
/// Gets access to the buffer pool that this worker is attached to. This can
/// be used to create more deques which share the same buffer pool as this
/// deque.
pub fn pool<'a>(&'a self) -> &'a BufferPool<T> {
&self.deque.pool
}
}
impl<T: Send> Stealer<T> {
/// Steals work off the end of the queue (opposite of the worker's end)
pub fn steal(&self) -> Stolen<T> {
unsafe { self.deque.steal() }
}
/// Gets access to the buffer pool that this stealer is attached to. This
/// can be used to create more deques which share the same buffer pool as
/// this deque.
pub fn pool<'a>(&'a self) -> &'a BufferPool<T> {
&self.deque.pool
}
}
impl<T: Send> Clone for Stealer<T> {
fn clone(&self) -> Stealer<T> {
Stealer { deque: self.deque.clone(), noshare: marker::NoShare }
}
}
// Almost all of this code can be found directly in the paper so I'm not
// personally going to heavily comment what's going on here.
impl<T: Send> Deque<T> {
fn new(mut pool: BufferPool<T>) -> Deque<T> {
let buf = pool.alloc(MIN_BITS);
Deque {
bottom: AtomicInt::new(0),
top: AtomicInt::new(0),
array: AtomicPtr::new(unsafe { transmute(buf) }),
pool: pool,
}
}
unsafe fn push(&self, data: T) {
let mut b = self.bottom.load(SeqCst);
let t = self.top.load(SeqCst);
let mut a = self.array.load(SeqCst);
let size = b - t;
if size >= (*a).size() - 1 {
// You won't find this code in the chase-lev deque paper. This is
// alluded to in a small footnote, however. We always free a buffer
// when growing in order to prevent leaks.
a = self.swap_buffer(b, a, (*a).resize(b, t, 1));
b = self.bottom.load(SeqCst);
}
(*a).put(b, data);
self.bottom.store(b + 1, SeqCst);
}
unsafe fn pop(&self) -> Option<T> {
let b = self.bottom.load(SeqCst);
let a = self.array.load(SeqCst);
let b = b - 1;
self.bottom.store(b, SeqCst);
let t = self.top.load(SeqCst);
let size = b - t;
if size < 0 {
self.bottom.store(t, SeqCst);
return None;
}
let data = (*a).get(b);
if size > 0 {
self.maybe_shrink(b, t);
return Some(data);
}
if self.top.compare_and_swap(t, t + 1, SeqCst) == t {
self.bottom.store(t + 1, SeqCst);
return Some(data);
} else {
self.bottom.store(t + 1, SeqCst);
forget(data); // someone else stole this value
return None;
}
}
unsafe fn steal(&self) -> Stolen<T> {
let t = self.top.load(SeqCst);
let old = self.array.load(SeqCst);
let b = self.bottom.load(SeqCst);
let a = self.array.load(SeqCst);
let size = b - t;
if size <= 0 { return Empty }
if size % (*a).size() == 0 {
if a == old && t == self.top.load(SeqCst) {
return Empty
}
return Abort
}
let data = (*a).get(t);
if self.top.compare_and_swap(t, t + 1, SeqCst) == t {
Data(data)
} else {
forget(data); // someone else stole this value
Abort
}
}
unsafe fn maybe_shrink(&self, b: int, t: int) {
let a = self.array.load(SeqCst);
if b - t < (*a).size() / K && b - t > (1 << MIN_BITS) {
self.swap_buffer(b, a, (*a).resize(b, t, -1));
}
}
// Helper routine not mentioned in the paper which is used in growing and
// shrinking buffers to swap in a new buffer into place. As a bit of a
// recap, the whole point that we need a buffer pool rather than just
// calling malloc/free directly is that stealers can continue using buffers
// after this method has called 'free' on it. The continued usage is simply
// a read followed by a forget, but we must make sure that the memory can
// continue to be read after we flag this buffer for reclamation.
unsafe fn swap_buffer(&self, b: int, old: *mut Buffer<T>,
buf: Buffer<T>) -> *mut Buffer<T> {
let newbuf: *mut Buffer<T> = transmute(box buf);
self.array.store(newbuf, SeqCst);
let ss = (*newbuf).size();
self.bottom.store(b + ss, SeqCst);
let t = self.top.load(SeqCst);
if self.top.compare_and_swap(t, t + ss, SeqCst)!= t {
self.bottom.store(b, SeqCst);
}
self.pool.free(transmute(old));
return newbuf;
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Deque<T> {
fn drop(&mut self) {
let t = self.top.load(SeqCst);
let b = self.bottom.load(SeqCst);
let a = self.array.load(SeqCst);
// Free whatever is leftover in the dequeue, and then move the buffer
// back into the pool.
for i in range(t, b) {
let _: T = unsafe { (*a).get(i) };
}
self.pool.free(unsafe { transmute(a) });
}
}
#[inline]
fn buffer_alloc_size<T>(log_size: uint) -> uint {
(1 << log_size) * size_of::<T>()
}
impl<T: Send> Buffer<T> {
unsafe fn new(log_size: uint) -> Buffer<T> {
let size = buffer_alloc_size::<T>(log_size);
let buffer = allocate(size, min_align_of::<T>());
Buffer {
storage: buffer as *const T,
log_size: log_size,
}
}
fn size(&self) -> int { 1 << self.log_size }
// Apparently LLVM cannot optimize (foo % (1 << bar)) into this implicitly
fn mask(&self) -> int { (1 << self.log_size) - 1 }
unsafe fn elem(&self, i: int) -> *const T {
self.storage.offset(i & self.mask())
}
// This does not protect against loading duplicate values of the same cell,
// nor does this clear out the contents contained within. Hence, this is a
// very unsafe method which the caller needs to treat specially in case a
// race is lost.
unsafe fn get(&self, i: int) -> T {
ptr::read(self.elem(i))
}
// Unsafe because this unsafely overwrites possibly uninitialized or
// initialized data.
unsafe fn put(&self, i: int, t: T) {
ptr::write(self.elem(i) as *mut T, t);
}
// Again, unsafe because this has incredibly dubious ownership violations.
// It is assumed that this buffer is immediately dropped.
unsafe fn resize(&self, b: int, t: int, delta: int) -> Buffer<T> {
// NB: not entirely obvious, but thanks to 2's complement,
// casting delta to uint and then adding gives the desired
// effect.
let buf = Buffer::new(self.log_size + delta as uint);
for i in range(t, b) {
buf.put(i, self.get(i));
}
return buf;
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Buffer<T> {
fn drop(&mut self) {
// It is assumed that all buffers are empty on drop.
let size = buffer_alloc_size::<T>(self.log_size);
unsafe { deallocate(self.storage as *mut u8, size, min_align_of::<T>()) }
}
}
#[cfg(test)]
mod tests {
use std::prelude::*;
use super::{Data, BufferPool, Abort, Empty, Worker, Stealer};
use std::mem;
use std::rt::thread::Thread;
use std::rand;
use std::rand::Rng;
use atomics::{AtomicBool, INIT_ATOMIC_BOOL, SeqCst,
AtomicUint, INIT_ATOMIC_UINT};
use std::vec;
#[test]
fn smoke() {
let pool = BufferPool::new();
let (w, s) = pool.deque();
assert_eq!(w.pop(), None);
assert_eq!(s.steal(), Empty);
w.push(1i);
assert_eq!(w.pop(), Some(1));
w.push(1);
assert_eq!(s.steal(), Data(1));
w.push(1);
assert_eq!(s.clone().steal(), Data(1));
}
#[test]
fn stealpush() {
static AMT: int = 100000;
let pool = BufferPool::<int>::new();
let (w, s) = pool.deque();
let t = Thread::start(proc() {
let mut left = AMT;
while left > 0 {
match s.steal() {
Data(i) => {
assert_eq!(i, 1);
left -= 1;
}
Abort | Empty => {}
}
}
});
for _ in range(0, AMT) {
w.push(1);
}
t.join();
}
#[test]
fn stealpush_large() {
static AMT: int = 100000;
let pool = BufferPool::<(int, int)>::new();
let (w, s) = pool.deque();
let t = Thread::start(proc() {
let mut left = AMT;
while left > 0 {
match s.steal() {
Data((1, 10)) => { left -= 1; }
Data(..) => fail!(),
Abort | Empty => {}
}
}
});
for _ in range(0, AMT) {
w.push((1, 10));
}
t.join();
}
fn stampede(w: Worker<Box<int>>, s: Stealer<Box<int>>,
nthreads: int, amt: uint) {
for _ in range(0, amt) {
w.push(box 20);
}
let mut remaining = AtomicUint::new(amt);
let unsafe_remaining: *mut AtomicUint = &mut remaining;
let threads = range(0, nthreads).map(|_| {
let s = s.clone();
Thread::start(proc() {
unsafe {
while (*unsafe_remaining).load(SeqCst) > 0 {
match s.steal() {
Data(box 20) => {
(*unsafe_remaining).fetch_sub(1, SeqCst);
}
Data(..) => fail!(),
Abort | Empty => {}
}
}
}
})
}).collect::<Vec<Thread<()>>>();
while remaining.load(SeqCst) > 0 {
match w.pop() {
Some(box 20) => { remaining.fetch_sub(1, SeqCst); }
Some(..) => fail!(),
None => {}
}
}
for thread in threads.move_iter() {
thread.join();
}
}
#[test]
fn run_stampede() {
let pool = BufferPool::<Box<int>>::new();
let (w, s) = pool.deque();
stampede(w, s, 8, 10000);
}
#[test]
fn many_stampede() {
static AMT: uint = 4;
let pool = BufferPool::<Box<int>>::new();
let threads = range(0, AMT).map(|_| {
let (w, s) = pool.deque();
Thread::start(proc() {
stampede(w, s, 4, 10000);
})
}).collect::<Vec<Thread<()>>>();
for thread in threads.move_iter() {
thread.join();
}
}
#[test]
fn stress() {
static AMT: int = 100000;
static NTHREADS: int = 8;
static mut DONE: AtomicBool = INIT_ATOMIC_BOOL;
static mut HITS: AtomicUint = INIT_ATOMIC_UINT;
let pool = BufferPool::<int>::new();
let (w, s) = pool.deque();
let threads = range(0, NTHREADS).map(|_| {
let s = s.clone();
Thread::start(proc() {
unsafe {
loop {
match s.steal() {
Data(2) => { HITS.fetch_add(1, SeqCst); }
Data(..) => fail!(),
_ if DONE.load(SeqCst) => break,
_ => {}
}
}
}
})
}).collect::<Vec<Thread<()>>>();
let mut rng = rand::task_rng();
let mut expected = 0;
while expected < AMT {
if rng.gen_range(0i, 3) == 2 {
match w.pop() {
None => {}
Some(2) => unsafe { HITS.fetch_add(1, SeqCst); },
Some(_) => fail!(),
}
} else {
expected += 1;
w.push(2);
}
}
unsafe {
while HITS.load(SeqCst) < AMT as uint {
match w.pop() {
None => {}
Some(2) => { HITS.fetch_add(1, SeqCst); },
Some(_) => fail!(),
}
}
DONE.store(true, SeqCst);
}
for thread in threads.move_iter() {
thread.join();
}
assert_eq!(unsafe { HITS.load(SeqCst) }, expected as uint);
}
#[test]
#[ignore(cfg(windows))] // apparently windows scheduling is weird?
fn no_starvation() {
static AMT: int =
|
{
unsafe { self.deque.push(t) }
}
|
identifier_body
|
deque.rs
|
the comment on `swap_buffer`
// FIXME: all atomic operations in this module use a SeqCst ordering. That is
// probably overkill
use core::prelude::*;
use alloc::arc::Arc;
use alloc::heap::{allocate, deallocate};
use alloc::owned::Box;
use collections::Vec;
use core::kinds::marker;
use core::mem::{forget, min_align_of, size_of, transmute};
use core::ptr;
use rustrt::exclusive::Exclusive;
use atomics::{AtomicInt, AtomicPtr, SeqCst};
// Once the queue is less than 1/K full, then it will be downsized. Note that
// the deque requires that this number be less than 2.
static K: int = 4;
// Minimum number of bits that a buffer size should be. No buffer will resize to
// under this value, and all deques will initially contain a buffer of this
// size.
//
// The size in question is 1 << MIN_BITS
static MIN_BITS: uint = 7;
struct Deque<T> {
bottom: AtomicInt,
top: AtomicInt,
array: AtomicPtr<Buffer<T>>,
pool: BufferPool<T>,
}
/// Worker half of the work-stealing deque. This worker has exclusive access to
/// one side of the deque, and uses `push` and `pop` method to manipulate it.
///
/// There may only be one worker per deque.
pub struct Worker<T> {
deque: Arc<Deque<T>>,
noshare: marker::NoShare,
}
/// The stealing half of the work-stealing deque. Stealers have access to the
/// opposite end of the deque from the worker, and they only have access to the
/// `steal` method.
pub struct Stealer<T> {
deque: Arc<Deque<T>>,
noshare: marker::NoShare,
}
/// When stealing some data, this is an enumeration of the possible outcomes.
#[deriving(PartialEq, Show)]
pub enum Stolen<T> {
/// The deque was empty at the time of stealing
Empty,
/// The stealer lost the race for stealing data, and a retry may return more
/// data.
Abort,
/// The stealer has successfully stolen some data.
Data(T),
}
/// The allocation pool for buffers used by work-stealing deques. Right now this
/// structure is used for reclamation of memory after it is no longer in use by
/// deques.
///
/// This data structure is protected by a mutex, but it is rarely used. Deques
/// will only use this structure when allocating a new buffer or deallocating a
/// previous one.
pub struct BufferPool<T> {
pool: Arc<Exclusive<Vec<Box<Buffer<T>>>>>,
}
/// An internal buffer used by the chase-lev deque. This structure is actually
/// implemented as a circular buffer, and is used as the intermediate storage of
/// the data in the deque.
///
/// This type is implemented with *T instead of Vec<T> for two reasons:
///
/// 1. There is nothing safe about using this buffer. This easily allows the
/// same value to be read twice in to rust, and there is nothing to
/// prevent this. The usage by the deque must ensure that one of the
/// values is forgotten. Furthermore, we only ever want to manually run
/// destructors for values in this buffer (on drop) because the bounds
/// are defined by the deque it's owned by.
///
/// 2. We can certainly avoid bounds checks using *T instead of Vec<T>, although
/// LLVM is probably pretty good at doing this already.
struct Buffer<T> {
storage: *const T,
log_size: uint,
}
impl<T: Send> BufferPool<T> {
/// Allocates a new buffer pool which in turn can be used to allocate new
/// deques.
pub fn new() -> BufferPool<T> {
BufferPool { pool: Arc::new(Exclusive::new(Vec::new())) }
}
/// Allocates a new work-stealing deque which will send/receiving memory to
/// and from this buffer pool.
pub fn deque(&self) -> (Worker<T>, Stealer<T>) {
let a = Arc::new(Deque::new(self.clone()));
let b = a.clone();
(Worker { deque: a, noshare: marker::NoShare },
Stealer { deque: b, noshare: marker::NoShare })
}
fn alloc(&mut self, bits: uint) -> Box<Buffer<T>> {
unsafe {
let mut pool = self.pool.lock();
match pool.iter().position(|x| x.size() >= (1 << bits)) {
Some(i) => pool.remove(i).unwrap(),
None => box Buffer::new(bits)
}
}
}
fn free(&self, buf: Box<Buffer<T>>) {
unsafe {
let mut pool = self.pool.lock();
match pool.iter().position(|v| v.size() > buf.size()) {
Some(i) => pool.insert(i, buf),
None => pool.push(buf),
}
}
}
}
impl<T: Send> Clone for BufferPool<T> {
fn
|
(&self) -> BufferPool<T> { BufferPool { pool: self.pool.clone() } }
}
impl<T: Send> Worker<T> {
/// Pushes data onto the front of this work queue.
pub fn push(&self, t: T) {
unsafe { self.deque.push(t) }
}
/// Pops data off the front of the work queue, returning `None` on an empty
/// queue.
pub fn pop(&self) -> Option<T> {
unsafe { self.deque.pop() }
}
/// Gets access to the buffer pool that this worker is attached to. This can
/// be used to create more deques which share the same buffer pool as this
/// deque.
pub fn pool<'a>(&'a self) -> &'a BufferPool<T> {
&self.deque.pool
}
}
impl<T: Send> Stealer<T> {
/// Steals work off the end of the queue (opposite of the worker's end)
pub fn steal(&self) -> Stolen<T> {
unsafe { self.deque.steal() }
}
/// Gets access to the buffer pool that this stealer is attached to. This
/// can be used to create more deques which share the same buffer pool as
/// this deque.
pub fn pool<'a>(&'a self) -> &'a BufferPool<T> {
&self.deque.pool
}
}
impl<T: Send> Clone for Stealer<T> {
fn clone(&self) -> Stealer<T> {
Stealer { deque: self.deque.clone(), noshare: marker::NoShare }
}
}
// Almost all of this code can be found directly in the paper so I'm not
// personally going to heavily comment what's going on here.
impl<T: Send> Deque<T> {
fn new(mut pool: BufferPool<T>) -> Deque<T> {
let buf = pool.alloc(MIN_BITS);
Deque {
bottom: AtomicInt::new(0),
top: AtomicInt::new(0),
array: AtomicPtr::new(unsafe { transmute(buf) }),
pool: pool,
}
}
unsafe fn push(&self, data: T) {
let mut b = self.bottom.load(SeqCst);
let t = self.top.load(SeqCst);
let mut a = self.array.load(SeqCst);
let size = b - t;
if size >= (*a).size() - 1 {
// You won't find this code in the chase-lev deque paper. This is
// alluded to in a small footnote, however. We always free a buffer
// when growing in order to prevent leaks.
a = self.swap_buffer(b, a, (*a).resize(b, t, 1));
b = self.bottom.load(SeqCst);
}
(*a).put(b, data);
self.bottom.store(b + 1, SeqCst);
}
unsafe fn pop(&self) -> Option<T> {
let b = self.bottom.load(SeqCst);
let a = self.array.load(SeqCst);
let b = b - 1;
self.bottom.store(b, SeqCst);
let t = self.top.load(SeqCst);
let size = b - t;
if size < 0 {
self.bottom.store(t, SeqCst);
return None;
}
let data = (*a).get(b);
if size > 0 {
self.maybe_shrink(b, t);
return Some(data);
}
if self.top.compare_and_swap(t, t + 1, SeqCst) == t {
self.bottom.store(t + 1, SeqCst);
return Some(data);
} else {
self.bottom.store(t + 1, SeqCst);
forget(data); // someone else stole this value
return None;
}
}
unsafe fn steal(&self) -> Stolen<T> {
let t = self.top.load(SeqCst);
let old = self.array.load(SeqCst);
let b = self.bottom.load(SeqCst);
let a = self.array.load(SeqCst);
let size = b - t;
if size <= 0 { return Empty }
if size % (*a).size() == 0 {
if a == old && t == self.top.load(SeqCst) {
return Empty
}
return Abort
}
let data = (*a).get(t);
if self.top.compare_and_swap(t, t + 1, SeqCst) == t {
Data(data)
} else {
forget(data); // someone else stole this value
Abort
}
}
unsafe fn maybe_shrink(&self, b: int, t: int) {
let a = self.array.load(SeqCst);
if b - t < (*a).size() / K && b - t > (1 << MIN_BITS) {
self.swap_buffer(b, a, (*a).resize(b, t, -1));
}
}
// Helper routine not mentioned in the paper which is used in growing and
// shrinking buffers to swap in a new buffer into place. As a bit of a
// recap, the whole point that we need a buffer pool rather than just
// calling malloc/free directly is that stealers can continue using buffers
// after this method has called 'free' on it. The continued usage is simply
// a read followed by a forget, but we must make sure that the memory can
// continue to be read after we flag this buffer for reclamation.
unsafe fn swap_buffer(&self, b: int, old: *mut Buffer<T>,
buf: Buffer<T>) -> *mut Buffer<T> {
let newbuf: *mut Buffer<T> = transmute(box buf);
self.array.store(newbuf, SeqCst);
let ss = (*newbuf).size();
self.bottom.store(b + ss, SeqCst);
let t = self.top.load(SeqCst);
if self.top.compare_and_swap(t, t + ss, SeqCst)!= t {
self.bottom.store(b, SeqCst);
}
self.pool.free(transmute(old));
return newbuf;
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Deque<T> {
fn drop(&mut self) {
let t = self.top.load(SeqCst);
let b = self.bottom.load(SeqCst);
let a = self.array.load(SeqCst);
// Free whatever is leftover in the dequeue, and then move the buffer
// back into the pool.
for i in range(t, b) {
let _: T = unsafe { (*a).get(i) };
}
self.pool.free(unsafe { transmute(a) });
}
}
#[inline]
fn buffer_alloc_size<T>(log_size: uint) -> uint {
(1 << log_size) * size_of::<T>()
}
impl<T: Send> Buffer<T> {
unsafe fn new(log_size: uint) -> Buffer<T> {
let size = buffer_alloc_size::<T>(log_size);
let buffer = allocate(size, min_align_of::<T>());
Buffer {
storage: buffer as *const T,
log_size: log_size,
}
}
fn size(&self) -> int { 1 << self.log_size }
// Apparently LLVM cannot optimize (foo % (1 << bar)) into this implicitly
fn mask(&self) -> int { (1 << self.log_size) - 1 }
unsafe fn elem(&self, i: int) -> *const T {
self.storage.offset(i & self.mask())
}
// This does not protect against loading duplicate values of the same cell,
// nor does this clear out the contents contained within. Hence, this is a
// very unsafe method which the caller needs to treat specially in case a
// race is lost.
unsafe fn get(&self, i: int) -> T {
ptr::read(self.elem(i))
}
// Unsafe because this unsafely overwrites possibly uninitialized or
// initialized data.
unsafe fn put(&self, i: int, t: T) {
ptr::write(self.elem(i) as *mut T, t);
}
// Again, unsafe because this has incredibly dubious ownership violations.
// It is assumed that this buffer is immediately dropped.
unsafe fn resize(&self, b: int, t: int, delta: int) -> Buffer<T> {
// NB: not entirely obvious, but thanks to 2's complement,
// casting delta to uint and then adding gives the desired
// effect.
let buf = Buffer::new(self.log_size + delta as uint);
for i in range(t, b) {
buf.put(i, self.get(i));
}
return buf;
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Buffer<T> {
fn drop(&mut self) {
// It is assumed that all buffers are empty on drop.
let size = buffer_alloc_size::<T>(self.log_size);
unsafe { deallocate(self.storage as *mut u8, size, min_align_of::<T>()) }
}
}
#[cfg(test)]
mod tests {
use std::prelude::*;
use super::{Data, BufferPool, Abort, Empty, Worker, Stealer};
use std::mem;
use std::rt::thread::Thread;
use std::rand;
use std::rand::Rng;
use atomics::{AtomicBool, INIT_ATOMIC_BOOL, SeqCst,
AtomicUint, INIT_ATOMIC_UINT};
use std::vec;
#[test]
fn smoke() {
let pool = BufferPool::new();
let (w, s) = pool.deque();
assert_eq!(w.pop(), None);
assert_eq!(s.steal(), Empty);
w.push(1i);
assert_eq!(w.pop(), Some(1));
w.push(1);
assert_eq!(s.steal(), Data(1));
w.push(1);
assert_eq!(s.clone().steal(), Data(1));
}
#[test]
fn stealpush() {
static AMT: int = 100000;
let pool = BufferPool::<int>::new();
let (w, s) = pool.deque();
let t = Thread::start(proc() {
let mut left = AMT;
while left > 0 {
match s.steal() {
Data(i) => {
assert_eq!(i, 1);
left -= 1;
}
Abort | Empty => {}
}
}
});
for _ in range(0, AMT) {
w.push(1);
}
t.join();
}
#[test]
fn stealpush_large() {
static AMT: int = 100000;
let pool = BufferPool::<(int, int)>::new();
let (w, s) = pool.deque();
let t = Thread::start(proc() {
let mut left = AMT;
while left > 0 {
match s.steal() {
Data((1, 10)) => { left -= 1; }
Data(..) => fail!(),
Abort | Empty => {}
}
}
});
for _ in range(0, AMT) {
w.push((1, 10));
}
t.join();
}
fn stampede(w: Worker<Box<int>>, s: Stealer<Box<int>>,
nthreads: int, amt: uint) {
for _ in range(0, amt) {
w.push(box 20);
}
let mut remaining = AtomicUint::new(amt);
let unsafe_remaining: *mut AtomicUint = &mut remaining;
let threads = range(0, nthreads).map(|_| {
let s = s.clone();
Thread::start(proc() {
unsafe {
while (*unsafe_remaining).load(SeqCst) > 0 {
match s.steal() {
Data(box 20) => {
(*unsafe_remaining).fetch_sub(1, SeqCst);
}
Data(..) => fail!(),
Abort | Empty => {}
}
}
}
})
}).collect::<Vec<Thread<()>>>();
while remaining.load(SeqCst) > 0 {
match w.pop() {
Some(box 20) => { remaining.fetch_sub(1, SeqCst); }
Some(..) => fail!(),
None => {}
}
}
for thread in threads.move_iter() {
thread.join();
}
}
#[test]
fn run_stampede() {
let pool = BufferPool::<Box<int>>::new();
let (w, s) = pool.deque();
stampede(w, s, 8, 10000);
}
#[test]
fn many_stampede() {
static AMT: uint = 4;
let pool = BufferPool::<Box<int>>::new();
let threads = range(0, AMT).map(|_| {
let (w, s) = pool.deque();
Thread::start(proc() {
stampede(w, s, 4, 10000);
})
}).collect::<Vec<Thread<()>>>();
for thread in threads.move_iter() {
thread.join();
}
}
#[test]
fn stress() {
static AMT: int = 100000;
static NTHREADS: int = 8;
static mut DONE: AtomicBool = INIT_ATOMIC_BOOL;
static mut HITS: AtomicUint = INIT_ATOMIC_UINT;
let pool = BufferPool::<int>::new();
let (w, s) = pool.deque();
let threads = range(0, NTHREADS).map(|_| {
let s = s.clone();
Thread::start(proc() {
unsafe {
loop {
match s.steal() {
Data(2) => { HITS.fetch_add(1, SeqCst); }
Data(..) => fail!(),
_ if DONE.load(SeqCst) => break,
_ => {}
}
}
}
})
}).collect::<Vec<Thread<()>>>();
let mut rng = rand::task_rng();
let mut expected = 0;
while expected < AMT {
if rng.gen_range(0i, 3) == 2 {
match w.pop() {
None => {}
Some(2) => unsafe { HITS.fetch_add(1, SeqCst); },
Some(_) => fail!(),
}
} else {
expected += 1;
w.push(2);
}
}
unsafe {
while HITS.load(SeqCst) < AMT as uint {
match w.pop() {
None => {}
Some(2) => { HITS.fetch_add(1, SeqCst); },
Some(_) => fail!(),
}
}
DONE.store(true, SeqCst);
}
for thread in threads.move_iter() {
thread.join();
}
assert_eq!(unsafe { HITS.load(SeqCst) }, expected as uint);
}
#[test]
#[ignore(cfg(windows))] // apparently windows scheduling is weird?
fn no_starvation() {
static AMT: int =
|
clone
|
identifier_name
|
deque.rs
|
//!
//! // Only the worker may push/pop
//! worker.push(1i);
//! worker.pop();
//!
//! // Stealers take data from the other end of the deque
//! worker.push(1i);
//! stealer.steal();
//!
//! // Stealers can be cloned to have many stealers stealing in parallel
//! worker.push(1i);
//! let mut stealer2 = stealer.clone();
//! stealer2.steal();
#![experimental]
// NB: the "buffer pool" strategy is not done for speed, but rather for
// correctness. For more info, see the comment on `swap_buffer`
// FIXME: all atomic operations in this module use a SeqCst ordering. That is
// probably overkill
use core::prelude::*;
use alloc::arc::Arc;
use alloc::heap::{allocate, deallocate};
use alloc::owned::Box;
use collections::Vec;
use core::kinds::marker;
use core::mem::{forget, min_align_of, size_of, transmute};
use core::ptr;
use rustrt::exclusive::Exclusive;
use atomics::{AtomicInt, AtomicPtr, SeqCst};
// Once the queue is less than 1/K full, then it will be downsized. Note that
// the deque requires that this number be less than 2.
static K: int = 4;
// Minimum number of bits that a buffer size should be. No buffer will resize to
// under this value, and all deques will initially contain a buffer of this
// size.
//
// The size in question is 1 << MIN_BITS
static MIN_BITS: uint = 7;
struct Deque<T> {
bottom: AtomicInt,
top: AtomicInt,
array: AtomicPtr<Buffer<T>>,
pool: BufferPool<T>,
}
/// Worker half of the work-stealing deque. This worker has exclusive access to
/// one side of the deque, and uses `push` and `pop` method to manipulate it.
///
/// There may only be one worker per deque.
pub struct Worker<T> {
deque: Arc<Deque<T>>,
noshare: marker::NoShare,
}
/// The stealing half of the work-stealing deque. Stealers have access to the
/// opposite end of the deque from the worker, and they only have access to the
/// `steal` method.
pub struct Stealer<T> {
deque: Arc<Deque<T>>,
noshare: marker::NoShare,
}
/// When stealing some data, this is an enumeration of the possible outcomes.
#[deriving(PartialEq, Show)]
pub enum Stolen<T> {
/// The deque was empty at the time of stealing
Empty,
/// The stealer lost the race for stealing data, and a retry may return more
/// data.
Abort,
/// The stealer has successfully stolen some data.
Data(T),
}
/// The allocation pool for buffers used by work-stealing deques. Right now this
/// structure is used for reclamation of memory after it is no longer in use by
/// deques.
///
/// This data structure is protected by a mutex, but it is rarely used. Deques
/// will only use this structure when allocating a new buffer or deallocating a
/// previous one.
pub struct BufferPool<T> {
pool: Arc<Exclusive<Vec<Box<Buffer<T>>>>>,
}
/// An internal buffer used by the chase-lev deque. This structure is actually
/// implemented as a circular buffer, and is used as the intermediate storage of
/// the data in the deque.
///
/// This type is implemented with *T instead of Vec<T> for two reasons:
///
/// 1. There is nothing safe about using this buffer. This easily allows the
/// same value to be read twice in to rust, and there is nothing to
/// prevent this. The usage by the deque must ensure that one of the
/// values is forgotten. Furthermore, we only ever want to manually run
/// destructors for values in this buffer (on drop) because the bounds
/// are defined by the deque it's owned by.
///
/// 2. We can certainly avoid bounds checks using *T instead of Vec<T>, although
/// LLVM is probably pretty good at doing this already.
struct Buffer<T> {
storage: *const T,
log_size: uint,
}
impl<T: Send> BufferPool<T> {
/// Allocates a new buffer pool which in turn can be used to allocate new
/// deques.
pub fn new() -> BufferPool<T> {
BufferPool { pool: Arc::new(Exclusive::new(Vec::new())) }
}
/// Allocates a new work-stealing deque which will send/receiving memory to
/// and from this buffer pool.
pub fn deque(&self) -> (Worker<T>, Stealer<T>) {
let a = Arc::new(Deque::new(self.clone()));
let b = a.clone();
(Worker { deque: a, noshare: marker::NoShare },
Stealer { deque: b, noshare: marker::NoShare })
}
fn alloc(&mut self, bits: uint) -> Box<Buffer<T>> {
unsafe {
let mut pool = self.pool.lock();
match pool.iter().position(|x| x.size() >= (1 << bits)) {
Some(i) => pool.remove(i).unwrap(),
None => box Buffer::new(bits)
}
}
}
fn free(&self, buf: Box<Buffer<T>>) {
unsafe {
let mut pool = self.pool.lock();
match pool.iter().position(|v| v.size() > buf.size()) {
Some(i) => pool.insert(i, buf),
None => pool.push(buf),
}
}
}
}
impl<T: Send> Clone for BufferPool<T> {
fn clone(&self) -> BufferPool<T> { BufferPool { pool: self.pool.clone() } }
}
impl<T: Send> Worker<T> {
/// Pushes data onto the front of this work queue.
pub fn push(&self, t: T) {
unsafe { self.deque.push(t) }
}
/// Pops data off the front of the work queue, returning `None` on an empty
/// queue.
pub fn pop(&self) -> Option<T> {
unsafe { self.deque.pop() }
}
/// Gets access to the buffer pool that this worker is attached to. This can
/// be used to create more deques which share the same buffer pool as this
/// deque.
pub fn pool<'a>(&'a self) -> &'a BufferPool<T> {
&self.deque.pool
}
}
impl<T: Send> Stealer<T> {
/// Steals work off the end of the queue (opposite of the worker's end)
pub fn steal(&self) -> Stolen<T> {
unsafe { self.deque.steal() }
}
/// Gets access to the buffer pool that this stealer is attached to. This
/// can be used to create more deques which share the same buffer pool as
/// this deque.
pub fn pool<'a>(&'a self) -> &'a BufferPool<T> {
&self.deque.pool
}
}
impl<T: Send> Clone for Stealer<T> {
fn clone(&self) -> Stealer<T> {
Stealer { deque: self.deque.clone(), noshare: marker::NoShare }
}
}
// Almost all of this code can be found directly in the paper so I'm not
// personally going to heavily comment what's going on here.
impl<T: Send> Deque<T> {
fn new(mut pool: BufferPool<T>) -> Deque<T> {
let buf = pool.alloc(MIN_BITS);
Deque {
bottom: AtomicInt::new(0),
top: AtomicInt::new(0),
array: AtomicPtr::new(unsafe { transmute(buf) }),
pool: pool,
}
}
unsafe fn push(&self, data: T) {
let mut b = self.bottom.load(SeqCst);
let t = self.top.load(SeqCst);
let mut a = self.array.load(SeqCst);
let size = b - t;
if size >= (*a).size() - 1 {
// You won't find this code in the chase-lev deque paper. This is
// alluded to in a small footnote, however. We always free a buffer
// when growing in order to prevent leaks.
a = self.swap_buffer(b, a, (*a).resize(b, t, 1));
b = self.bottom.load(SeqCst);
}
(*a).put(b, data);
self.bottom.store(b + 1, SeqCst);
}
unsafe fn pop(&self) -> Option<T> {
let b = self.bottom.load(SeqCst);
let a = self.array.load(SeqCst);
let b = b - 1;
self.bottom.store(b, SeqCst);
let t = self.top.load(SeqCst);
let size = b - t;
if size < 0 {
self.bottom.store(t, SeqCst);
return None;
}
let data = (*a).get(b);
if size > 0 {
self.maybe_shrink(b, t);
return Some(data);
}
if self.top.compare_and_swap(t, t + 1, SeqCst) == t {
self.bottom.store(t + 1, SeqCst);
return Some(data);
} else {
self.bottom.store(t + 1, SeqCst);
forget(data); // someone else stole this value
return None;
}
}
unsafe fn steal(&self) -> Stolen<T> {
let t = self.top.load(SeqCst);
let old = self.array.load(SeqCst);
let b = self.bottom.load(SeqCst);
let a = self.array.load(SeqCst);
let size = b - t;
if size <= 0 { return Empty }
if size % (*a).size() == 0 {
if a == old && t == self.top.load(SeqCst) {
return Empty
}
return Abort
}
let data = (*a).get(t);
if self.top.compare_and_swap(t, t + 1, SeqCst) == t {
Data(data)
} else {
forget(data); // someone else stole this value
Abort
}
}
unsafe fn maybe_shrink(&self, b: int, t: int) {
let a = self.array.load(SeqCst);
if b - t < (*a).size() / K && b - t > (1 << MIN_BITS) {
self.swap_buffer(b, a, (*a).resize(b, t, -1));
}
}
// Helper routine not mentioned in the paper which is used in growing and
// shrinking buffers to swap in a new buffer into place. As a bit of a
// recap, the whole point that we need a buffer pool rather than just
// calling malloc/free directly is that stealers can continue using buffers
// after this method has called 'free' on it. The continued usage is simply
// a read followed by a forget, but we must make sure that the memory can
// continue to be read after we flag this buffer for reclamation.
unsafe fn swap_buffer(&self, b: int, old: *mut Buffer<T>,
buf: Buffer<T>) -> *mut Buffer<T> {
let newbuf: *mut Buffer<T> = transmute(box buf);
self.array.store(newbuf, SeqCst);
let ss = (*newbuf).size();
self.bottom.store(b + ss, SeqCst);
let t = self.top.load(SeqCst);
if self.top.compare_and_swap(t, t + ss, SeqCst)!= t {
self.bottom.store(b, SeqCst);
}
self.pool.free(transmute(old));
return newbuf;
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Deque<T> {
fn drop(&mut self) {
let t = self.top.load(SeqCst);
let b = self.bottom.load(SeqCst);
let a = self.array.load(SeqCst);
// Free whatever is leftover in the dequeue, and then move the buffer
// back into the pool.
for i in range(t, b) {
let _: T = unsafe { (*a).get(i) };
}
self.pool.free(unsafe { transmute(a) });
}
}
#[inline]
fn buffer_alloc_size<T>(log_size: uint) -> uint {
(1 << log_size) * size_of::<T>()
}
impl<T: Send> Buffer<T> {
unsafe fn new(log_size: uint) -> Buffer<T> {
let size = buffer_alloc_size::<T>(log_size);
let buffer = allocate(size, min_align_of::<T>());
Buffer {
storage: buffer as *const T,
log_size: log_size,
}
}
fn size(&self) -> int { 1 << self.log_size }
// Apparently LLVM cannot optimize (foo % (1 << bar)) into this implicitly
fn mask(&self) -> int { (1 << self.log_size) - 1 }
unsafe fn elem(&self, i: int) -> *const T {
self.storage.offset(i & self.mask())
}
// This does not protect against loading duplicate values of the same cell,
// nor does this clear out the contents contained within. Hence, this is a
// very unsafe method which the caller needs to treat specially in case a
// race is lost.
unsafe fn get(&self, i: int) -> T {
ptr::read(self.elem(i))
}
// Unsafe because this unsafely overwrites possibly uninitialized or
// initialized data.
unsafe fn put(&self, i: int, t: T) {
ptr::write(self.elem(i) as *mut T, t);
}
// Again, unsafe because this has incredibly dubious ownership violations.
// It is assumed that this buffer is immediately dropped.
unsafe fn resize(&self, b: int, t: int, delta: int) -> Buffer<T> {
// NB: not entirely obvious, but thanks to 2's complement,
// casting delta to uint and then adding gives the desired
// effect.
let buf = Buffer::new(self.log_size + delta as uint);
for i in range(t, b) {
buf.put(i, self.get(i));
}
return buf;
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Buffer<T> {
fn drop(&mut self) {
// It is assumed that all buffers are empty on drop.
let size = buffer_alloc_size::<T>(self.log_size);
unsafe { deallocate(self.storage as *mut u8, size, min_align_of::<T>()) }
}
}
#[cfg(test)]
mod tests {
use std::prelude::*;
use super::{Data, BufferPool, Abort, Empty, Worker, Stealer};
use std::mem;
use std::rt::thread::Thread;
use std::rand;
use std::rand::Rng;
use atomics::{AtomicBool, INIT_ATOMIC_BOOL, SeqCst,
AtomicUint, INIT_ATOMIC_UINT};
use std::vec;
#[test]
fn smoke() {
let pool = BufferPool::new();
let (w, s) = pool.deque();
assert_eq!(w.pop(), None);
assert_eq!(s.steal(), Empty);
w.push(1i);
assert_eq!(w.pop(), Some(1));
w.push(1);
assert_eq!(s.steal(), Data(1));
w.push(1);
assert_eq!(s.clone().steal(), Data(1));
}
#[test]
fn stealpush() {
static AMT: int = 100000;
let pool = BufferPool::<int>::new();
let (w, s) = pool.deque();
let t = Thread::start(proc() {
let mut left = AMT;
while left > 0 {
match s.steal() {
Data(i) => {
assert_eq!(i, 1);
left -= 1;
}
Abort | Empty => {}
}
}
});
for _ in range(0, AMT) {
w.push(1);
}
t.join();
}
#[test]
fn stealpush_large() {
static AMT: int = 100000;
let pool = BufferPool::<(int, int)>::new();
let (w, s) = pool.deque();
let t = Thread::start(proc() {
let mut left = AMT;
while left > 0 {
match s.steal() {
Data((1, 10)) => { left -= 1; }
Data(..) => fail!(),
Abort | Empty => {}
}
}
});
for _ in range(0, AMT) {
w.push((1, 10));
}
t.join();
}
fn stampede(w: Worker<Box<int>>, s: Stealer<Box<int>>,
nthreads: int, amt: uint) {
for _ in range(0, amt) {
w.push(box 20);
}
let mut remaining = AtomicUint::new(amt);
let unsafe_remaining: *mut AtomicUint = &mut remaining;
let threads = range(0, nthreads).map(|_| {
let s = s.clone();
Thread::start(proc() {
unsafe {
while (*unsafe_remaining).load(SeqCst) > 0 {
match s.steal() {
Data(box 20) => {
(*unsafe_remaining).fetch_sub(1, SeqCst);
}
Data(..) => fail!(),
Abort | Empty => {}
}
}
}
})
}).collect::<Vec<Thread<()>>>();
while remaining.load(SeqCst) > 0 {
match w.pop() {
Some(box 20) => { remaining.fetch_sub(1, SeqCst); }
Some(..) => fail!(),
None => {}
}
}
for thread in threads.move_iter() {
thread.join();
}
}
#[test]
fn run_stampede() {
let pool = BufferPool::<Box<int>>::new();
let (w, s) = pool.deque();
stampede(w, s, 8, 10000);
}
#[test]
fn many_stampede() {
static AMT: uint = 4;
let pool = BufferPool::<Box<int>>::new();
let threads = range(0, AMT).map(|_| {
let (w, s) = pool.deque();
Thread::start(proc() {
stampede(w, s, 4, 10000);
})
}).collect::<Vec<Thread<()>>>();
for thread in threads.move_iter() {
thread.join();
}
}
#[test]
fn stress() {
static AMT: int = 100000;
static NTHREADS: int = 8;
static mut DONE: AtomicBool = INIT_ATOMIC_BOOL;
static mut HITS: AtomicUint = INIT_ATOMIC_UINT;
let pool = BufferPool::<int>::new();
let (w, s) = pool.deque();
let threads = range(0, NTHREADS).map(|_| {
let s = s.clone();
Thread::start(proc() {
unsafe {
loop {
match s.steal() {
Data(2) => { HITS.fetch_add(1, SeqCst); }
Data(..) => fail!(),
_ if DONE.load(SeqCst) => break,
_ => {}
}
}
}
})
}).collect::<Vec<Thread<()>>>();
let mut rng = rand::task_rng();
let mut expected = 0;
while expected < AMT {
if rng.gen_range(0i, 3) == 2 {
match w.pop() {
None => {}
Some(2) => unsafe { HITS.fetch_add(1, SeqCst); },
Some(_) => fail!(),
}
} else {
expected += 1;
w.push(2);
}
}
unsafe {
while HITS.load(SeqCst) < AMT as uint {
match w.pop() {
None => {}
Some(2) => { HITS.fetch_add(1, SeqCst); },
|
//! let mut pool = BufferPool::new();
//! let (mut worker, mut stealer) = pool.deque();
|
random_line_split
|
|
mod.rs
|
return;
}
let hir_id = tcx.hir().local_def_id_to_hir_id(mir_source.def_id().expect_local());
let is_fn_like = tcx.hir().get(hir_id).fn_kind().is_some();
// Only instrument functions, methods, and closures (not constants since they are evaluated
// at compile time by Miri).
// FIXME(#73156): Handle source code coverage in const eval, but note, if and when const
// expressions get coverage spans, we will probably have to "carve out" space for const
// expressions from coverage spans in enclosing MIR's, like we do for closures. (That might
// be tricky if const expressions have no corresponding statements in the enclosing MIR.
// Closures are carved out by their initial `Assign` statement.)
if!is_fn_like {
trace!("InstrumentCoverage skipped for {:?} (not an fn-like)", mir_source.def_id());
return;
}
match mir_body.basic_blocks()[mir::START_BLOCK].terminator().kind {
TerminatorKind::Unreachable => {
trace!("InstrumentCoverage skipped for unreachable `START_BLOCK`");
return;
}
_ => {}
}
let codegen_fn_attrs = tcx.codegen_fn_attrs(mir_source.def_id());
if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_COVERAGE) {
return;
}
trace!("InstrumentCoverage starting for {:?}", mir_source.def_id());
Instrumentor::new(&self.name(), tcx, mir_body).inject_counters();
trace!("InstrumentCoverage done for {:?}", mir_source.def_id());
}
}
struct Instrumentor<'a, 'tcx> {
pass_name: &'a str,
tcx: TyCtxt<'tcx>,
mir_body: &'a mut mir::Body<'tcx>,
source_file: Lrc<SourceFile>,
fn_sig_span: Span,
body_span: Span,
basic_coverage_blocks: CoverageGraph,
coverage_counters: CoverageCounters,
}
impl<'a, 'tcx> Instrumentor<'a, 'tcx> {
fn new(pass_name: &'a str, tcx: TyCtxt<'tcx>, mir_body: &'a mut mir::Body<'tcx>) -> Self {
let source_map = tcx.sess.source_map();
let def_id = mir_body.source.def_id();
let (some_fn_sig, hir_body) = fn_sig_and_body(tcx, def_id);
let body_span = get_body_span(tcx, hir_body, mir_body);
let source_file = source_map.lookup_source_file(body_span.lo());
let fn_sig_span = match some_fn_sig.filter(|fn_sig| {
fn_sig.span.ctxt() == body_span.ctxt()
&& Lrc::ptr_eq(&source_file, &source_map.lookup_source_file(fn_sig.span.lo()))
}) {
Some(fn_sig) => fn_sig.span.with_hi(body_span.lo()),
None => body_span.shrink_to_lo(),
};
debug!(
"instrumenting {}: {:?}, fn sig span: {:?}, body span: {:?}",
if tcx.is_closure(def_id) { "closure" } else { "function" },
def_id,
fn_sig_span,
body_span
);
let function_source_hash = hash_mir_source(tcx, hir_body);
let basic_coverage_blocks = CoverageGraph::from_mir(mir_body);
Self {
pass_name,
tcx,
mir_body,
source_file,
fn_sig_span,
body_span,
basic_coverage_blocks,
coverage_counters: CoverageCounters::new(function_source_hash),
}
}
fn inject_counters(&'a mut self) {
let tcx = self.tcx;
let mir_source = self.mir_body.source;
let def_id = mir_source.def_id();
let fn_sig_span = self.fn_sig_span;
let body_span = self.body_span;
let mut graphviz_data = debug::GraphvizData::new();
let mut debug_used_expressions = debug::UsedExpressions::new();
let dump_mir = dump_enabled(tcx, self.pass_name, def_id);
let dump_graphviz = dump_mir && tcx.sess.opts.debugging_opts.dump_mir_graphviz;
let dump_spanview = dump_mir && tcx.sess.opts.debugging_opts.dump_mir_spanview.is_some();
if dump_graphviz {
graphviz_data.enable();
self.coverage_counters.enable_debug();
}
if dump_graphviz || level_enabled!(tracing::Level::DEBUG) {
debug_used_expressions.enable();
}
////////////////////////////////////////////////////
// Compute `CoverageSpan`s from the `CoverageGraph`.
let coverage_spans = CoverageSpans::generate_coverage_spans(
&self.mir_body,
fn_sig_span,
body_span,
&self.basic_coverage_blocks,
);
if dump_spanview {
debug::dump_coverage_spanview(
tcx,
self.mir_body,
&self.basic_coverage_blocks,
self.pass_name,
body_span,
&coverage_spans,
);
}
////////////////////////////////////////////////////
// Create an optimized mix of `Counter`s and `Expression`s for the `CoverageGraph`. Ensure
// every `CoverageSpan` has a `Counter` or `Expression` assigned to its `BasicCoverageBlock`
// and all `Expression` dependencies (operands) are also generated, for any other
// `BasicCoverageBlock`s not already associated with a `CoverageSpan`.
//
// Intermediate expressions (used to compute other `Expression` values), which have no
// direct associate to any `BasicCoverageBlock`, are returned in the method `Result`.
let intermediate_expressions_or_error = self
.coverage_counters
.make_bcb_counters(&mut self.basic_coverage_blocks, &coverage_spans);
let (result, intermediate_expressions) = match intermediate_expressions_or_error {
Ok(intermediate_expressions) => {
// If debugging, add any intermediate expressions (which are not associated with any
// BCB) to the `debug_used_expressions` map.
if debug_used_expressions.is_enabled() {
for intermediate_expression in &intermediate_expressions {
debug_used_expressions.add_expression_operands(intermediate_expression);
}
}
////////////////////////////////////////////////////
// Remove the counter or edge counter from of each `CoverageSpan`s associated
// `BasicCoverageBlock`, and inject a `Coverage` statement into the MIR.
//
// `Coverage` statements injected from `CoverageSpan`s will include the code regions
// (source code start and end positions) to be counted by the associated counter.
//
// These `CoverageSpan`-associated counters are removed from their associated
// `BasicCoverageBlock`s so that the only remaining counters in the `CoverageGraph`
// are indirect counters (to be injected next, without associated code regions).
self.inject_coverage_span_counters(
coverage_spans,
&mut graphviz_data,
&mut debug_used_expressions,
);
////////////////////////////////////////////////////
// For any remaining `BasicCoverageBlock` counters (that were not associated with
// any `CoverageSpan`), inject `Coverage` statements (_without_ code region `Span`s)
// to ensure `BasicCoverageBlock` counters that other `Expression`s may depend on
// are in fact counted, even though they don't directly contribute to counting
// their own independent code region's coverage.
self.inject_indirect_counters(&mut graphviz_data, &mut debug_used_expressions);
// Intermediate expressions will be injected as the final step, after generating
// debug output, if any.
////////////////////////////////////////////////////
(Ok(()), intermediate_expressions)
}
Err(e) => (Err(e), Vec::new()),
};
if graphviz_data.is_enabled() {
// Even if there was an error, a partial CoverageGraph can still generate a useful
// graphviz output.
debug::dump_coverage_graphviz(
tcx,
self.mir_body,
self.pass_name,
&self.basic_coverage_blocks,
&self.coverage_counters.debug_counters,
&graphviz_data,
&intermediate_expressions,
&debug_used_expressions,
);
}
if let Err(e) = result {
bug!("Error processing: {:?}: {:?}", self.mir_body.source.def_id(), e.message)
};
// Depending on current `debug_options()`, `alert_on_unused_expressions()` could panic, so
// this check is performed as late as possible, to allow other debug output (logs and dump
// files), which might be helpful in analyzing unused expressions, to still be generated.
debug_used_expressions.alert_on_unused_expressions(&self.coverage_counters.debug_counters);
////////////////////////////////////////////////////
// Finally, inject the intermediate expressions collected along the way.
for intermediate_expression in intermediate_expressions {
inject_intermediate_expression(self.mir_body, intermediate_expression);
}
}
/// Inject a counter for each `CoverageSpan`. There can be multiple `CoverageSpan`s for a given
/// BCB, but only one actual counter needs to be incremented per BCB. `bb_counters` maps each
/// `bcb` to its `Counter`, when injected. Subsequent `CoverageSpan`s for a BCB that already has
/// a `Counter` will inject an `Expression` instead, and compute its value by adding `ZERO` to
/// the BCB `Counter` value.
///
/// If debugging, add every BCB `Expression` associated with a `CoverageSpan`s to the
/// `used_expression_operands` map.
fn inject_coverage_span_counters(
&mut self,
coverage_spans: Vec<CoverageSpan>,
graphviz_data: &mut debug::GraphvizData,
debug_used_expressions: &mut debug::UsedExpressions,
) {
let tcx = self.tcx;
let source_map = tcx.sess.source_map();
let body_span = self.body_span;
let file_name = Symbol::intern(&self.source_file.name.prefer_remapped().to_string_lossy());
let mut bcb_counters = IndexVec::from_elem_n(None, self.basic_coverage_blocks.num_nodes());
for covspan in coverage_spans {
let bcb = covspan.bcb;
let span = covspan.span;
let counter_kind = if let Some(&counter_operand) = bcb_counters[bcb].as_ref() {
self.coverage_counters.make_identity_counter(counter_operand)
} else if let Some(counter_kind) = self.bcb_data_mut(bcb).take_counter() {
bcb_counters[bcb] = Some(counter_kind.as_operand_id());
debug_used_expressions.add_expression_operands(&counter_kind);
counter_kind
} else {
bug!("Every BasicCoverageBlock should have a Counter or Expression");
};
graphviz_data.add_bcb_coverage_span_with_counter(bcb, &covspan, &counter_kind);
debug!(
"Calling make_code_region(file_name={}, source_file={:?}, span={}, body_span={})",
file_name,
self.source_file,
source_map.span_to_diagnostic_string(span),
source_map.span_to_diagnostic_string(body_span)
);
inject_statement(
self.mir_body,
counter_kind,
self.bcb_leader_bb(bcb),
Some(make_code_region(source_map, file_name, &self.source_file, span, body_span)),
);
}
}
/// `inject_coverage_span_counters()` looped through the `CoverageSpan`s and injected the
/// counter from the `CoverageSpan`s `BasicCoverageBlock`, removing it from the BCB in the
/// process (via `take_counter()`).
///
/// Any other counter associated with a `BasicCoverageBlock`, or its incoming edge, but not
/// associated with a `CoverageSpan`, should only exist if the counter is an `Expression`
/// dependency (one of the expression operands). Collect them, and inject the additional
/// counters into the MIR, without a reportable coverage span.
fn inject_indirect_counters(
&mut self,
graphviz_data: &mut debug::GraphvizData,
debug_used_expressions: &mut debug::UsedExpressions,
|
for (target_bcb, target_bcb_data) in self.basic_coverage_blocks.iter_enumerated_mut() {
if let Some(counter_kind) = target_bcb_data.take_counter() {
bcb_counters_without_direct_coverage_spans.push((None, target_bcb, counter_kind));
}
if let Some(edge_counters) = target_bcb_data.take_edge_counters() {
for (from_bcb, counter_kind) in edge_counters {
bcb_counters_without_direct_coverage_spans.push((
Some(from_bcb),
target_bcb,
counter_kind,
));
}
}
}
// If debug is enabled, validate that every BCB or edge counter not directly associated
// with a coverage span is at least indirectly associated (it is a dependency of a BCB
// counter that _is_ associated with a coverage span).
debug_used_expressions.validate(&bcb_counters_without_direct_coverage_spans);
for (edge_from_bcb, target_bcb, counter_kind) in bcb_counters_without_direct_coverage_spans
{
debug_used_expressions.add_unused_expression_if_not_found(
&counter_kind,
edge_from_bcb,
target_bcb,
);
match counter_kind {
CoverageKind::Counter {.. } => {
let inject_to_bb = if let Some(from_bcb) = edge_from_bcb {
// The MIR edge starts `from_bb` (the outgoing / last BasicBlock in
// `from_bcb`) and ends at `to_bb` (the incoming / first BasicBlock in the
// `target_bcb`; also called the `leader_bb`).
let from_bb = self.bcb_last_bb(from_bcb);
let to_bb = self.bcb_leader_bb(target_bcb);
let new_bb = inject_edge_counter_basic_block(self.mir_body, from_bb, to_bb);
graphviz_data.set_edge_counter(from_bcb, new_bb, &counter_kind);
debug!(
"Edge {:?} (last {:?}) -> {:?} (leader {:?}) requires a new MIR \
BasicBlock {:?}, for unclaimed edge counter {}",
edge_from_bcb,
from_bb,
target_bcb,
to_bb,
new_bb,
self.format_counter(&counter_kind),
);
new_bb
} else {
let target_bb = self.bcb_last_bb(target_bcb);
graphviz_data.add_bcb_dependency_counter(target_bcb, &counter_kind);
debug!(
"{:?} ({:?}) gets a new Coverage statement for unclaimed counter {}",
target_bcb,
target_bb,
self.format_counter(&counter_kind),
);
target_bb
};
inject_statement(self.mir_body, counter_kind, inject_to_bb, None);
}
CoverageKind::Expression {.. } => {
inject_intermediate_expression(self.mir_body, counter_kind)
}
_ => bug!("CoverageKind should be a counter"),
}
}
}
#[inline]
fn bcb_leader_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock {
self.bcb_data(bcb).leader_bb()
}
#[inline]
fn bcb_last_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock {
self.bcb_data(bcb).last_bb()
}
#[inline]
fn bcb_data(&self, bcb: BasicCoverageBlock) -> &BasicCoverageBlockData {
&self.basic_coverage_blocks[bcb]
}
#[inline]
fn bcb_data_mut(&mut self, bcb: BasicCoverageBlock) -> &mut BasicCoverageBlockData {
&mut self.basic_coverage_blocks[bcb]
}
#[inline]
fn format_counter(&self, counter_kind: &CoverageKind) -> String {
self.coverage_counters.debug_counters.format_counter(counter_kind)
}
}
fn inject_edge_counter_basic_block(
mir_body: &mut mir::Body<'tcx>,
from_bb: BasicBlock,
to_bb: BasicBlock,
) -> BasicBlock {
let span = mir_body[from_bb].terminator().source_info.span.shrink_to_hi();
let new_bb = mir_body.basic_blocks_mut().push(BasicBlockData {
statements: vec![], // counter will be injected here
terminator: Some(Terminator {
source_info: SourceInfo::outermost(span),
kind: TerminatorKind::Goto { target: to_bb },
}),
is_cleanup: false,
});
let edge_ref = mir_body[from_bb]
.terminator_mut()
.successors_mut()
.find(|successor| **successor == to_bb)
.expect("from_bb should have a successor for to_bb");
*edge_ref = new_bb;
new_bb
}
fn inject_statement(
mir_body: &mut mir::Body<'tcx>,
counter_kind: CoverageKind,
bb: BasicBlock,
some_code_region: Option<CodeRegion>,
) {
debug!(
" injecting statement {:?} for {:?} at code region: {:?}",
counter_kind, bb, some_code_region
);
let data = &mut mir_body[bb];
let source_info = data.terminator().source_info;
let statement = Statement {
source_info,
kind: StatementKind::Coverage(Box::new(Coverage {
kind: counter_kind,
code_region: some_code_region,
})),
};
data.statements.insert(0, statement);
}
// Non-code expressions are injected into the coverage map, without generating executable code.
fn inject_intermediate_expression(mir_body: &mut mir::
|
) {
let mut bcb_counters_without_direct_coverage_spans = Vec::new();
|
random_line_split
|
mod.rs
|
return;
}
let hir_id = tcx.hir().local_def_id_to_hir_id(mir_source.def_id().expect_local());
let is_fn_like = tcx.hir().get(hir_id).fn_kind().is_some();
// Only instrument functions, methods, and closures (not constants since they are evaluated
// at compile time by Miri).
// FIXME(#73156): Handle source code coverage in const eval, but note, if and when const
// expressions get coverage spans, we will probably have to "carve out" space for const
// expressions from coverage spans in enclosing MIR's, like we do for closures. (That might
// be tricky if const expressions have no corresponding statements in the enclosing MIR.
// Closures are carved out by their initial `Assign` statement.)
if!is_fn_like {
trace!("InstrumentCoverage skipped for {:?} (not an fn-like)", mir_source.def_id());
return;
}
match mir_body.basic_blocks()[mir::START_BLOCK].terminator().kind {
TerminatorKind::Unreachable => {
trace!("InstrumentCoverage skipped for unreachable `START_BLOCK`");
return;
}
_ => {}
}
let codegen_fn_attrs = tcx.codegen_fn_attrs(mir_source.def_id());
if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_COVERAGE) {
return;
}
trace!("InstrumentCoverage starting for {:?}", mir_source.def_id());
Instrumentor::new(&self.name(), tcx, mir_body).inject_counters();
trace!("InstrumentCoverage done for {:?}", mir_source.def_id());
}
}
struct Instrumentor<'a, 'tcx> {
pass_name: &'a str,
tcx: TyCtxt<'tcx>,
mir_body: &'a mut mir::Body<'tcx>,
source_file: Lrc<SourceFile>,
fn_sig_span: Span,
body_span: Span,
basic_coverage_blocks: CoverageGraph,
coverage_counters: CoverageCounters,
}
impl<'a, 'tcx> Instrumentor<'a, 'tcx> {
fn new(pass_name: &'a str, tcx: TyCtxt<'tcx>, mir_body: &'a mut mir::Body<'tcx>) -> Self {
let source_map = tcx.sess.source_map();
let def_id = mir_body.source.def_id();
let (some_fn_sig, hir_body) = fn_sig_and_body(tcx, def_id);
let body_span = get_body_span(tcx, hir_body, mir_body);
let source_file = source_map.lookup_source_file(body_span.lo());
let fn_sig_span = match some_fn_sig.filter(|fn_sig| {
fn_sig.span.ctxt() == body_span.ctxt()
&& Lrc::ptr_eq(&source_file, &source_map.lookup_source_file(fn_sig.span.lo()))
}) {
Some(fn_sig) => fn_sig.span.with_hi(body_span.lo()),
None => body_span.shrink_to_lo(),
};
debug!(
"instrumenting {}: {:?}, fn sig span: {:?}, body span: {:?}",
if tcx.is_closure(def_id) { "closure" } else { "function" },
def_id,
fn_sig_span,
body_span
);
let function_source_hash = hash_mir_source(tcx, hir_body);
let basic_coverage_blocks = CoverageGraph::from_mir(mir_body);
Self {
pass_name,
tcx,
mir_body,
source_file,
fn_sig_span,
body_span,
basic_coverage_blocks,
coverage_counters: CoverageCounters::new(function_source_hash),
}
}
fn inject_counters(&'a mut self) {
let tcx = self.tcx;
let mir_source = self.mir_body.source;
let def_id = mir_source.def_id();
let fn_sig_span = self.fn_sig_span;
let body_span = self.body_span;
let mut graphviz_data = debug::GraphvizData::new();
let mut debug_used_expressions = debug::UsedExpressions::new();
let dump_mir = dump_enabled(tcx, self.pass_name, def_id);
let dump_graphviz = dump_mir && tcx.sess.opts.debugging_opts.dump_mir_graphviz;
let dump_spanview = dump_mir && tcx.sess.opts.debugging_opts.dump_mir_spanview.is_some();
if dump_graphviz {
graphviz_data.enable();
self.coverage_counters.enable_debug();
}
if dump_graphviz || level_enabled!(tracing::Level::DEBUG) {
debug_used_expressions.enable();
}
////////////////////////////////////////////////////
// Compute `CoverageSpan`s from the `CoverageGraph`.
let coverage_spans = CoverageSpans::generate_coverage_spans(
&self.mir_body,
fn_sig_span,
body_span,
&self.basic_coverage_blocks,
);
if dump_spanview {
debug::dump_coverage_spanview(
tcx,
self.mir_body,
&self.basic_coverage_blocks,
self.pass_name,
body_span,
&coverage_spans,
);
}
////////////////////////////////////////////////////
// Create an optimized mix of `Counter`s and `Expression`s for the `CoverageGraph`. Ensure
// every `CoverageSpan` has a `Counter` or `Expression` assigned to its `BasicCoverageBlock`
// and all `Expression` dependencies (operands) are also generated, for any other
// `BasicCoverageBlock`s not already associated with a `CoverageSpan`.
//
// Intermediate expressions (used to compute other `Expression` values), which have no
// direct associate to any `BasicCoverageBlock`, are returned in the method `Result`.
let intermediate_expressions_or_error = self
.coverage_counters
.make_bcb_counters(&mut self.basic_coverage_blocks, &coverage_spans);
let (result, intermediate_expressions) = match intermediate_expressions_or_error {
Ok(intermediate_expressions) => {
// If debugging, add any intermediate expressions (which are not associated with any
// BCB) to the `debug_used_expressions` map.
if debug_used_expressions.is_enabled() {
for intermediate_expression in &intermediate_expressions {
debug_used_expressions.add_expression_operands(intermediate_expression);
}
}
////////////////////////////////////////////////////
// Remove the counter or edge counter from of each `CoverageSpan`s associated
// `BasicCoverageBlock`, and inject a `Coverage` statement into the MIR.
//
// `Coverage` statements injected from `CoverageSpan`s will include the code regions
// (source code start and end positions) to be counted by the associated counter.
//
// These `CoverageSpan`-associated counters are removed from their associated
// `BasicCoverageBlock`s so that the only remaining counters in the `CoverageGraph`
// are indirect counters (to be injected next, without associated code regions).
self.inject_coverage_span_counters(
coverage_spans,
&mut graphviz_data,
&mut debug_used_expressions,
);
////////////////////////////////////////////////////
// For any remaining `BasicCoverageBlock` counters (that were not associated with
// any `CoverageSpan`), inject `Coverage` statements (_without_ code region `Span`s)
// to ensure `BasicCoverageBlock` counters that other `Expression`s may depend on
// are in fact counted, even though they don't directly contribute to counting
// their own independent code region's coverage.
self.inject_indirect_counters(&mut graphviz_data, &mut debug_used_expressions);
// Intermediate expressions will be injected as the final step, after generating
// debug output, if any.
////////////////////////////////////////////////////
(Ok(()), intermediate_expressions)
}
Err(e) => (Err(e), Vec::new()),
};
if graphviz_data.is_enabled() {
// Even if there was an error, a partial CoverageGraph can still generate a useful
// graphviz output.
debug::dump_coverage_graphviz(
tcx,
self.mir_body,
self.pass_name,
&self.basic_coverage_blocks,
&self.coverage_counters.debug_counters,
&graphviz_data,
&intermediate_expressions,
&debug_used_expressions,
);
}
if let Err(e) = result {
bug!("Error processing: {:?}: {:?}", self.mir_body.source.def_id(), e.message)
};
// Depending on current `debug_options()`, `alert_on_unused_expressions()` could panic, so
// this check is performed as late as possible, to allow other debug output (logs and dump
// files), which might be helpful in analyzing unused expressions, to still be generated.
debug_used_expressions.alert_on_unused_expressions(&self.coverage_counters.debug_counters);
////////////////////////////////////////////////////
// Finally, inject the intermediate expressions collected along the way.
for intermediate_expression in intermediate_expressions {
inject_intermediate_expression(self.mir_body, intermediate_expression);
}
}
/// Inject a counter for each `CoverageSpan`. There can be multiple `CoverageSpan`s for a given
/// BCB, but only one actual counter needs to be incremented per BCB. `bb_counters` maps each
/// `bcb` to its `Counter`, when injected. Subsequent `CoverageSpan`s for a BCB that already has
/// a `Counter` will inject an `Expression` instead, and compute its value by adding `ZERO` to
/// the BCB `Counter` value.
///
/// If debugging, add every BCB `Expression` associated with a `CoverageSpan`s to the
/// `used_expression_operands` map.
fn inject_coverage_span_counters(
&mut self,
coverage_spans: Vec<CoverageSpan>,
graphviz_data: &mut debug::GraphvizData,
debug_used_expressions: &mut debug::UsedExpressions,
) {
let tcx = self.tcx;
let source_map = tcx.sess.source_map();
let body_span = self.body_span;
let file_name = Symbol::intern(&self.source_file.name.prefer_remapped().to_string_lossy());
let mut bcb_counters = IndexVec::from_elem_n(None, self.basic_coverage_blocks.num_nodes());
for covspan in coverage_spans {
let bcb = covspan.bcb;
let span = covspan.span;
let counter_kind = if let Some(&counter_operand) = bcb_counters[bcb].as_ref() {
self.coverage_counters.make_identity_counter(counter_operand)
} else if let Some(counter_kind) = self.bcb_data_mut(bcb).take_counter() {
bcb_counters[bcb] = Some(counter_kind.as_operand_id());
debug_used_expressions.add_expression_operands(&counter_kind);
counter_kind
} else {
bug!("Every BasicCoverageBlock should have a Counter or Expression");
};
graphviz_data.add_bcb_coverage_span_with_counter(bcb, &covspan, &counter_kind);
debug!(
"Calling make_code_region(file_name={}, source_file={:?}, span={}, body_span={})",
file_name,
self.source_file,
source_map.span_to_diagnostic_string(span),
source_map.span_to_diagnostic_string(body_span)
);
inject_statement(
self.mir_body,
counter_kind,
self.bcb_leader_bb(bcb),
Some(make_code_region(source_map, file_name, &self.source_file, span, body_span)),
);
}
}
/// `inject_coverage_span_counters()` looped through the `CoverageSpan`s and injected the
/// counter from the `CoverageSpan`s `BasicCoverageBlock`, removing it from the BCB in the
/// process (via `take_counter()`).
///
/// Any other counter associated with a `BasicCoverageBlock`, or its incoming edge, but not
/// associated with a `CoverageSpan`, should only exist if the counter is an `Expression`
/// dependency (one of the expression operands). Collect them, and inject the additional
/// counters into the MIR, without a reportable coverage span.
fn inject_indirect_counters(
&mut self,
graphviz_data: &mut debug::GraphvizData,
debug_used_expressions: &mut debug::UsedExpressions,
) {
let mut bcb_counters_without_direct_coverage_spans = Vec::new();
for (target_bcb, target_bcb_data) in self.basic_coverage_blocks.iter_enumerated_mut() {
if let Some(counter_kind) = target_bcb_data.take_counter() {
bcb_counters_without_direct_coverage_spans.push((None, target_bcb, counter_kind));
}
if let Some(edge_counters) = target_bcb_data.take_edge_counters() {
for (from_bcb, counter_kind) in edge_counters {
bcb_counters_without_direct_coverage_spans.push((
Some(from_bcb),
target_bcb,
counter_kind,
));
}
}
}
// If debug is enabled, validate that every BCB or edge counter not directly associated
// with a coverage span is at least indirectly associated (it is a dependency of a BCB
// counter that _is_ associated with a coverage span).
debug_used_expressions.validate(&bcb_counters_without_direct_coverage_spans);
for (edge_from_bcb, target_bcb, counter_kind) in bcb_counters_without_direct_coverage_spans
{
debug_used_expressions.add_unused_expression_if_not_found(
&counter_kind,
edge_from_bcb,
target_bcb,
);
match counter_kind {
CoverageKind::Counter {.. } => {
let inject_to_bb = if let Some(from_bcb) = edge_from_bcb {
// The MIR edge starts `from_bb` (the outgoing / last BasicBlock in
// `from_bcb`) and ends at `to_bb` (the incoming / first BasicBlock in the
// `target_bcb`; also called the `leader_bb`).
let from_bb = self.bcb_last_bb(from_bcb);
let to_bb = self.bcb_leader_bb(target_bcb);
let new_bb = inject_edge_counter_basic_block(self.mir_body, from_bb, to_bb);
graphviz_data.set_edge_counter(from_bcb, new_bb, &counter_kind);
debug!(
"Edge {:?} (last {:?}) -> {:?} (leader {:?}) requires a new MIR \
BasicBlock {:?}, for unclaimed edge counter {}",
edge_from_bcb,
from_bb,
target_bcb,
to_bb,
new_bb,
self.format_counter(&counter_kind),
);
new_bb
} else {
let target_bb = self.bcb_last_bb(target_bcb);
graphviz_data.add_bcb_dependency_counter(target_bcb, &counter_kind);
debug!(
"{:?} ({:?}) gets a new Coverage statement for unclaimed counter {}",
target_bcb,
target_bb,
self.format_counter(&counter_kind),
);
target_bb
};
inject_statement(self.mir_body, counter_kind, inject_to_bb, None);
}
CoverageKind::Expression {.. } => {
inject_intermediate_expression(self.mir_body, counter_kind)
}
_ => bug!("CoverageKind should be a counter"),
}
}
}
#[inline]
fn bcb_leader_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock {
self.bcb_data(bcb).leader_bb()
}
#[inline]
fn
|
(&self, bcb: BasicCoverageBlock) -> BasicBlock {
self.bcb_data(bcb).last_bb()
}
#[inline]
fn bcb_data(&self, bcb: BasicCoverageBlock) -> &BasicCoverageBlockData {
&self.basic_coverage_blocks[bcb]
}
#[inline]
fn bcb_data_mut(&mut self, bcb: BasicCoverageBlock) -> &mut BasicCoverageBlockData {
&mut self.basic_coverage_blocks[bcb]
}
#[inline]
fn format_counter(&self, counter_kind: &CoverageKind) -> String {
self.coverage_counters.debug_counters.format_counter(counter_kind)
}
}
fn inject_edge_counter_basic_block(
mir_body: &mut mir::Body<'tcx>,
from_bb: BasicBlock,
to_bb: BasicBlock,
) -> BasicBlock {
let span = mir_body[from_bb].terminator().source_info.span.shrink_to_hi();
let new_bb = mir_body.basic_blocks_mut().push(BasicBlockData {
statements: vec![], // counter will be injected here
terminator: Some(Terminator {
source_info: SourceInfo::outermost(span),
kind: TerminatorKind::Goto { target: to_bb },
}),
is_cleanup: false,
});
let edge_ref = mir_body[from_bb]
.terminator_mut()
.successors_mut()
.find(|successor| **successor == to_bb)
.expect("from_bb should have a successor for to_bb");
*edge_ref = new_bb;
new_bb
}
fn inject_statement(
mir_body: &mut mir::Body<'tcx>,
counter_kind: CoverageKind,
bb: BasicBlock,
some_code_region: Option<CodeRegion>,
) {
debug!(
" injecting statement {:?} for {:?} at code region: {:?}",
counter_kind, bb, some_code_region
);
let data = &mut mir_body[bb];
let source_info = data.terminator().source_info;
let statement = Statement {
source_info,
kind: StatementKind::Coverage(Box::new(Coverage {
kind: counter_kind,
code_region: some_code_region,
})),
};
data.statements.insert(0, statement);
}
// Non-code expressions are injected into the coverage map, without generating executable code.
fn inject_intermediate_expression(mir_body: &mut mir
|
bcb_last_bb
|
identifier_name
|
mod.rs
|
);
let function_source_hash = hash_mir_source(tcx, hir_body);
let basic_coverage_blocks = CoverageGraph::from_mir(mir_body);
Self {
pass_name,
tcx,
mir_body,
source_file,
fn_sig_span,
body_span,
basic_coverage_blocks,
coverage_counters: CoverageCounters::new(function_source_hash),
}
}
fn inject_counters(&'a mut self) {
let tcx = self.tcx;
let mir_source = self.mir_body.source;
let def_id = mir_source.def_id();
let fn_sig_span = self.fn_sig_span;
let body_span = self.body_span;
let mut graphviz_data = debug::GraphvizData::new();
let mut debug_used_expressions = debug::UsedExpressions::new();
let dump_mir = dump_enabled(tcx, self.pass_name, def_id);
let dump_graphviz = dump_mir && tcx.sess.opts.debugging_opts.dump_mir_graphviz;
let dump_spanview = dump_mir && tcx.sess.opts.debugging_opts.dump_mir_spanview.is_some();
if dump_graphviz {
graphviz_data.enable();
self.coverage_counters.enable_debug();
}
if dump_graphviz || level_enabled!(tracing::Level::DEBUG) {
debug_used_expressions.enable();
}
////////////////////////////////////////////////////
// Compute `CoverageSpan`s from the `CoverageGraph`.
let coverage_spans = CoverageSpans::generate_coverage_spans(
&self.mir_body,
fn_sig_span,
body_span,
&self.basic_coverage_blocks,
);
if dump_spanview {
debug::dump_coverage_spanview(
tcx,
self.mir_body,
&self.basic_coverage_blocks,
self.pass_name,
body_span,
&coverage_spans,
);
}
////////////////////////////////////////////////////
// Create an optimized mix of `Counter`s and `Expression`s for the `CoverageGraph`. Ensure
// every `CoverageSpan` has a `Counter` or `Expression` assigned to its `BasicCoverageBlock`
// and all `Expression` dependencies (operands) are also generated, for any other
// `BasicCoverageBlock`s not already associated with a `CoverageSpan`.
//
// Intermediate expressions (used to compute other `Expression` values), which have no
// direct associate to any `BasicCoverageBlock`, are returned in the method `Result`.
let intermediate_expressions_or_error = self
.coverage_counters
.make_bcb_counters(&mut self.basic_coverage_blocks, &coverage_spans);
let (result, intermediate_expressions) = match intermediate_expressions_or_error {
Ok(intermediate_expressions) => {
// If debugging, add any intermediate expressions (which are not associated with any
// BCB) to the `debug_used_expressions` map.
if debug_used_expressions.is_enabled() {
for intermediate_expression in &intermediate_expressions {
debug_used_expressions.add_expression_operands(intermediate_expression);
}
}
////////////////////////////////////////////////////
// Remove the counter or edge counter from of each `CoverageSpan`s associated
// `BasicCoverageBlock`, and inject a `Coverage` statement into the MIR.
//
// `Coverage` statements injected from `CoverageSpan`s will include the code regions
// (source code start and end positions) to be counted by the associated counter.
//
// These `CoverageSpan`-associated counters are removed from their associated
// `BasicCoverageBlock`s so that the only remaining counters in the `CoverageGraph`
// are indirect counters (to be injected next, without associated code regions).
self.inject_coverage_span_counters(
coverage_spans,
&mut graphviz_data,
&mut debug_used_expressions,
);
////////////////////////////////////////////////////
// For any remaining `BasicCoverageBlock` counters (that were not associated with
// any `CoverageSpan`), inject `Coverage` statements (_without_ code region `Span`s)
// to ensure `BasicCoverageBlock` counters that other `Expression`s may depend on
// are in fact counted, even though they don't directly contribute to counting
// their own independent code region's coverage.
self.inject_indirect_counters(&mut graphviz_data, &mut debug_used_expressions);
// Intermediate expressions will be injected as the final step, after generating
// debug output, if any.
////////////////////////////////////////////////////
(Ok(()), intermediate_expressions)
}
Err(e) => (Err(e), Vec::new()),
};
if graphviz_data.is_enabled() {
// Even if there was an error, a partial CoverageGraph can still generate a useful
// graphviz output.
debug::dump_coverage_graphviz(
tcx,
self.mir_body,
self.pass_name,
&self.basic_coverage_blocks,
&self.coverage_counters.debug_counters,
&graphviz_data,
&intermediate_expressions,
&debug_used_expressions,
);
}
if let Err(e) = result {
bug!("Error processing: {:?}: {:?}", self.mir_body.source.def_id(), e.message)
};
// Depending on current `debug_options()`, `alert_on_unused_expressions()` could panic, so
// this check is performed as late as possible, to allow other debug output (logs and dump
// files), which might be helpful in analyzing unused expressions, to still be generated.
debug_used_expressions.alert_on_unused_expressions(&self.coverage_counters.debug_counters);
////////////////////////////////////////////////////
// Finally, inject the intermediate expressions collected along the way.
for intermediate_expression in intermediate_expressions {
inject_intermediate_expression(self.mir_body, intermediate_expression);
}
}
/// Inject a counter for each `CoverageSpan`. There can be multiple `CoverageSpan`s for a given
/// BCB, but only one actual counter needs to be incremented per BCB. `bb_counters` maps each
/// `bcb` to its `Counter`, when injected. Subsequent `CoverageSpan`s for a BCB that already has
/// a `Counter` will inject an `Expression` instead, and compute its value by adding `ZERO` to
/// the BCB `Counter` value.
///
/// If debugging, add every BCB `Expression` associated with a `CoverageSpan`s to the
/// `used_expression_operands` map.
fn inject_coverage_span_counters(
&mut self,
coverage_spans: Vec<CoverageSpan>,
graphviz_data: &mut debug::GraphvizData,
debug_used_expressions: &mut debug::UsedExpressions,
) {
let tcx = self.tcx;
let source_map = tcx.sess.source_map();
let body_span = self.body_span;
let file_name = Symbol::intern(&self.source_file.name.prefer_remapped().to_string_lossy());
let mut bcb_counters = IndexVec::from_elem_n(None, self.basic_coverage_blocks.num_nodes());
for covspan in coverage_spans {
let bcb = covspan.bcb;
let span = covspan.span;
let counter_kind = if let Some(&counter_operand) = bcb_counters[bcb].as_ref() {
self.coverage_counters.make_identity_counter(counter_operand)
} else if let Some(counter_kind) = self.bcb_data_mut(bcb).take_counter() {
bcb_counters[bcb] = Some(counter_kind.as_operand_id());
debug_used_expressions.add_expression_operands(&counter_kind);
counter_kind
} else {
bug!("Every BasicCoverageBlock should have a Counter or Expression");
};
graphviz_data.add_bcb_coverage_span_with_counter(bcb, &covspan, &counter_kind);
debug!(
"Calling make_code_region(file_name={}, source_file={:?}, span={}, body_span={})",
file_name,
self.source_file,
source_map.span_to_diagnostic_string(span),
source_map.span_to_diagnostic_string(body_span)
);
inject_statement(
self.mir_body,
counter_kind,
self.bcb_leader_bb(bcb),
Some(make_code_region(source_map, file_name, &self.source_file, span, body_span)),
);
}
}
/// `inject_coverage_span_counters()` looped through the `CoverageSpan`s and injected the
/// counter from the `CoverageSpan`s `BasicCoverageBlock`, removing it from the BCB in the
/// process (via `take_counter()`).
///
/// Any other counter associated with a `BasicCoverageBlock`, or its incoming edge, but not
/// associated with a `CoverageSpan`, should only exist if the counter is an `Expression`
/// dependency (one of the expression operands). Collect them, and inject the additional
/// counters into the MIR, without a reportable coverage span.
fn inject_indirect_counters(
&mut self,
graphviz_data: &mut debug::GraphvizData,
debug_used_expressions: &mut debug::UsedExpressions,
) {
let mut bcb_counters_without_direct_coverage_spans = Vec::new();
for (target_bcb, target_bcb_data) in self.basic_coverage_blocks.iter_enumerated_mut() {
if let Some(counter_kind) = target_bcb_data.take_counter() {
bcb_counters_without_direct_coverage_spans.push((None, target_bcb, counter_kind));
}
if let Some(edge_counters) = target_bcb_data.take_edge_counters() {
for (from_bcb, counter_kind) in edge_counters {
bcb_counters_without_direct_coverage_spans.push((
Some(from_bcb),
target_bcb,
counter_kind,
));
}
}
}
// If debug is enabled, validate that every BCB or edge counter not directly associated
// with a coverage span is at least indirectly associated (it is a dependency of a BCB
// counter that _is_ associated with a coverage span).
debug_used_expressions.validate(&bcb_counters_without_direct_coverage_spans);
for (edge_from_bcb, target_bcb, counter_kind) in bcb_counters_without_direct_coverage_spans
{
debug_used_expressions.add_unused_expression_if_not_found(
&counter_kind,
edge_from_bcb,
target_bcb,
);
match counter_kind {
CoverageKind::Counter {.. } => {
let inject_to_bb = if let Some(from_bcb) = edge_from_bcb {
// The MIR edge starts `from_bb` (the outgoing / last BasicBlock in
// `from_bcb`) and ends at `to_bb` (the incoming / first BasicBlock in the
// `target_bcb`; also called the `leader_bb`).
let from_bb = self.bcb_last_bb(from_bcb);
let to_bb = self.bcb_leader_bb(target_bcb);
let new_bb = inject_edge_counter_basic_block(self.mir_body, from_bb, to_bb);
graphviz_data.set_edge_counter(from_bcb, new_bb, &counter_kind);
debug!(
"Edge {:?} (last {:?}) -> {:?} (leader {:?}) requires a new MIR \
BasicBlock {:?}, for unclaimed edge counter {}",
edge_from_bcb,
from_bb,
target_bcb,
to_bb,
new_bb,
self.format_counter(&counter_kind),
);
new_bb
} else {
let target_bb = self.bcb_last_bb(target_bcb);
graphviz_data.add_bcb_dependency_counter(target_bcb, &counter_kind);
debug!(
"{:?} ({:?}) gets a new Coverage statement for unclaimed counter {}",
target_bcb,
target_bb,
self.format_counter(&counter_kind),
);
target_bb
};
inject_statement(self.mir_body, counter_kind, inject_to_bb, None);
}
CoverageKind::Expression {.. } => {
inject_intermediate_expression(self.mir_body, counter_kind)
}
_ => bug!("CoverageKind should be a counter"),
}
}
}
#[inline]
fn bcb_leader_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock {
self.bcb_data(bcb).leader_bb()
}
#[inline]
fn bcb_last_bb(&self, bcb: BasicCoverageBlock) -> BasicBlock {
self.bcb_data(bcb).last_bb()
}
#[inline]
fn bcb_data(&self, bcb: BasicCoverageBlock) -> &BasicCoverageBlockData {
&self.basic_coverage_blocks[bcb]
}
#[inline]
fn bcb_data_mut(&mut self, bcb: BasicCoverageBlock) -> &mut BasicCoverageBlockData {
&mut self.basic_coverage_blocks[bcb]
}
#[inline]
fn format_counter(&self, counter_kind: &CoverageKind) -> String {
self.coverage_counters.debug_counters.format_counter(counter_kind)
}
}
fn inject_edge_counter_basic_block(
mir_body: &mut mir::Body<'tcx>,
from_bb: BasicBlock,
to_bb: BasicBlock,
) -> BasicBlock {
let span = mir_body[from_bb].terminator().source_info.span.shrink_to_hi();
let new_bb = mir_body.basic_blocks_mut().push(BasicBlockData {
statements: vec![], // counter will be injected here
terminator: Some(Terminator {
source_info: SourceInfo::outermost(span),
kind: TerminatorKind::Goto { target: to_bb },
}),
is_cleanup: false,
});
let edge_ref = mir_body[from_bb]
.terminator_mut()
.successors_mut()
.find(|successor| **successor == to_bb)
.expect("from_bb should have a successor for to_bb");
*edge_ref = new_bb;
new_bb
}
fn inject_statement(
mir_body: &mut mir::Body<'tcx>,
counter_kind: CoverageKind,
bb: BasicBlock,
some_code_region: Option<CodeRegion>,
) {
debug!(
" injecting statement {:?} for {:?} at code region: {:?}",
counter_kind, bb, some_code_region
);
let data = &mut mir_body[bb];
let source_info = data.terminator().source_info;
let statement = Statement {
source_info,
kind: StatementKind::Coverage(Box::new(Coverage {
kind: counter_kind,
code_region: some_code_region,
})),
};
data.statements.insert(0, statement);
}
// Non-code expressions are injected into the coverage map, without generating executable code.
fn inject_intermediate_expression(mir_body: &mut mir::Body<'tcx>, expression: CoverageKind) {
debug_assert!(matches!(expression, CoverageKind::Expression {.. }));
debug!(" injecting non-code expression {:?}", expression);
let inject_in_bb = mir::START_BLOCK;
let data = &mut mir_body[inject_in_bb];
let source_info = data.terminator().source_info;
let statement = Statement {
source_info,
kind: StatementKind::Coverage(Box::new(Coverage { kind: expression, code_region: None })),
};
data.statements.push(statement);
}
/// Convert the Span into its file name, start line and column, and end line and column
fn make_code_region(
source_map: &SourceMap,
file_name: Symbol,
source_file: &Lrc<SourceFile>,
span: Span,
body_span: Span,
) -> CodeRegion {
let (start_line, mut start_col) = source_file.lookup_file_pos(span.lo());
let (end_line, end_col) = if span.hi() == span.lo() {
let (end_line, mut end_col) = (start_line, start_col);
// Extend an empty span by one character so the region will be counted.
let CharPos(char_pos) = start_col;
if span.hi() == body_span.hi() {
start_col = CharPos(char_pos - 1);
} else {
end_col = CharPos(char_pos + 1);
}
(end_line, end_col)
} else {
source_file.lookup_file_pos(span.hi())
};
let start_line = source_map.doctest_offset_line(&source_file.name, start_line);
let end_line = source_map.doctest_offset_line(&source_file.name, end_line);
CodeRegion {
file_name,
start_line: start_line as u32,
start_col: start_col.to_u32() + 1,
end_line: end_line as u32,
end_col: end_col.to_u32() + 1,
}
}
fn fn_sig_and_body<'tcx>(
tcx: TyCtxt<'tcx>,
def_id: DefId,
) -> (Option<&'tcx rustc_hir::FnSig<'tcx>>, &'tcx rustc_hir::Body<'tcx>) {
// FIXME(#79625): Consider improving MIR to provide the information needed, to avoid going back
// to HIR for it.
let hir_node = tcx.hir().get_if_local(def_id).expect("expected DefId is local");
let fn_body_id = hir::map::associated_body(hir_node).expect("HIR node is a function with body");
(hir::map::fn_sig(hir_node), tcx.hir().body(fn_body_id))
}
fn get_body_span<'tcx>(
tcx: TyCtxt<'tcx>,
hir_body: &rustc_hir::Body<'tcx>,
mir_body: &mut mir::Body<'tcx>,
) -> Span {
let mut body_span = hir_body.value.span;
let def_id = mir_body.source.def_id();
if tcx.is_closure(def_id) {
// If the MIR function is a closure, and if the closure body span
// starts from a macro, but it's content is not in that macro, try
// to find a non-macro callsite, and instrument the spans there
// instead.
loop {
let expn_data = body_span.ctxt().outer_expn_data();
if expn_data.is_root() {
break;
}
if let ExpnKind::Macro {.. } = expn_data.kind
|
{
body_span = expn_data.call_site;
}
|
conditional_block
|
|
copy-a-resource.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.
#[deriving(Show)]
struct foo {
i: int,
}
impl Drop for foo {
fn drop(&mut self) {}
}
fn foo(i:int) -> foo
|
fn main() {
let x = foo(10);
let _y = x.clone();
//~^ ERROR does not implement any method in scope
println!("{}", x);
}
|
{
foo {
i: i
}
}
|
identifier_body
|
copy-a-resource.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.
#[deriving(Show)]
struct foo {
i: int,
}
impl Drop for foo {
fn drop(&mut self) {}
}
fn foo(i:int) -> foo {
foo {
i: i
}
}
|
//~^ ERROR does not implement any method in scope
println!("{}", x);
}
|
fn main() {
let x = foo(10);
let _y = x.clone();
|
random_line_split
|
copy-a-resource.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.
#[deriving(Show)]
struct
|
{
i: int,
}
impl Drop for foo {
fn drop(&mut self) {}
}
fn foo(i:int) -> foo {
foo {
i: i
}
}
fn main() {
let x = foo(10);
let _y = x.clone();
//~^ ERROR does not implement any method in scope
println!("{}", x);
}
|
foo
|
identifier_name
|
sequential.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/. */
//! Implements sequential traversal over the DOM tree.
use dom::{TElement, TNode};
use traversal::{DomTraversalContext, PerLevelTraversalData, PreTraverseToken};
pub fn traverse_dom<N, C>(root: N::ConcreteElement,
shared: &C::SharedContext,
token: PreTraverseToken)
where N: TNode,
C: DomTraversalContext<N>
{
|
fn doit<'a, N, C>(context: &'a C, node: N, data: &mut PerLevelTraversalData)
where N: TNode,
C: DomTraversalContext<N>
{
context.process_preorder(node, data);
if let Some(el) = node.as_element() {
if let Some(ref mut depth) = data.current_dom_depth {
*depth += 1;
}
C::traverse_children(el, |kid| doit::<N, C>(context, kid, data));
if let Some(ref mut depth) = data.current_dom_depth {
*depth -= 1;
}
}
if C::needs_postorder_traversal() {
context.process_postorder(node);
}
}
let mut data = PerLevelTraversalData {
current_dom_depth: None,
};
let context = C::new(shared, root.as_node().opaque());
if token.traverse_unstyled_children_only() {
for kid in root.as_node().children() {
if kid.as_element().map_or(false, |el| el.get_data().is_none()) {
doit::<N, C>(&context, kid, &mut data);
}
}
} else {
doit::<N, C>(&context, root.as_node(), &mut data);
}
// Clear the local LRU cache since we store stateful elements inside.
context.local_context().style_sharing_candidate_cache.borrow_mut().clear();
}
|
debug_assert!(token.should_traverse());
|
random_line_split
|
sequential.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/. */
//! Implements sequential traversal over the DOM tree.
use dom::{TElement, TNode};
use traversal::{DomTraversalContext, PerLevelTraversalData, PreTraverseToken};
pub fn traverse_dom<N, C>(root: N::ConcreteElement,
shared: &C::SharedContext,
token: PreTraverseToken)
where N: TNode,
C: DomTraversalContext<N>
{
debug_assert!(token.should_traverse());
fn doit<'a, N, C>(context: &'a C, node: N, data: &mut PerLevelTraversalData)
where N: TNode,
C: DomTraversalContext<N>
{
context.process_preorder(node, data);
if let Some(el) = node.as_element() {
if let Some(ref mut depth) = data.current_dom_depth {
*depth += 1;
}
C::traverse_children(el, |kid| doit::<N, C>(context, kid, data));
if let Some(ref mut depth) = data.current_dom_depth
|
}
if C::needs_postorder_traversal() {
context.process_postorder(node);
}
}
let mut data = PerLevelTraversalData {
current_dom_depth: None,
};
let context = C::new(shared, root.as_node().opaque());
if token.traverse_unstyled_children_only() {
for kid in root.as_node().children() {
if kid.as_element().map_or(false, |el| el.get_data().is_none()) {
doit::<N, C>(&context, kid, &mut data);
}
}
} else {
doit::<N, C>(&context, root.as_node(), &mut data);
}
// Clear the local LRU cache since we store stateful elements inside.
context.local_context().style_sharing_candidate_cache.borrow_mut().clear();
}
|
{
*depth -= 1;
}
|
conditional_block
|
sequential.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/. */
//! Implements sequential traversal over the DOM tree.
use dom::{TElement, TNode};
use traversal::{DomTraversalContext, PerLevelTraversalData, PreTraverseToken};
pub fn traverse_dom<N, C>(root: N::ConcreteElement,
shared: &C::SharedContext,
token: PreTraverseToken)
where N: TNode,
C: DomTraversalContext<N>
|
if C::needs_postorder_traversal() {
context.process_postorder(node);
}
}
let mut data = PerLevelTraversalData {
current_dom_depth: None,
};
let context = C::new(shared, root.as_node().opaque());
if token.traverse_unstyled_children_only() {
for kid in root.as_node().children() {
if kid.as_element().map_or(false, |el| el.get_data().is_none()) {
doit::<N, C>(&context, kid, &mut data);
}
}
} else {
doit::<N, C>(&context, root.as_node(), &mut data);
}
// Clear the local LRU cache since we store stateful elements inside.
context.local_context().style_sharing_candidate_cache.borrow_mut().clear();
}
|
{
debug_assert!(token.should_traverse());
fn doit<'a, N, C>(context: &'a C, node: N, data: &mut PerLevelTraversalData)
where N: TNode,
C: DomTraversalContext<N>
{
context.process_preorder(node, data);
if let Some(el) = node.as_element() {
if let Some(ref mut depth) = data.current_dom_depth {
*depth += 1;
}
C::traverse_children(el, |kid| doit::<N, C>(context, kid, data));
if let Some(ref mut depth) = data.current_dom_depth {
*depth -= 1;
}
}
|
identifier_body
|
sequential.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/. */
//! Implements sequential traversal over the DOM tree.
use dom::{TElement, TNode};
use traversal::{DomTraversalContext, PerLevelTraversalData, PreTraverseToken};
pub fn traverse_dom<N, C>(root: N::ConcreteElement,
shared: &C::SharedContext,
token: PreTraverseToken)
where N: TNode,
C: DomTraversalContext<N>
{
debug_assert!(token.should_traverse());
fn
|
<'a, N, C>(context: &'a C, node: N, data: &mut PerLevelTraversalData)
where N: TNode,
C: DomTraversalContext<N>
{
context.process_preorder(node, data);
if let Some(el) = node.as_element() {
if let Some(ref mut depth) = data.current_dom_depth {
*depth += 1;
}
C::traverse_children(el, |kid| doit::<N, C>(context, kid, data));
if let Some(ref mut depth) = data.current_dom_depth {
*depth -= 1;
}
}
if C::needs_postorder_traversal() {
context.process_postorder(node);
}
}
let mut data = PerLevelTraversalData {
current_dom_depth: None,
};
let context = C::new(shared, root.as_node().opaque());
if token.traverse_unstyled_children_only() {
for kid in root.as_node().children() {
if kid.as_element().map_or(false, |el| el.get_data().is_none()) {
doit::<N, C>(&context, kid, &mut data);
}
}
} else {
doit::<N, C>(&context, root.as_node(), &mut data);
}
// Clear the local LRU cache since we store stateful elements inside.
context.local_context().style_sharing_candidate_cache.borrow_mut().clear();
}
|
doit
|
identifier_name
|
multicol.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/. */
//! CSS Multi-column layout http://dev.w3.org/csswg/css-multicol/
#![deny(unsafe_code)]
use block::BlockFlow;
use context::LayoutContext;
use floats::FloatKind;
use flow::{FlowClass, Flow, OpaqueFlow};
use fragment::{Fragment, FragmentBorderBoxIterator};
use euclid::{Point2D, Rect};
use std::fmt;
use std::sync::Arc;
use style::properties::ComputedValues;
use util::geometry::Au;
use util::logical_geometry::LogicalSize;
pub struct MulticolFlow {
pub block_flow: BlockFlow,
}
impl MulticolFlow {
pub fn
|
(fragment: Fragment, float_kind: Option<FloatKind>) -> MulticolFlow {
MulticolFlow {
block_flow: BlockFlow::from_fragment(fragment, float_kind)
}
}
}
impl Flow for MulticolFlow {
fn class(&self) -> FlowClass {
FlowClass::Multicol
}
fn as_mut_multicol(&mut self) -> &mut MulticolFlow {
self
}
fn as_mut_block(&mut self) -> &mut BlockFlow {
&mut self.block_flow
}
fn as_block(&self) -> &BlockFlow {
&self.block_flow
}
fn bubble_inline_sizes(&mut self) {
// FIXME(SimonSapin) http://dev.w3.org/csswg/css-sizing/#multicol-intrinsic
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, ctx: &LayoutContext) {
debug!("assign_inline_sizes({}): assigning inline_size for flow", "multicol");
self.block_flow.assign_inline_sizes(ctx);
}
fn assign_block_size<'a>(&mut self, ctx: &'a LayoutContext<'a>) {
debug!("assign_block_size: assigning block_size for multicol");
self.block_flow.assign_block_size(ctx);
}
fn compute_absolute_position(&mut self, layout_context: &LayoutContext) {
self.block_flow.compute_absolute_position(layout_context)
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
debug!("build_display_list_multicol: same process as block flow");
self.block_flow.build_display_list(layout_context)
}
fn repair_style(&mut self, new_style: &Arc<ComputedValues>) {
self.block_flow.repair_style(new_style)
}
fn compute_overflow(&self) -> Rect<Au> {
self.block_flow.compute_overflow()
}
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn iterate_through_fragment_border_boxes(&self,
iterator: &mut FragmentBorderBoxIterator,
level: i32,
stacking_context_position: &Point2D<Au>) {
self.block_flow.iterate_through_fragment_border_boxes(iterator, level, stacking_context_position)
}
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) {
self.block_flow.mutate_fragments(mutator)
}
}
impl fmt::Debug for MulticolFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "MulticolFlow: {:?}", self.block_flow)
}
}
|
from_fragment
|
identifier_name
|
multicol.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/. */
//! CSS Multi-column layout http://dev.w3.org/csswg/css-multicol/
#![deny(unsafe_code)]
use block::BlockFlow;
use context::LayoutContext;
use floats::FloatKind;
use flow::{FlowClass, Flow, OpaqueFlow};
use fragment::{Fragment, FragmentBorderBoxIterator};
use euclid::{Point2D, Rect};
use std::fmt;
use std::sync::Arc;
use style::properties::ComputedValues;
use util::geometry::Au;
use util::logical_geometry::LogicalSize;
pub struct MulticolFlow {
pub block_flow: BlockFlow,
}
impl MulticolFlow {
pub fn from_fragment(fragment: Fragment, float_kind: Option<FloatKind>) -> MulticolFlow {
MulticolFlow {
block_flow: BlockFlow::from_fragment(fragment, float_kind)
}
}
}
impl Flow for MulticolFlow {
fn class(&self) -> FlowClass {
FlowClass::Multicol
}
fn as_mut_multicol(&mut self) -> &mut MulticolFlow {
self
}
fn as_mut_block(&mut self) -> &mut BlockFlow {
&mut self.block_flow
}
fn as_block(&self) -> &BlockFlow {
&self.block_flow
}
fn bubble_inline_sizes(&mut self) {
// FIXME(SimonSapin) http://dev.w3.org/csswg/css-sizing/#multicol-intrinsic
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, ctx: &LayoutContext) {
debug!("assign_inline_sizes({}): assigning inline_size for flow", "multicol");
self.block_flow.assign_inline_sizes(ctx);
}
fn assign_block_size<'a>(&mut self, ctx: &'a LayoutContext<'a>) {
debug!("assign_block_size: assigning block_size for multicol");
self.block_flow.assign_block_size(ctx);
}
fn compute_absolute_position(&mut self, layout_context: &LayoutContext) {
self.block_flow.compute_absolute_position(layout_context)
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
debug!("build_display_list_multicol: same process as block flow");
self.block_flow.build_display_list(layout_context)
}
fn repair_style(&mut self, new_style: &Arc<ComputedValues>) {
self.block_flow.repair_style(new_style)
}
fn compute_overflow(&self) -> Rect<Au> {
self.block_flow.compute_overflow()
}
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn iterate_through_fragment_border_boxes(&self,
iterator: &mut FragmentBorderBoxIterator,
level: i32,
stacking_context_position: &Point2D<Au>) {
self.block_flow.iterate_through_fragment_border_boxes(iterator, level, stacking_context_position)
}
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) {
self.block_flow.mutate_fragments(mutator)
}
}
impl fmt::Debug for MulticolFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "MulticolFlow: {:?}", self.block_flow)
}
|
}
|
random_line_split
|
|
multicol.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/. */
//! CSS Multi-column layout http://dev.w3.org/csswg/css-multicol/
#![deny(unsafe_code)]
use block::BlockFlow;
use context::LayoutContext;
use floats::FloatKind;
use flow::{FlowClass, Flow, OpaqueFlow};
use fragment::{Fragment, FragmentBorderBoxIterator};
use euclid::{Point2D, Rect};
use std::fmt;
use std::sync::Arc;
use style::properties::ComputedValues;
use util::geometry::Au;
use util::logical_geometry::LogicalSize;
pub struct MulticolFlow {
pub block_flow: BlockFlow,
}
impl MulticolFlow {
pub fn from_fragment(fragment: Fragment, float_kind: Option<FloatKind>) -> MulticolFlow {
MulticolFlow {
block_flow: BlockFlow::from_fragment(fragment, float_kind)
}
}
}
impl Flow for MulticolFlow {
fn class(&self) -> FlowClass {
FlowClass::Multicol
}
fn as_mut_multicol(&mut self) -> &mut MulticolFlow {
self
}
fn as_mut_block(&mut self) -> &mut BlockFlow {
&mut self.block_flow
}
fn as_block(&self) -> &BlockFlow {
&self.block_flow
}
fn bubble_inline_sizes(&mut self) {
// FIXME(SimonSapin) http://dev.w3.org/csswg/css-sizing/#multicol-intrinsic
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, ctx: &LayoutContext) {
debug!("assign_inline_sizes({}): assigning inline_size for flow", "multicol");
self.block_flow.assign_inline_sizes(ctx);
}
fn assign_block_size<'a>(&mut self, ctx: &'a LayoutContext<'a>) {
debug!("assign_block_size: assigning block_size for multicol");
self.block_flow.assign_block_size(ctx);
}
fn compute_absolute_position(&mut self, layout_context: &LayoutContext) {
self.block_flow.compute_absolute_position(layout_context)
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
debug!("build_display_list_multicol: same process as block flow");
self.block_flow.build_display_list(layout_context)
}
fn repair_style(&mut self, new_style: &Arc<ComputedValues>) {
self.block_flow.repair_style(new_style)
}
fn compute_overflow(&self) -> Rect<Au>
|
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn iterate_through_fragment_border_boxes(&self,
iterator: &mut FragmentBorderBoxIterator,
level: i32,
stacking_context_position: &Point2D<Au>) {
self.block_flow.iterate_through_fragment_border_boxes(iterator, level, stacking_context_position)
}
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) {
self.block_flow.mutate_fragments(mutator)
}
}
impl fmt::Debug for MulticolFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "MulticolFlow: {:?}", self.block_flow)
}
}
|
{
self.block_flow.compute_overflow()
}
|
identifier_body
|
rational_impl.rs
|
//! # Licensing
//! This Source Code is subject to the terms of the Mozilla Public License
//! version 2.0 (the "License"). You can obtain a copy of the License at
//! [http://mozilla.org/MPL/2.0/](http://mozilla.org/MPL/2.0/).
use num_rational::Ratio;
use num_integer::Integer;
use num_traits::identities::Zero;
use NearlyEq;
#[cfg_attr(feature = "docs", stable(feature = "rational", since = "0.2.1"))]
impl<A: Integer + Clone> NearlyEq<Ratio<A>, Ratio<A>> for Ratio<A> {
fn eps() -> Ratio<A>
|
fn eq(&self, other: &Ratio<A>, eps: &Ratio<A>) -> bool {
let diff = if *self > *other {
self.clone() - other.clone()
} else {
other.clone() - self.clone()
};
if *self == *other {
true
} else {
diff < *eps
}
}
}
|
{
Ratio::zero()
}
|
identifier_body
|
rational_impl.rs
|
//! # Licensing
//! This Source Code is subject to the terms of the Mozilla Public License
//! version 2.0 (the "License"). You can obtain a copy of the License at
//! [http://mozilla.org/MPL/2.0/](http://mozilla.org/MPL/2.0/).
use num_rational::Ratio;
use num_integer::Integer;
use num_traits::identities::Zero;
use NearlyEq;
#[cfg_attr(feature = "docs", stable(feature = "rational", since = "0.2.1"))]
impl<A: Integer + Clone> NearlyEq<Ratio<A>, Ratio<A>> for Ratio<A> {
fn
|
() -> Ratio<A> {
Ratio::zero()
}
fn eq(&self, other: &Ratio<A>, eps: &Ratio<A>) -> bool {
let diff = if *self > *other {
self.clone() - other.clone()
} else {
other.clone() - self.clone()
};
if *self == *other {
true
} else {
diff < *eps
}
}
}
|
eps
|
identifier_name
|
rational_impl.rs
|
//! # Licensing
//! This Source Code is subject to the terms of the Mozilla Public License
//! version 2.0 (the "License"). You can obtain a copy of the License at
//! [http://mozilla.org/MPL/2.0/](http://mozilla.org/MPL/2.0/).
use num_rational::Ratio;
use num_integer::Integer;
use num_traits::identities::Zero;
use NearlyEq;
#[cfg_attr(feature = "docs", stable(feature = "rational", since = "0.2.1"))]
impl<A: Integer + Clone> NearlyEq<Ratio<A>, Ratio<A>> for Ratio<A> {
fn eps() -> Ratio<A> {
Ratio::zero()
}
fn eq(&self, other: &Ratio<A>, eps: &Ratio<A>) -> bool {
let diff = if *self > *other {
self.clone() - other.clone()
} else {
other.clone() - self.clone()
};
if *self == *other
|
else {
diff < *eps
}
}
}
|
{
true
}
|
conditional_block
|
rational_impl.rs
|
//! # Licensing
//! This Source Code is subject to the terms of the Mozilla Public License
//! version 2.0 (the "License"). You can obtain a copy of the License at
//! [http://mozilla.org/MPL/2.0/](http://mozilla.org/MPL/2.0/).
use num_rational::Ratio;
use num_integer::Integer;
use num_traits::identities::Zero;
use NearlyEq;
#[cfg_attr(feature = "docs", stable(feature = "rational", since = "0.2.1"))]
|
fn eq(&self, other: &Ratio<A>, eps: &Ratio<A>) -> bool {
let diff = if *self > *other {
self.clone() - other.clone()
} else {
other.clone() - self.clone()
};
if *self == *other {
true
} else {
diff < *eps
}
}
}
|
impl<A: Integer + Clone> NearlyEq<Ratio<A>, Ratio<A>> for Ratio<A> {
fn eps() -> Ratio<A> {
Ratio::zero()
}
|
random_line_split
|
mu_lambda.rs
|
use std::sync::mpsc::{Sender, Receiver};
use std::sync::{mpsc, Arc};
use rand::{Rng, thread_rng};
use threadpool::{ThreadPool};
use chapter2::evaluation::{EvaluationFn};
use chapter2::genotype::{Genotype};
use chapter2::statistics::{Statistic};
use util::util::{shuffle};
pub struct MuLambda<G: Genotype> {
threads: usize,
iterations: u32,
current_iteration: u32,
mu: usize, // number to keep
lambda: usize, // number to generate
mutation: f64, // mutation of genotype to mutate (between 0.0 and 1.0)
genotype: G,
evaluations: Arc<Vec<(EvaluationFn, f64)>>,
}
impl<G: Genotype + Clone + Send +'static> MuLambda<G> {
pub fn new(threads: usize,
iterations: u32,
mu: usize,
lambda: usize,
mutation: f64,
genotype: G,
funcs: Vec<EvaluationFn>,
weights: Vec<f64>) -> MuLambda<G> {
MuLambda {
threads: threads,
iterations: iterations,
current_iteration: 0,
mu: mu,
lambda: lambda,
mutation: mutation,
genotype: genotype,
evaluations: Arc::new(funcs.into_iter().zip(weights.iter().cloned()).collect()),
}
}
pub fn run(&mut self) -> Vec<(G, Statistic)> {
let total = self.mu + self.lambda;
let mut rng = thread_rng();
let mut primer: Vec<(G, Statistic)> = (0..total).map(|_| {
(self.genotype.initialize(&mut rng), Statistic::empty())
}).collect();
// for each iteration except the last, do a full generation life-cycle.
while self.current_iteration < self.iterations - 1 {
primer = self.iterate(&mut rng, primer.as_mut_slice(), self.current_iteration);
primer = self.prune(primer);
self.current_iteration += 1;
}
// one last iteration without the pruning.
primer = self.iterate(&mut rng, primer.as_mut_slice(), self.current_iteration);
primer.clone()
}
fn iterate<R: Rng>(&self, rng: &mut R, primer: &mut [(G, Statistic)], iteration: u32) -> Vec<(G, Statistic)> {
// shuffle the population
shuffle(rng, primer);
|
let (tx, rx): (Sender<(G, Statistic)>, Receiver<(G, Statistic)>) = mpsc::channel();
for &(ref adult, _) in primer.iter() {
let individual = adult.clone();
let sender = tx.clone();
let fns = self.evaluations.clone();
pool.execute(move || {
let dungeon = individual.generate();
let fitness = individual.evaluate(&dungeon, &fns[..]);
let statistic = Statistic::new(iteration, fitness);
sender.send((individual, statistic)).unwrap();
});
}
let mut colony: Vec<(G, Statistic)> = (0..n).map(|_| rx.recv().unwrap()).collect();
// sort by fitness
colony.sort_by(|&(_, ref i1), &(_, ref i2)| {
match i1.fitness.partial_cmp(&i2.fitness) {
Some(ordering) => ordering,
None => panic!("{:?} and {:?} could not be ordered.", i1.fitness, i2.fitness)
}
});
colony
}
fn prune(&self, generation: Vec<(G, Statistic)>) -> Vec<(G, Statistic)> {
// keep mu
let mut survivors: Vec<(G, Statistic)> = generation.iter().map(|v| v.clone()).take(self.mu).collect();
// add the next generation
let next_generation: Vec<(G, Statistic)> = generation.into_iter().map(|(ref mut individual, _)| {
let mut new_rng = thread_rng();
let mut baby = individual.clone();
baby.mutate(&mut new_rng, self.mutation);
(baby, Statistic::empty())
}).skip(self.mu).collect();
survivors.push_all(&next_generation[..]);
survivors
}
}
|
// calculate the fitness for each individual (in a separate thread)
let n = primer.len();
let pool = ThreadPool::new(self.threads);
|
random_line_split
|
mu_lambda.rs
|
use std::sync::mpsc::{Sender, Receiver};
use std::sync::{mpsc, Arc};
use rand::{Rng, thread_rng};
use threadpool::{ThreadPool};
use chapter2::evaluation::{EvaluationFn};
use chapter2::genotype::{Genotype};
use chapter2::statistics::{Statistic};
use util::util::{shuffle};
pub struct MuLambda<G: Genotype> {
threads: usize,
iterations: u32,
current_iteration: u32,
mu: usize, // number to keep
lambda: usize, // number to generate
mutation: f64, // mutation of genotype to mutate (between 0.0 and 1.0)
genotype: G,
evaluations: Arc<Vec<(EvaluationFn, f64)>>,
}
impl<G: Genotype + Clone + Send +'static> MuLambda<G> {
pub fn new(threads: usize,
iterations: u32,
mu: usize,
lambda: usize,
mutation: f64,
genotype: G,
funcs: Vec<EvaluationFn>,
weights: Vec<f64>) -> MuLambda<G> {
MuLambda {
threads: threads,
iterations: iterations,
current_iteration: 0,
mu: mu,
lambda: lambda,
mutation: mutation,
genotype: genotype,
evaluations: Arc::new(funcs.into_iter().zip(weights.iter().cloned()).collect()),
}
}
pub fn run(&mut self) -> Vec<(G, Statistic)> {
let total = self.mu + self.lambda;
let mut rng = thread_rng();
let mut primer: Vec<(G, Statistic)> = (0..total).map(|_| {
(self.genotype.initialize(&mut rng), Statistic::empty())
}).collect();
// for each iteration except the last, do a full generation life-cycle.
while self.current_iteration < self.iterations - 1 {
primer = self.iterate(&mut rng, primer.as_mut_slice(), self.current_iteration);
primer = self.prune(primer);
self.current_iteration += 1;
}
// one last iteration without the pruning.
primer = self.iterate(&mut rng, primer.as_mut_slice(), self.current_iteration);
primer.clone()
}
fn
|
<R: Rng>(&self, rng: &mut R, primer: &mut [(G, Statistic)], iteration: u32) -> Vec<(G, Statistic)> {
// shuffle the population
shuffle(rng, primer);
// calculate the fitness for each individual (in a separate thread)
let n = primer.len();
let pool = ThreadPool::new(self.threads);
let (tx, rx): (Sender<(G, Statistic)>, Receiver<(G, Statistic)>) = mpsc::channel();
for &(ref adult, _) in primer.iter() {
let individual = adult.clone();
let sender = tx.clone();
let fns = self.evaluations.clone();
pool.execute(move || {
let dungeon = individual.generate();
let fitness = individual.evaluate(&dungeon, &fns[..]);
let statistic = Statistic::new(iteration, fitness);
sender.send((individual, statistic)).unwrap();
});
}
let mut colony: Vec<(G, Statistic)> = (0..n).map(|_| rx.recv().unwrap()).collect();
// sort by fitness
colony.sort_by(|&(_, ref i1), &(_, ref i2)| {
match i1.fitness.partial_cmp(&i2.fitness) {
Some(ordering) => ordering,
None => panic!("{:?} and {:?} could not be ordered.", i1.fitness, i2.fitness)
}
});
colony
}
fn prune(&self, generation: Vec<(G, Statistic)>) -> Vec<(G, Statistic)> {
// keep mu
let mut survivors: Vec<(G, Statistic)> = generation.iter().map(|v| v.clone()).take(self.mu).collect();
// add the next generation
let next_generation: Vec<(G, Statistic)> = generation.into_iter().map(|(ref mut individual, _)| {
let mut new_rng = thread_rng();
let mut baby = individual.clone();
baby.mutate(&mut new_rng, self.mutation);
(baby, Statistic::empty())
}).skip(self.mu).collect();
survivors.push_all(&next_generation[..]);
survivors
}
}
|
iterate
|
identifier_name
|
test_index.rs
|
// // #![feature(hashmap_hasher)]
//
// extern crate rand;
// extern crate time;
// extern crate getopts;
// extern crate timely;
// extern crate graph_map;
// extern crate differential_dataflow;
//
// // use std::collections::HashMap;
// // use std::collections::hash_state::DefaultState;
// use std::hash::{Hash, SipHasher, Hasher};
//
// fn hash_me<T: Hash>(x: &T) -> u64 {
// let mut h = SipHasher::new();
// x.hash(&mut h);
// h.finish()
// }
//
// use rand::{Rng, SeedableRng, StdRng};
//
// use differential_dataflow::collection_trace::hash_index::HashIndex;
//
// fn main() {
// for i in 25..26 {
// test_index(i);
// }
// }
//
// fn test_index(log_size: usize) {
//
// // let default_state: DefaultState<SipHasher> = Default::default();
// // let mut hash = HashMap::with_capacity_and_hash_state(1 << log_size, default_state);
// let mut hash_index = HashIndex::<(u64, (u64, u64)), (u64, u64), _>::new(|x| x.0);
// let mut hash_index2 = HashIndex::<(u64, u64), (u64, u64), _>::new(|x| x.0 ^ x.1);
//
// let seed: &[_] = &[1, 2, 3, 4];
// let mut rng: StdRng = SeedableRng::from_seed(seed);
//
// // let start = time::precise_time_ns();
// // for i in 0u64..(1 << log_size) {
// // hash.insert((i,i),(i,i));
// // }
// //
// // println!("loaded hash_map 2^{}:\t{:.2e} ns; capacity: {}", log_size, (time::precise_time_ns() - start) as f64, hash.capacity());
//
// let start = time::precise_time_ns();
// for _ in 0u64..(1 << log_size) {
// let key = (rng.next_u64(), rng.next_u64());
// hash_index.entry_or_insert((key.0 ^ key.1, key), || key);
// }
//
// println!("loaded hash_index 2^{}:\t{:.2e} ns; capacity: {}", log_size, (time::precise_time_ns() - start) as f64, hash_index.capacity());
//
// let start = time::precise_time_ns();
// for _ in 0u64..(1 << log_size) {
// let key = (rng.next_u64(), rng.next_u64());
// hash_index2.entry_or_insert(key, || key);
// }
//
// println!("loaded hash_index 3^{}:\t{:.2e} ns; capacity: {}", log_size, (time::precise_time_ns() - start) as f64, hash_index.capacity());
//
// for query in 0..log_size {
//
// // let mut hash1_tally = 0;
// let mut hash2_tally = 0;
// let mut hash3_tally = 0;
//
// for _ in 0..10 {
// let mut vec = vec![];
//
// for _ in 0..(1 << query) {
// let key = (rng.next_u64(), rng.next_u64());
|
// }
//
// // // vec.sort_by(|x,y| (x.0 & ((1 << (log_size + 1)) - 1)).cmp(&(y.0 & ((1 << (log_size + 1)) - 1))));
// // let start = time::precise_time_ns();
// // for i in vec.iter() {
// // assert!(hash.get(&i.1).is_none());
// // }
// // hash1_tally += time::precise_time_ns() - start;
//
//
// // vec.sort_by(|x,y| ((x.1).0 ^ (x.1).1).cmp(&((y.1).0 ^ (y.1).1)));
// let start = time::precise_time_ns();
// for i in vec.iter() {
// assert!(hash_index.get_ref(&((i.1).0 ^ (i.1).1, i.1)).is_none());
// }
// hash2_tally += time::precise_time_ns() - start;
//
// let start = time::precise_time_ns();
// for i in vec.iter() {
// assert!(hash_index2.get_ref(&i.1).is_none());
// }
// hash3_tally += time::precise_time_ns() - start;
// vec.clear();
// }
//
// println!("\t2^{}:\t{}\t{}\t{}", query, "STABILITY BOO", (hash2_tally / 10) >> query, (hash3_tally / 10) >> query);
//
// }
// }
|
// vec.push((hash_me(&key), key));
|
random_line_split
|
messages.rs
|
use byteorder::{WriteBytesExt, LittleEndian};
use frame::FrameOfData;
use model;
use sender::Sender;
use std::ffi::CString;
use super::NatNetMsgType;
/// Enumeration of possible responses from `NatNet`
#[derive(Clone, Debug, PartialEq)]
pub enum NatNetResponse {
/// Response to ping request
///
/// The ping response contains data about the sender application
Ping(Sender),
/// Response to command
Response(i32),
/// Response to command in String form
ResponseString(String),
/// Model definitions
///
/// This type contains a list of `DataSet`s that describe data in a
/// `FrameOfData`
ModelDef(Vec<model::DataSet>),
/// Data about tracked content
FrameOfData(FrameOfData),
/// Message from the sender application
MessageString(String),
/// The sender application did not understand the request
UnrecognizedRequest,
}
/// Enumeration of possible requests sent to `NatNet`
#[derive(Clone, Debug, PartialEq)]
pub enum NatNetRequest {
/// Send ping to other application
///
/// This should result in a `NatNetResponse::Ping`
Ping(CString),
/// Request model definitions
ModelDefinitions,
/// Request a frame of data
FrameOfData,
}
impl Into<Vec<u8>> for NatNetRequest {
fn into(self) -> Vec<u8> {
// Pre-allocate some bytes for the message
// most messages are smaller than this
let mut bytes = Vec::with_capacity(32);
match self {
NatNetRequest::ModelDefinitions => {
bytes.write_u16::<LittleEndian>(NatNetMsgType::RequestModelDef as u16).unwrap();
bytes.write_u16::<LittleEndian>(0).unwrap();
}
NatNetRequest::FrameOfData => {
bytes.write_u16::<LittleEndian>(NatNetMsgType::RequestFrameOfData as u16).unwrap();
bytes.write_u16::<LittleEndian>(0).unwrap();
}
NatNetRequest::Ping(data) => {
let str_data = data.to_bytes_with_nul();
bytes.write_u16::<LittleEndian>(NatNetMsgType::Ping as u16).unwrap();
// NatNet does not support more than 100_000 bytes in messages,
// to support this restriction in an Into we simply truncate
// FIXME: Use `TryInto` instead
if str_data.len() > u16::max_value() as usize {
bytes.write_u16::<LittleEndian>(u16::max_value()).unwrap();
// The message might still be valid so we append as much as
// possible, NOTE: We need to append C-String null to the
// end and so we must take `max_value() - 1`
bytes.extend_from_slice(&str_data[..u16::max_value() as usize - 1]);
bytes.push(b'\0');
} else {
bytes.write_u16::<LittleEndian>(str_data.len() as u16).unwrap();
|
}
}
}
bytes
}
}
|
bytes.extend_from_slice(str_data);
|
random_line_split
|
messages.rs
|
use byteorder::{WriteBytesExt, LittleEndian};
use frame::FrameOfData;
use model;
use sender::Sender;
use std::ffi::CString;
use super::NatNetMsgType;
/// Enumeration of possible responses from `NatNet`
#[derive(Clone, Debug, PartialEq)]
pub enum NatNetResponse {
/// Response to ping request
///
/// The ping response contains data about the sender application
Ping(Sender),
/// Response to command
Response(i32),
/// Response to command in String form
ResponseString(String),
/// Model definitions
///
/// This type contains a list of `DataSet`s that describe data in a
/// `FrameOfData`
ModelDef(Vec<model::DataSet>),
/// Data about tracked content
FrameOfData(FrameOfData),
/// Message from the sender application
MessageString(String),
/// The sender application did not understand the request
UnrecognizedRequest,
}
/// Enumeration of possible requests sent to `NatNet`
#[derive(Clone, Debug, PartialEq)]
pub enum NatNetRequest {
/// Send ping to other application
///
/// This should result in a `NatNetResponse::Ping`
Ping(CString),
/// Request model definitions
ModelDefinitions,
/// Request a frame of data
FrameOfData,
}
impl Into<Vec<u8>> for NatNetRequest {
fn into(self) -> Vec<u8> {
// Pre-allocate some bytes for the message
// most messages are smaller than this
let mut bytes = Vec::with_capacity(32);
match self {
NatNetRequest::ModelDefinitions => {
bytes.write_u16::<LittleEndian>(NatNetMsgType::RequestModelDef as u16).unwrap();
bytes.write_u16::<LittleEndian>(0).unwrap();
}
NatNetRequest::FrameOfData => {
bytes.write_u16::<LittleEndian>(NatNetMsgType::RequestFrameOfData as u16).unwrap();
bytes.write_u16::<LittleEndian>(0).unwrap();
}
NatNetRequest::Ping(data) => {
let str_data = data.to_bytes_with_nul();
bytes.write_u16::<LittleEndian>(NatNetMsgType::Ping as u16).unwrap();
// NatNet does not support more than 100_000 bytes in messages,
// to support this restriction in an Into we simply truncate
// FIXME: Use `TryInto` instead
if str_data.len() > u16::max_value() as usize {
bytes.write_u16::<LittleEndian>(u16::max_value()).unwrap();
// The message might still be valid so we append as much as
// possible, NOTE: We need to append C-String null to the
// end and so we must take `max_value() - 1`
bytes.extend_from_slice(&str_data[..u16::max_value() as usize - 1]);
bytes.push(b'\0');
} else
|
}
}
bytes
}
}
|
{
bytes.write_u16::<LittleEndian>(str_data.len() as u16).unwrap();
bytes.extend_from_slice(str_data);
}
|
conditional_block
|
messages.rs
|
use byteorder::{WriteBytesExt, LittleEndian};
use frame::FrameOfData;
use model;
use sender::Sender;
use std::ffi::CString;
use super::NatNetMsgType;
/// Enumeration of possible responses from `NatNet`
#[derive(Clone, Debug, PartialEq)]
pub enum NatNetResponse {
/// Response to ping request
///
/// The ping response contains data about the sender application
Ping(Sender),
/// Response to command
Response(i32),
/// Response to command in String form
ResponseString(String),
/// Model definitions
///
/// This type contains a list of `DataSet`s that describe data in a
/// `FrameOfData`
ModelDef(Vec<model::DataSet>),
/// Data about tracked content
FrameOfData(FrameOfData),
/// Message from the sender application
MessageString(String),
/// The sender application did not understand the request
UnrecognizedRequest,
}
/// Enumeration of possible requests sent to `NatNet`
#[derive(Clone, Debug, PartialEq)]
pub enum
|
{
/// Send ping to other application
///
/// This should result in a `NatNetResponse::Ping`
Ping(CString),
/// Request model definitions
ModelDefinitions,
/// Request a frame of data
FrameOfData,
}
impl Into<Vec<u8>> for NatNetRequest {
fn into(self) -> Vec<u8> {
// Pre-allocate some bytes for the message
// most messages are smaller than this
let mut bytes = Vec::with_capacity(32);
match self {
NatNetRequest::ModelDefinitions => {
bytes.write_u16::<LittleEndian>(NatNetMsgType::RequestModelDef as u16).unwrap();
bytes.write_u16::<LittleEndian>(0).unwrap();
}
NatNetRequest::FrameOfData => {
bytes.write_u16::<LittleEndian>(NatNetMsgType::RequestFrameOfData as u16).unwrap();
bytes.write_u16::<LittleEndian>(0).unwrap();
}
NatNetRequest::Ping(data) => {
let str_data = data.to_bytes_with_nul();
bytes.write_u16::<LittleEndian>(NatNetMsgType::Ping as u16).unwrap();
// NatNet does not support more than 100_000 bytes in messages,
// to support this restriction in an Into we simply truncate
// FIXME: Use `TryInto` instead
if str_data.len() > u16::max_value() as usize {
bytes.write_u16::<LittleEndian>(u16::max_value()).unwrap();
// The message might still be valid so we append as much as
// possible, NOTE: We need to append C-String null to the
// end and so we must take `max_value() - 1`
bytes.extend_from_slice(&str_data[..u16::max_value() as usize - 1]);
bytes.push(b'\0');
} else {
bytes.write_u16::<LittleEndian>(str_data.len() as u16).unwrap();
bytes.extend_from_slice(str_data);
}
}
}
bytes
}
}
|
NatNetRequest
|
identifier_name
|
interning.rs
|
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::collections::HashMap;
use std::hash;
use std::sync::atomic;
use cpython::{ObjectProtocol, PyErr, PyType, Python, ToPyObject};
use parking_lot::{Mutex, RwLock};
use crate::core::{Key, Value, FNV};
use crate::externs;
///
/// A struct that encapsulates interning of python `Value`s as comparable `Key`s.
///
/// To minimize the total amount of time spent in python code comparing objects (represented on
/// the rust side of the FFI boundary as `Value` instances) to one another, this API supports
/// memoizing `Value`s as `Key`s.
///
/// Creating a `Key` involves interning a `Value` under a (private) `InternKey` struct which
/// implements `Hash` and `Eq` using the precomputed python `__hash__` for the `Value` and
/// delegating to python's `__eq__`, respectively.
///
/// Currently `Value`s are interned indefinitely as `Key`s, meaning that they can never
/// be collected: it's possible that this can eventually be improved by either:
///
/// 1) switching to directly linking-against or embedding python, such that the `Value`
/// type goes away in favor of direct usage of a python object wrapper struct.
/// 2) This structure might begin storing weak-references to `Key`s and/or `Value`s, which
/// would allow the associated `Value` handles to be dropped when they were no longer used.
/// The challenge to this approach is that it would make it more difficult to pass
/// `Key`/`Value` instances across the FFI boundary.
/// 3) `Value` could implement `Eq`/`Hash` directly via extern calls to python (although we've
/// avoided doing this so far because it would hide a relatively expensive operation behind
/// those usually-inexpensive traits).
///
/// To avoid deadlocks, methods of Interns require that the GIL is held, and then explicitly release
/// it before acquiring inner locks. That way we can guarantee that these locks are always acquired
/// before the GIL (Value equality in particular might re-acquire it).
///
#[derive(Default)]
pub struct Interns {
forward_keys: Mutex<HashMap<InternKey, Key, FNV>>,
reverse_keys: RwLock<HashMap<Key, Value, FNV>>,
id_generator: atomic::AtomicU64,
}
impl Interns {
pub fn new() -> Interns {
Interns::default()
}
pub fn key_insert(&self, py: Python, v: Value) -> Result<Key, PyErr> {
let (intern_key, type_id) = {
let obj = v.to_py_object(py).into();
(InternKey(v.hash(py)?, obj), (&v.get_type(py)).into())
};
py.allow_threads(|| {
let (key, key_was_new) = {
let mut forward_keys = self.forward_keys.lock();
if let Some(key) = forward_keys.get(&intern_key) {
(*key, false)
} else {
let id = self.id_generator.fetch_add(1, atomic::Ordering::SeqCst);
let key = Key::new(id, type_id);
forward_keys.insert(intern_key, key);
(key, true)
}
};
if key_was_new {
self.reverse_keys.write().insert(key, v);
}
Ok(key)
})
}
pub fn key_get(&self, k: &Key) -> Value {
// NB: We do not need to acquire+release the GIL before getting a Value for a Key, because
// neither `Key::eq` nor `Value::clone` acquire the GIL.
self
.reverse_keys
.read()
.get(&k)
|
}
struct InternKey(isize, Value);
impl Eq for InternKey {}
impl PartialEq for InternKey {
fn eq(&self, other: &InternKey) -> bool {
externs::equals(&self.1, &other.1)
}
}
impl hash::Hash for InternKey {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
struct InternType(isize, PyType);
impl Eq for InternType {}
impl PartialEq for InternType {
fn eq(&self, other: &InternType) -> bool {
self.1 == other.1
}
}
impl hash::Hash for InternType {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
|
.cloned()
.unwrap_or_else(|| panic!("Previously memoized object disappeared for {:?}", k))
}
|
random_line_split
|
interning.rs
|
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::collections::HashMap;
use std::hash;
use std::sync::atomic;
use cpython::{ObjectProtocol, PyErr, PyType, Python, ToPyObject};
use parking_lot::{Mutex, RwLock};
use crate::core::{Key, Value, FNV};
use crate::externs;
///
/// A struct that encapsulates interning of python `Value`s as comparable `Key`s.
///
/// To minimize the total amount of time spent in python code comparing objects (represented on
/// the rust side of the FFI boundary as `Value` instances) to one another, this API supports
/// memoizing `Value`s as `Key`s.
///
/// Creating a `Key` involves interning a `Value` under a (private) `InternKey` struct which
/// implements `Hash` and `Eq` using the precomputed python `__hash__` for the `Value` and
/// delegating to python's `__eq__`, respectively.
///
/// Currently `Value`s are interned indefinitely as `Key`s, meaning that they can never
/// be collected: it's possible that this can eventually be improved by either:
///
/// 1) switching to directly linking-against or embedding python, such that the `Value`
/// type goes away in favor of direct usage of a python object wrapper struct.
/// 2) This structure might begin storing weak-references to `Key`s and/or `Value`s, which
/// would allow the associated `Value` handles to be dropped when they were no longer used.
/// The challenge to this approach is that it would make it more difficult to pass
/// `Key`/`Value` instances across the FFI boundary.
/// 3) `Value` could implement `Eq`/`Hash` directly via extern calls to python (although we've
/// avoided doing this so far because it would hide a relatively expensive operation behind
/// those usually-inexpensive traits).
///
/// To avoid deadlocks, methods of Interns require that the GIL is held, and then explicitly release
/// it before acquiring inner locks. That way we can guarantee that these locks are always acquired
/// before the GIL (Value equality in particular might re-acquire it).
///
#[derive(Default)]
pub struct Interns {
forward_keys: Mutex<HashMap<InternKey, Key, FNV>>,
reverse_keys: RwLock<HashMap<Key, Value, FNV>>,
id_generator: atomic::AtomicU64,
}
impl Interns {
pub fn new() -> Interns {
Interns::default()
}
pub fn key_insert(&self, py: Python, v: Value) -> Result<Key, PyErr> {
let (intern_key, type_id) = {
let obj = v.to_py_object(py).into();
(InternKey(v.hash(py)?, obj), (&v.get_type(py)).into())
};
py.allow_threads(|| {
let (key, key_was_new) = {
let mut forward_keys = self.forward_keys.lock();
if let Some(key) = forward_keys.get(&intern_key) {
(*key, false)
} else {
let id = self.id_generator.fetch_add(1, atomic::Ordering::SeqCst);
let key = Key::new(id, type_id);
forward_keys.insert(intern_key, key);
(key, true)
}
};
if key_was_new {
self.reverse_keys.write().insert(key, v);
}
Ok(key)
})
}
pub fn key_get(&self, k: &Key) -> Value {
// NB: We do not need to acquire+release the GIL before getting a Value for a Key, because
// neither `Key::eq` nor `Value::clone` acquire the GIL.
self
.reverse_keys
.read()
.get(&k)
.cloned()
.unwrap_or_else(|| panic!("Previously memoized object disappeared for {:?}", k))
}
}
struct InternKey(isize, Value);
impl Eq for InternKey {}
impl PartialEq for InternKey {
fn eq(&self, other: &InternKey) -> bool {
externs::equals(&self.1, &other.1)
}
}
impl hash::Hash for InternKey {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
struct InternType(isize, PyType);
impl Eq for InternType {}
impl PartialEq for InternType {
fn eq(&self, other: &InternType) -> bool
|
}
impl hash::Hash for InternType {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
|
{
self.1 == other.1
}
|
identifier_body
|
interning.rs
|
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::collections::HashMap;
use std::hash;
use std::sync::atomic;
use cpython::{ObjectProtocol, PyErr, PyType, Python, ToPyObject};
use parking_lot::{Mutex, RwLock};
use crate::core::{Key, Value, FNV};
use crate::externs;
///
/// A struct that encapsulates interning of python `Value`s as comparable `Key`s.
///
/// To minimize the total amount of time spent in python code comparing objects (represented on
/// the rust side of the FFI boundary as `Value` instances) to one another, this API supports
/// memoizing `Value`s as `Key`s.
///
/// Creating a `Key` involves interning a `Value` under a (private) `InternKey` struct which
/// implements `Hash` and `Eq` using the precomputed python `__hash__` for the `Value` and
/// delegating to python's `__eq__`, respectively.
///
/// Currently `Value`s are interned indefinitely as `Key`s, meaning that they can never
/// be collected: it's possible that this can eventually be improved by either:
///
/// 1) switching to directly linking-against or embedding python, such that the `Value`
/// type goes away in favor of direct usage of a python object wrapper struct.
/// 2) This structure might begin storing weak-references to `Key`s and/or `Value`s, which
/// would allow the associated `Value` handles to be dropped when they were no longer used.
/// The challenge to this approach is that it would make it more difficult to pass
/// `Key`/`Value` instances across the FFI boundary.
/// 3) `Value` could implement `Eq`/`Hash` directly via extern calls to python (although we've
/// avoided doing this so far because it would hide a relatively expensive operation behind
/// those usually-inexpensive traits).
///
/// To avoid deadlocks, methods of Interns require that the GIL is held, and then explicitly release
/// it before acquiring inner locks. That way we can guarantee that these locks are always acquired
/// before the GIL (Value equality in particular might re-acquire it).
///
#[derive(Default)]
pub struct Interns {
forward_keys: Mutex<HashMap<InternKey, Key, FNV>>,
reverse_keys: RwLock<HashMap<Key, Value, FNV>>,
id_generator: atomic::AtomicU64,
}
impl Interns {
pub fn new() -> Interns {
Interns::default()
}
pub fn key_insert(&self, py: Python, v: Value) -> Result<Key, PyErr> {
let (intern_key, type_id) = {
let obj = v.to_py_object(py).into();
(InternKey(v.hash(py)?, obj), (&v.get_type(py)).into())
};
py.allow_threads(|| {
let (key, key_was_new) = {
let mut forward_keys = self.forward_keys.lock();
if let Some(key) = forward_keys.get(&intern_key) {
(*key, false)
} else {
let id = self.id_generator.fetch_add(1, atomic::Ordering::SeqCst);
let key = Key::new(id, type_id);
forward_keys.insert(intern_key, key);
(key, true)
}
};
if key_was_new {
self.reverse_keys.write().insert(key, v);
}
Ok(key)
})
}
pub fn
|
(&self, k: &Key) -> Value {
// NB: We do not need to acquire+release the GIL before getting a Value for a Key, because
// neither `Key::eq` nor `Value::clone` acquire the GIL.
self
.reverse_keys
.read()
.get(&k)
.cloned()
.unwrap_or_else(|| panic!("Previously memoized object disappeared for {:?}", k))
}
}
struct InternKey(isize, Value);
impl Eq for InternKey {}
impl PartialEq for InternKey {
fn eq(&self, other: &InternKey) -> bool {
externs::equals(&self.1, &other.1)
}
}
impl hash::Hash for InternKey {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
struct InternType(isize, PyType);
impl Eq for InternType {}
impl PartialEq for InternType {
fn eq(&self, other: &InternType) -> bool {
self.1 == other.1
}
}
impl hash::Hash for InternType {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
|
key_get
|
identifier_name
|
interning.rs
|
// Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::collections::HashMap;
use std::hash;
use std::sync::atomic;
use cpython::{ObjectProtocol, PyErr, PyType, Python, ToPyObject};
use parking_lot::{Mutex, RwLock};
use crate::core::{Key, Value, FNV};
use crate::externs;
///
/// A struct that encapsulates interning of python `Value`s as comparable `Key`s.
///
/// To minimize the total amount of time spent in python code comparing objects (represented on
/// the rust side of the FFI boundary as `Value` instances) to one another, this API supports
/// memoizing `Value`s as `Key`s.
///
/// Creating a `Key` involves interning a `Value` under a (private) `InternKey` struct which
/// implements `Hash` and `Eq` using the precomputed python `__hash__` for the `Value` and
/// delegating to python's `__eq__`, respectively.
///
/// Currently `Value`s are interned indefinitely as `Key`s, meaning that they can never
/// be collected: it's possible that this can eventually be improved by either:
///
/// 1) switching to directly linking-against or embedding python, such that the `Value`
/// type goes away in favor of direct usage of a python object wrapper struct.
/// 2) This structure might begin storing weak-references to `Key`s and/or `Value`s, which
/// would allow the associated `Value` handles to be dropped when they were no longer used.
/// The challenge to this approach is that it would make it more difficult to pass
/// `Key`/`Value` instances across the FFI boundary.
/// 3) `Value` could implement `Eq`/`Hash` directly via extern calls to python (although we've
/// avoided doing this so far because it would hide a relatively expensive operation behind
/// those usually-inexpensive traits).
///
/// To avoid deadlocks, methods of Interns require that the GIL is held, and then explicitly release
/// it before acquiring inner locks. That way we can guarantee that these locks are always acquired
/// before the GIL (Value equality in particular might re-acquire it).
///
#[derive(Default)]
pub struct Interns {
forward_keys: Mutex<HashMap<InternKey, Key, FNV>>,
reverse_keys: RwLock<HashMap<Key, Value, FNV>>,
id_generator: atomic::AtomicU64,
}
impl Interns {
pub fn new() -> Interns {
Interns::default()
}
pub fn key_insert(&self, py: Python, v: Value) -> Result<Key, PyErr> {
let (intern_key, type_id) = {
let obj = v.to_py_object(py).into();
(InternKey(v.hash(py)?, obj), (&v.get_type(py)).into())
};
py.allow_threads(|| {
let (key, key_was_new) = {
let mut forward_keys = self.forward_keys.lock();
if let Some(key) = forward_keys.get(&intern_key) {
(*key, false)
} else
|
};
if key_was_new {
self.reverse_keys.write().insert(key, v);
}
Ok(key)
})
}
pub fn key_get(&self, k: &Key) -> Value {
// NB: We do not need to acquire+release the GIL before getting a Value for a Key, because
// neither `Key::eq` nor `Value::clone` acquire the GIL.
self
.reverse_keys
.read()
.get(&k)
.cloned()
.unwrap_or_else(|| panic!("Previously memoized object disappeared for {:?}", k))
}
}
struct InternKey(isize, Value);
impl Eq for InternKey {}
impl PartialEq for InternKey {
fn eq(&self, other: &InternKey) -> bool {
externs::equals(&self.1, &other.1)
}
}
impl hash::Hash for InternKey {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
struct InternType(isize, PyType);
impl Eq for InternType {}
impl PartialEq for InternType {
fn eq(&self, other: &InternType) -> bool {
self.1 == other.1
}
}
impl hash::Hash for InternType {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
|
{
let id = self.id_generator.fetch_add(1, atomic::Ordering::SeqCst);
let key = Key::new(id, type_id);
forward_keys.insert(intern_key, key);
(key, true)
}
|
conditional_block
|
mod.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/. */
//! The implementation of the DOM.
//!
//! The DOM is comprised of interfaces (defined by specifications using
//! [WebIDL](https://heycam.github.io/webidl/)) that are implemented as Rust
//! structs in submodules of this module. Its implementation is documented
//! below.
//!
//! A DOM object and its reflector
//! ==============================
//!
//! The implementation of an interface `Foo` in Servo's DOM involves two
//! related but distinct objects:
//!
//! * the **DOM object**: an instance of the Rust struct `dom::foo::Foo`
//! (marked with the `#[dom_struct]` attribute) on the Rust heap;
//! * the **reflector**: a `JSObject` allocated by SpiderMonkey, that owns the
//! DOM object.
//!
//! Memory management
//! =================
//!
//! Reflectors of DOM objects, and thus the DOM objects themselves, are managed
//! by the SpiderMonkey Garbage Collector. Thus, keeping alive a DOM object
//! is done through its reflector.
//!
//! For more information, see:
//!
//! * rooting pointers on the stack:
//! the [`Root`](bindings/js/struct.Root.html) smart pointer;
//! * tracing pointers in member fields: the [`JS`](bindings/js/struct.JS.html),
//! [`MutNullableJS`](bindings/js/struct.MutNullableJS.html) and
//! [`MutJS`](bindings/js/struct.MutJS.html) smart pointers and
//! [the tracing implementation](bindings/trace/index.html);
//! * rooting pointers from across thread boundaries or in channels: the
//! [`Trusted`](bindings/refcounted/struct.Trusted.html) smart pointer;
//!
//! Inheritance
//! ===========
//!
//! Rust does not support struct inheritance, as would be used for the
//! object-oriented DOM APIs. To work around this issue, Servo stores an
//! instance of the superclass in the first field of its subclasses. (Note that
//! it is stored by value, rather than in a smart pointer such as `JS<T>`.)
//!
//! This implies that a pointer to an object can safely be cast to a pointer
//! to all its classes.
//!
//! This invariant is enforced by the lint in
//! `plugins::lints::inheritance_integrity`.
//!
//! Interfaces which either derive from or are derived by other interfaces
//! implement the `Castable` trait, which provides three methods `is::<T>()`,
//! `downcast::<T>()` and `upcast::<T>()` to cast across the type hierarchy
//! and check whether a given instance is of a given type.
//!
//! ```ignore
//! use dom::bindings::inheritance::Castable;
//! use dom::element::Element;
//! use dom::htmlelement::HTMLElement;
//! use dom::htmlinputelement::HTMLInputElement;
//!
//! if let Some(elem) = node.downcast::<Element> {
//! if elem.is::<HTMLInputElement>() {
//! return elem.upcast::<HTMLElement>();
//! }
//! }
//! ```
//!
//! Furthermore, when discriminating a given instance against multiple
//! interface types, code generation provides a convenient TypeId enum
//! which can be used to write `match` expressions instead of multiple
//! calls to `Castable::is::<T>`. The `type_id()` method of an instance is
//! provided by the farthest interface it derives from, e.g. `EventTarget`
//! for `HTMLMediaElement`. For convenience, that method is also provided
//! on the `Node` interface to avoid unnecessary upcasts to `EventTarget`.
//!
//! ```ignore
//! use dom::bindings::inheritance::{EventTargetTypeId, NodeTypeId};
//!
//! match *node.type_id() {
//! EventTargetTypeId::Node(NodeTypeId::CharacterData(_)) =>...,
//! EventTargetTypeId::Node(NodeTypeId::Element(_)) =>...,
//! ...,
//! }
//! ```
//!
//! Construction
//! ============
//!
//! DOM objects of type `T` in Servo have two constructors:
//!
//! * a `T::new_inherited` static method that returns a plain `T`, and
//! * a `T::new` static method that returns `Root<T>`.
//!
//! (The result of either method can be wrapped in `Result`, if that is
//! appropriate for the type in question.)
//!
//! The latter calls the former, boxes the result, and creates a reflector
//! corresponding to it by calling `dom::bindings::utils::reflect_dom_object`
//! (which yields ownership of the object to the SpiderMonkey Garbage Collector).
//! This is the API to use when creating a DOM object.
//!
//! The former should only be called by the latter, and by subclasses'
//! `new_inherited` methods.
//!
//! DOM object constructors in JavaScript correspond to a `T::Constructor`
//! static method. This method is always fallible.
//!
//! Destruction
//! ===========
//!
//! When the SpiderMonkey Garbage Collector discovers that the reflector of a
//! DOM object is garbage, it calls the reflector's finalization hook. This
//! function deletes the reflector's DOM object, calling its destructor in the
//! process.
//!
//! Mutability and aliasing
//! =======================
//!
//! Reflectors are JavaScript objects, and as such can be freely aliased. As
//! Rust does not allow mutable aliasing, mutable borrows of DOM objects are
//! not allowed. In particular, any mutable fields use `Cell` or `DOMRefCell`
//! to manage their mutability.
//!
//! `Reflector` and `DomObject`
//! =============================
//!
//! Every DOM object has a `Reflector` as its first (transitive) member field.
//! This contains a `*mut JSObject` that points to its reflector.
//!
//! The `FooBinding::Wrap` function creates the reflector, stores a pointer to
//! the DOM object in the reflector, and initializes the pointer to the reflector
//! in the `Reflector` field.
//!
//! The `DomObject` trait provides a `reflector()` method that returns the
//! DOM object's `Reflector`. It is implemented automatically for DOM structs
//! through the `#[dom_struct]` attribute.
//!
//! Implementing methods for a DOM object
//! =====================================
//!
//! * `dom::bindings::codegen::Bindings::FooBindings::FooMethods` for methods
//! defined through IDL;
//! * `&self` public methods for public helpers;
//! * `&self` methods for private helpers.
//!
//! Accessing fields of a DOM object
//! ================================
//!
//! All fields of DOM objects are private; accessing them from outside their
//! module is done through explicit getter or setter methods.
//!
//! Inheritance and casting
//! =======================
//!
//! All DOM interfaces part of an inheritance chain (i.e. interfaces
//! that derive others or are derived from) implement the trait `Castable`
//! which provides both downcast and upcasts.
//!
//! ```ignore
//! # use script::dom::bindings::inheritance::Castable;
//! # use script::dom::element::Element;
//! # use script::dom::node::Node;
//! # use script::dom::htmlelement::HTMLElement;
//! fn f(element: &Element) {
//! let base = element.upcast::<Node>();
//! let derived = element.downcast::<HTMLElement>().unwrap();
//! }
//! ```
//!
//! Adding a new DOM interface
//! ==========================
//!
//! Adding a new interface `Foo` requires at least the following:
//!
//! * adding the new IDL file at `components/script/dom/webidls/Foo.webidl`;
//! * creating `components/script/dom/foo.rs`;
//! * listing `foo.rs` in `components/script/dom/mod.rs`;
//! * defining the DOM struct `Foo` with a `#[dom_struct]` attribute, a
//! superclass or `Reflector` member, and other members as appropriate;
//! * implementing the
//! `dom::bindings::codegen::Bindings::FooBindings::FooMethods` trait for
//! `Foo`;
//! * adding/updating the match arm in create_element in
//! `components/script/dom/create.rs` (only applicable to new types inheriting
//! from `HTMLElement`)
//!
//! More information is available in the [bindings module](bindings/index.html).
//!
//! Accessing DOM objects from layout
//! =================================
//!
//! Layout code can access the DOM through the
//! [`LayoutJS`](bindings/js/struct.LayoutJS.html) smart pointer. This does not
//! keep the DOM object alive; we ensure that no DOM code (Garbage Collection
//! in particular) runs while the layout thread is accessing the DOM.
//!
//! Methods accessible to layout are implemented on `LayoutJS<Foo>` using
//! `LayoutFooHelpers` traits.
#[macro_use]
pub mod macros;
pub mod types {
#[cfg(not(target_env = "msvc"))]
include!(concat!(env!("OUT_DIR"), "/InterfaceTypes.rs"));
#[cfg(target_env = "msvc")]
include!(concat!(env!("OUT_DIR"), "/build/InterfaceTypes.rs"));
}
pub mod abstractworker;
pub mod abstractworkerglobalscope;
pub mod activation;
pub mod attr;
pub mod beforeunloadevent;
pub mod bindings;
pub mod blob;
pub mod bluetooth;
pub mod bluetoothadvertisingevent;
pub mod bluetoothcharacteristicproperties;
pub mod bluetoothdevice;
pub mod bluetoothpermissionresult;
pub mod bluetoothremotegattcharacteristic;
pub mod bluetoothremotegattdescriptor;
pub mod bluetoothremotegattserver;
pub mod bluetoothremotegattservice;
pub mod bluetoothuuid;
pub mod canvasgradient;
pub mod canvaspattern;
pub mod canvasrenderingcontext2d;
pub mod characterdata;
pub mod client;
pub mod closeevent;
pub mod comment;
pub mod console;
mod create;
pub mod crypto;
pub mod css;
pub mod cssconditionrule;
pub mod cssfontfacerule;
pub mod cssgroupingrule;
pub mod cssimportrule;
pub mod csskeyframerule;
pub mod csskeyframesrule;
pub mod cssmediarule;
pub mod cssnamespacerule;
pub mod cssrule;
pub mod cssrulelist;
pub mod cssstyledeclaration;
pub mod cssstylerule;
pub mod cssstylesheet;
pub mod csssupportsrule;
pub mod cssviewportrule;
pub mod customevent;
pub mod dedicatedworkerglobalscope;
pub mod dissimilaroriginlocation;
pub mod dissimilaroriginwindow;
pub mod document;
pub mod documentfragment;
pub mod documenttype;
pub mod domexception;
pub mod domimplementation;
pub mod dommatrix;
pub mod dommatrixreadonly;
pub mod domparser;
pub mod dompoint;
pub mod dompointreadonly;
pub mod domquad;
pub mod domrect;
pub mod domrectreadonly;
pub mod domstringmap;
pub mod domtokenlist;
pub mod element;
pub mod errorevent;
pub mod event;
pub mod eventsource;
pub mod eventtarget;
pub mod extendableevent;
pub mod extendablemessageevent;
pub mod file;
pub mod filelist;
pub mod filereader;
pub mod filereadersync;
pub mod focusevent;
pub mod forcetouchevent;
pub mod formdata;
pub mod gamepad;
pub mod gamepadbutton;
pub mod gamepadbuttonlist;
pub mod gamepadevent;
pub mod gamepadlist;
pub mod globalscope;
pub mod hashchangeevent;
pub mod headers;
pub mod history;
pub mod htmlanchorelement;
pub mod htmlappletelement;
pub mod htmlareaelement;
pub mod htmlaudioelement;
pub mod htmlbaseelement;
pub mod htmlbodyelement;
pub mod htmlbrelement;
pub mod htmlbuttonelement;
pub mod htmlcanvaselement;
pub mod htmlcollection;
pub mod htmldataelement;
pub mod htmldatalistelement;
pub mod htmldetailselement;
pub mod htmldialogelement;
pub mod htmldirectoryelement;
pub mod htmldivelement;
pub mod htmldlistelement;
pub mod htmlelement;
pub mod htmlembedelement;
pub mod htmlfieldsetelement;
pub mod htmlfontelement;
pub mod htmlformcontrolscollection;
pub mod htmlformelement;
pub mod htmlframeelement;
pub mod htmlframesetelement;
pub mod htmlheadelement;
pub mod htmlheadingelement;
pub mod htmlhrelement;
pub mod htmlhtmlelement;
pub mod htmliframeelement;
pub mod htmlimageelement;
pub mod htmlinputelement;
pub mod htmllabelelement;
pub mod htmllegendelement;
pub mod htmllielement;
pub mod htmllinkelement;
pub mod htmlmapelement;
pub mod htmlmediaelement;
pub mod htmlmetaelement;
pub mod htmlmeterelement;
pub mod htmlmodelement;
pub mod htmlobjectelement;
pub mod htmlolistelement;
pub mod htmloptgroupelement;
pub mod htmloptionelement;
pub mod htmloptionscollection;
pub mod htmloutputelement;
pub mod htmlparagraphelement;
pub mod htmlparamelement;
pub mod htmlpreelement;
pub mod htmlprogresselement;
pub mod htmlquoteelement;
pub mod htmlscriptelement;
pub mod htmlselectelement;
pub mod htmlsourceelement;
pub mod htmlspanelement;
pub mod htmlstyleelement;
pub mod htmltablecaptionelement;
pub mod htmltablecellelement;
pub mod htmltablecolelement;
pub mod htmltabledatacellelement;
pub mod htmltableelement;
pub mod htmltableheadercellelement;
pub mod htmltablerowelement;
pub mod htmltablesectionelement;
pub mod htmltemplateelement;
pub mod htmltextareaelement;
pub mod htmltimeelement;
pub mod htmltitleelement;
pub mod htmltrackelement;
pub mod htmlulistelement;
pub mod htmlunknownelement;
pub mod htmlvideoelement;
pub mod imagedata;
pub mod keyboardevent;
pub mod location;
pub mod mediaerror;
pub mod medialist;
pub mod mediaquerylist;
pub mod mediaquerylistevent;
pub mod messageevent;
pub mod mimetype;
pub mod mimetypearray;
pub mod mouseevent;
pub mod mutationobserver;
pub mod mutationrecord;
pub mod namednodemap;
pub mod navigator;
pub mod navigatorinfo;
pub mod node;
pub mod nodeiterator;
pub mod nodelist;
pub mod pagetransitionevent;
pub mod performance;
pub mod performancetiming;
pub mod permissions;
pub mod permissionstatus;
pub mod plugin;
pub mod pluginarray;
pub mod popstateevent;
pub mod processinginstruction;
pub mod progressevent;
pub mod promise;
pub mod promisenativehandler;
pub mod radionodelist;
pub mod range;
pub mod request;
pub mod response;
pub mod screen;
pub mod serviceworker;
pub mod serviceworkercontainer;
pub mod serviceworkerglobalscope;
pub mod serviceworkerregistration;
pub mod servoparser;
pub mod storage;
pub mod storageevent;
pub mod stylesheet;
pub mod stylesheetlist;
pub mod svgelement;
pub mod svggraphicselement;
pub mod svgsvgelement;
pub mod testbinding;
pub mod testbindingiterable;
pub mod testbindingpairiterable;
pub mod testbindingproxy;
pub mod testrunner;
pub mod testworklet;
|
pub mod textencoder;
pub mod touch;
pub mod touchevent;
pub mod touchlist;
pub mod transitionevent;
pub mod treewalker;
pub mod uievent;
pub mod url;
pub mod urlhelper;
pub mod urlsearchparams;
pub mod userscripts;
pub mod validation;
pub mod validitystate;
pub mod values;
pub mod virtualmethods;
pub mod vr;
pub mod vrdisplay;
pub mod vrdisplaycapabilities;
pub mod vrdisplayevent;
pub mod vreyeparameters;
pub mod vrfieldofview;
pub mod vrframedata;
pub mod vrpose;
pub mod vrstageparameters;
pub mod webgl_extensions;
pub use self::webgl_extensions::ext::*;
pub mod webgl_validations;
pub mod webglactiveinfo;
pub mod webglbuffer;
pub mod webglcontextevent;
pub mod webglframebuffer;
pub mod webglobject;
pub mod webglprogram;
pub mod webglrenderbuffer;
pub mod webglrenderingcontext;
pub mod webglshader;
pub mod webglshaderprecisionformat;
pub mod webgltexture;
pub mod webgluniformlocation;
pub mod websocket;
pub mod window;
pub mod windowproxy;
pub mod worker;
pub mod workerglobalscope;
pub mod workerlocation;
pub mod workernavigator;
pub mod worklet;
pub mod workletglobalscope;
pub mod xmldocument;
pub mod xmlhttprequest;
pub mod xmlhttprequesteventtarget;
pub mod xmlhttprequestupload;
|
pub mod testworkletglobalscope;
pub mod text;
pub mod textdecoder;
|
random_line_split
|
largest-series-product.rs
|
use largest_series_product::*;
#[test]
fn return_is_a_result() {
assert!(lsp("29", 2).is_ok());
}
#[test]
#[ignore]
fn find_the_largest_product_when_span_equals_length() {
assert_eq!(Ok(18), lsp("29", 2));
}
#[test]
#[ignore]
fn find_the_largest_product_of_two_with_numbers_in_order() {
assert_eq!(Ok(72), lsp("0123456789", 2));
}
#[test]
#[ignore]
fn find_the_largest_product_of_two_with_numbers_not_in_order() {
assert_eq!(Ok(48), lsp("576802143", 2));
}
#[test]
#[ignore]
fn find_the_largest_product_of_three_with_numbers_in_order() {
assert_eq!(Ok(504), lsp("0123456789", 3));
}
#[test]
#[ignore]
fn find_the_largest_product_of_three_with_numbers_not_in_order() {
assert_eq!(Ok(270), lsp("1027839564", 3));
}
#[test]
#[ignore]
fn find_the_largest_product_of_five_with_numbers_in_order() {
assert_eq!(Ok(15_120), lsp("0123456789", 5));
}
#[test]
#[ignore]
fn span_of_six_in_a_large_number() {
assert_eq!(
Ok(23_520),
lsp("73167176531330624919225119674426574742355349194934", 6)
);
}
#[test]
#[ignore]
fn returns_zero_if_number_is_zeros() {
assert_eq!(Ok(0), lsp("0000", 2));
}
#[test]
#[ignore]
fn returns_zero_if_all_products_are_zero() {
assert_eq!(Ok(0), lsp("99099", 3));
}
#[test]
#[ignore]
fn a_span_is_longer_than_number_is_an_error() {
assert_eq!(Err(Error::SpanTooLong), lsp("123", 4));
}
// There may be some confusion about whether this should be 1 or error.
// The reasoning for it being 1 is this:
// There is one 0-character string contained in the empty string.
// That's the empty string itself.
// The empty product is 1 (the identity for multiplication).
// Therefore LSP('', 0) is 1.
// It's NOT the case that LSP('', 0) takes max of an empty list.
// So there is no error.
// Compare against LSP('123', 4):
// There are zero 4-character strings in '123'.
// So LSP('123', 4) really DOES take the max of an empty list.
// So LSP('123', 4) errors and LSP('', 0) does NOT.
#[test]
#[ignore]
fn an_empty_string_and_no_span_returns_one() {
assert_eq!(Ok(1), lsp("", 0));
}
#[test]
#[ignore]
fn
|
() {
assert_eq!(Ok(1), lsp("123", 0));
}
#[test]
#[ignore]
fn empty_string_and_non_zero_span_is_an_error() {
assert_eq!(Err(Error::SpanTooLong), lsp("", 1));
}
#[test]
#[ignore]
fn a_string_with_non_digits_is_an_error() {
assert_eq!(Err(Error::InvalidDigit('a')), lsp("1234a5", 2));
}
|
a_non_empty_string_and_no_span_returns_one
|
identifier_name
|
largest-series-product.rs
|
use largest_series_product::*;
#[test]
fn return_is_a_result() {
assert!(lsp("29", 2).is_ok());
}
#[test]
#[ignore]
fn find_the_largest_product_when_span_equals_length() {
assert_eq!(Ok(18), lsp("29", 2));
}
#[test]
#[ignore]
fn find_the_largest_product_of_two_with_numbers_in_order() {
assert_eq!(Ok(72), lsp("0123456789", 2));
}
#[test]
#[ignore]
fn find_the_largest_product_of_two_with_numbers_not_in_order() {
assert_eq!(Ok(48), lsp("576802143", 2));
}
#[test]
#[ignore]
fn find_the_largest_product_of_three_with_numbers_in_order() {
assert_eq!(Ok(504), lsp("0123456789", 3));
}
#[test]
#[ignore]
|
#[test]
#[ignore]
fn find_the_largest_product_of_five_with_numbers_in_order() {
assert_eq!(Ok(15_120), lsp("0123456789", 5));
}
#[test]
#[ignore]
fn span_of_six_in_a_large_number() {
assert_eq!(
Ok(23_520),
lsp("73167176531330624919225119674426574742355349194934", 6)
);
}
#[test]
#[ignore]
fn returns_zero_if_number_is_zeros() {
assert_eq!(Ok(0), lsp("0000", 2));
}
#[test]
#[ignore]
fn returns_zero_if_all_products_are_zero() {
assert_eq!(Ok(0), lsp("99099", 3));
}
#[test]
#[ignore]
fn a_span_is_longer_than_number_is_an_error() {
assert_eq!(Err(Error::SpanTooLong), lsp("123", 4));
}
// There may be some confusion about whether this should be 1 or error.
// The reasoning for it being 1 is this:
// There is one 0-character string contained in the empty string.
// That's the empty string itself.
// The empty product is 1 (the identity for multiplication).
// Therefore LSP('', 0) is 1.
// It's NOT the case that LSP('', 0) takes max of an empty list.
// So there is no error.
// Compare against LSP('123', 4):
// There are zero 4-character strings in '123'.
// So LSP('123', 4) really DOES take the max of an empty list.
// So LSP('123', 4) errors and LSP('', 0) does NOT.
#[test]
#[ignore]
fn an_empty_string_and_no_span_returns_one() {
assert_eq!(Ok(1), lsp("", 0));
}
#[test]
#[ignore]
fn a_non_empty_string_and_no_span_returns_one() {
assert_eq!(Ok(1), lsp("123", 0));
}
#[test]
#[ignore]
fn empty_string_and_non_zero_span_is_an_error() {
assert_eq!(Err(Error::SpanTooLong), lsp("", 1));
}
#[test]
#[ignore]
fn a_string_with_non_digits_is_an_error() {
assert_eq!(Err(Error::InvalidDigit('a')), lsp("1234a5", 2));
}
|
fn find_the_largest_product_of_three_with_numbers_not_in_order() {
assert_eq!(Ok(270), lsp("1027839564", 3));
}
|
random_line_split
|
largest-series-product.rs
|
use largest_series_product::*;
#[test]
fn return_is_a_result() {
assert!(lsp("29", 2).is_ok());
}
#[test]
#[ignore]
fn find_the_largest_product_when_span_equals_length() {
assert_eq!(Ok(18), lsp("29", 2));
}
#[test]
#[ignore]
fn find_the_largest_product_of_two_with_numbers_in_order() {
assert_eq!(Ok(72), lsp("0123456789", 2));
}
#[test]
#[ignore]
fn find_the_largest_product_of_two_with_numbers_not_in_order() {
assert_eq!(Ok(48), lsp("576802143", 2));
}
#[test]
#[ignore]
fn find_the_largest_product_of_three_with_numbers_in_order() {
assert_eq!(Ok(504), lsp("0123456789", 3));
}
#[test]
#[ignore]
fn find_the_largest_product_of_three_with_numbers_not_in_order() {
assert_eq!(Ok(270), lsp("1027839564", 3));
}
#[test]
#[ignore]
fn find_the_largest_product_of_five_with_numbers_in_order() {
assert_eq!(Ok(15_120), lsp("0123456789", 5));
}
#[test]
#[ignore]
fn span_of_six_in_a_large_number() {
assert_eq!(
Ok(23_520),
lsp("73167176531330624919225119674426574742355349194934", 6)
);
}
#[test]
#[ignore]
fn returns_zero_if_number_is_zeros() {
assert_eq!(Ok(0), lsp("0000", 2));
}
#[test]
#[ignore]
fn returns_zero_if_all_products_are_zero() {
assert_eq!(Ok(0), lsp("99099", 3));
}
#[test]
#[ignore]
fn a_span_is_longer_than_number_is_an_error() {
assert_eq!(Err(Error::SpanTooLong), lsp("123", 4));
}
// There may be some confusion about whether this should be 1 or error.
// The reasoning for it being 1 is this:
// There is one 0-character string contained in the empty string.
// That's the empty string itself.
// The empty product is 1 (the identity for multiplication).
// Therefore LSP('', 0) is 1.
// It's NOT the case that LSP('', 0) takes max of an empty list.
// So there is no error.
// Compare against LSP('123', 4):
// There are zero 4-character strings in '123'.
// So LSP('123', 4) really DOES take the max of an empty list.
// So LSP('123', 4) errors and LSP('', 0) does NOT.
#[test]
#[ignore]
fn an_empty_string_and_no_span_returns_one() {
assert_eq!(Ok(1), lsp("", 0));
}
#[test]
#[ignore]
fn a_non_empty_string_and_no_span_returns_one()
|
#[test]
#[ignore]
fn empty_string_and_non_zero_span_is_an_error() {
assert_eq!(Err(Error::SpanTooLong), lsp("", 1));
}
#[test]
#[ignore]
fn a_string_with_non_digits_is_an_error() {
assert_eq!(Err(Error::InvalidDigit('a')), lsp("1234a5", 2));
}
|
{
assert_eq!(Ok(1), lsp("123", 0));
}
|
identifier_body
|
conf.rs
|
use configuration::{ self, BitflagU32, VecStringPath };
use toml;
use std;
use levels as levelss;
use graphics::{ Color, Layer };
pub type VecVecStringPath = Vec<VecStringPath>;
pub type Dimension = [u32;2];
pub type Array4F32 = [f32;4];
pub type Array4F64 = [f64;4];
pub type VecF32 = Vec<f32>;
pub type VecU8 = Vec<u8>;
pub type Dungeons = Vec<levelss::Dungeon>;
pub type Array3U8 = [u8;3];
fn
|
(conf: &Config) -> Result<(),String> {
if conf.keys.up.len() == 0
|| conf.keys.down.len() == 0
|| conf.keys.left.len() == 0
|| conf.keys.right.len() == 0 {
return Err("ERROR: configuration file invalid: keys mustn't be empty".into());
}
// assert persistent snd and static snd doesn't overlap
if conf.entities.monster_persistent_snd == conf.entities.laser_persistent_snd {
return Err("ERROR: configuration file invalid: monster_persistent_snd and laser_persistent_snd must be different".into());
}
Ok(())
}
configure!(
file = "config.toml";
debug_file = "config.toml";
save_file = "save.toml";
constraint = config_constraint;
general: {
number_of_thread: t usize,
persistent_snd_cooldown: t usize,
difficulty: t f32 save difficulty,
},
keys: {
up: t VecU8,
down: t VecU8,
left: t VecU8,
right: t VecU8,
escape: t VecU8,
},
effect: {
color: t Color,
angles: t VecF32,
persistance: t f32,
thickness: t f32,
inner_length: t f32,
length: t f32,
},
physic: {
rate: t f32,
unit: t f32,
},
touch: {
joystick_rec: t Array4F64,
joystick_radius: t f64,
escape_rec: t Array4F64,
},
joystick: {
time_to_repeat: t f32,
time_to_start_repeating: t f32,
press_epsilon: t f32,
release_epsilon: t f32,
},
menu:{
entry_color: t Color,
cursor_color: t Color,
background_color: t Color,
clic_snd: t usize,
background_width: t f32,
background_height: t f32,
},
entities: {
text_color: t Color,
ball_group: t BitflagU32,
ball_mask: t BitflagU32,
ball_killer_mask: t BitflagU32,
ball_kill_snd: t usize,
ball_die_snd: t usize,
ball_radius: t f32,
ball_velocity: t f32,
ball_time: t f32,
ball_weight: t f32,
ball_color: t Color,
ball_layer: t Layer,
ball_vel_snd_coef: t f32,
ball_vel_snd: t usize,
laser_group: t BitflagU32,
laser_mask: t BitflagU32,
laser_killer_mask: t BitflagU32,
laser_kill_snd: t usize,
laser_radius: t f32,
laser_color: t Color,
laser_layer: t Layer,
laser_persistent_snd: t usize,
column_group: t BitflagU32,
column_mask: t BitflagU32,
column_radius: t f32,
column_color: t Color,
column_layer: t Layer,
column_cooldown: t f32,
column_spawn_snd: t usize,
char_group: t BitflagU32,
char_mask: t BitflagU32,
char_radius: t f32,
char_velocity: t f32,
char_time: t f32,
char_weight: t f32,
char_color: t Color,
char_layer: t Layer,
char_die_snd: t usize,
char_restart: t f32,
wall_group: t BitflagU32,
wall_mask: t BitflagU32,
wall_radius: t f32,
wall_color: t Color,
wall_layer: t Layer,
monster_vision_mask: t BitflagU32,
monster_killer_mask: t BitflagU32,
monster_kill_snd: t usize,
monster_die_snd: t usize,
monster_group: t BitflagU32,
monster_mask: t BitflagU32,
monster_vision_time: t f32,
monster_radius: t f32,
monster_velocity: t f32,
monster_time: t f32,
monster_weight: t f32,
monster_color: t Color,
monster_layer: t Layer,
monster_persistent_snd: t usize,
portal_end_color: t Color,
portal_end_layer: t Layer,
portal_start_color: t Color,
portal_start_layer: t Layer,
portal_snd: t usize,
},
levels: {
hall_length: t usize,
corridor_length: t usize,
dir: t VecStringPath,
entry_music: t VecStringPath,
check_level: e String [always,debug,never],
empty_col: t Array3U8,
char_col: t Array3U8,
portal_col: t Array3U8,
laser_col: t Array3U8,
monster_col: t Array3U8,
column_col: t Array3U8,
wall_col: t Array3U8,
},
audio: {
effect_dir: t VecStringPath,
music_dir: t VecStringPath,
global_volume: t f32 save global_volume,
music_volume: t f32 save music_volume,
effect_volume: t f32 save effect_volume,
distance_model: e String [linear,pow2],
distance_model_min: t f32,
distance_model_max: t f32,
short_effects: t VecVecStringPath,
persistent_effects: t VecVecStringPath,
transition_type: e String [instant,smooth,overlap],
transition_time: t u64,
},
window: {
dimension: t Dimension,
vsync: t bool,
multisampling: t u16,
fullscreen: t bool,
fullscreen_on_primary_monitor: t bool,
fullscreen_monitor: t usize,
},
graphics: {
base03: t Array4F32,
base02: t Array4F32,
base01: t Array4F32,
base00: t Array4F32,
base0: t Array4F32,
base1: t Array4F32,
base2: t Array4F32,
base3: t Array4F32,
yellow: t Array4F32,
orange: t Array4F32,
red: t Array4F32,
magenta: t Array4F32,
violet: t Array4F32,
blue: t Array4F32,
cyan: t Array4F32,
green: t Array4F32,
mode: e String [light,dark] save mode,
luminosity: t f32 save luminosity,
circle_precision: t usize,
font_file: t VecStringPath,
billboard_font_scale: t f32,
font_scale: t f32,
},
text: {
top: t i32,
bottom: t i32,
right: t i32,
left: t i32,
},
camera: {
zoom: t f32,
},
event_loop: {
ups: t u64,
max_fps: t u64,
},
);
|
config_constraint
|
identifier_name
|
conf.rs
|
use configuration::{ self, BitflagU32, VecStringPath };
use toml;
use std;
use levels as levelss;
use graphics::{ Color, Layer };
pub type VecVecStringPath = Vec<VecStringPath>;
pub type Dimension = [u32;2];
pub type Array4F32 = [f32;4];
pub type Array4F64 = [f64;4];
pub type VecF32 = Vec<f32>;
pub type VecU8 = Vec<u8>;
pub type Dungeons = Vec<levelss::Dungeon>;
pub type Array3U8 = [u8;3];
fn config_constraint(conf: &Config) -> Result<(),String>
|
configure!(
file = "config.toml";
debug_file = "config.toml";
save_file = "save.toml";
constraint = config_constraint;
general: {
number_of_thread: t usize,
persistent_snd_cooldown: t usize,
difficulty: t f32 save difficulty,
},
keys: {
up: t VecU8,
down: t VecU8,
left: t VecU8,
right: t VecU8,
escape: t VecU8,
},
effect: {
color: t Color,
angles: t VecF32,
persistance: t f32,
thickness: t f32,
inner_length: t f32,
length: t f32,
},
physic: {
rate: t f32,
unit: t f32,
},
touch: {
joystick_rec: t Array4F64,
joystick_radius: t f64,
escape_rec: t Array4F64,
},
joystick: {
time_to_repeat: t f32,
time_to_start_repeating: t f32,
press_epsilon: t f32,
release_epsilon: t f32,
},
menu:{
entry_color: t Color,
cursor_color: t Color,
background_color: t Color,
clic_snd: t usize,
background_width: t f32,
background_height: t f32,
},
entities: {
text_color: t Color,
ball_group: t BitflagU32,
ball_mask: t BitflagU32,
ball_killer_mask: t BitflagU32,
ball_kill_snd: t usize,
ball_die_snd: t usize,
ball_radius: t f32,
ball_velocity: t f32,
ball_time: t f32,
ball_weight: t f32,
ball_color: t Color,
ball_layer: t Layer,
ball_vel_snd_coef: t f32,
ball_vel_snd: t usize,
laser_group: t BitflagU32,
laser_mask: t BitflagU32,
laser_killer_mask: t BitflagU32,
laser_kill_snd: t usize,
laser_radius: t f32,
laser_color: t Color,
laser_layer: t Layer,
laser_persistent_snd: t usize,
column_group: t BitflagU32,
column_mask: t BitflagU32,
column_radius: t f32,
column_color: t Color,
column_layer: t Layer,
column_cooldown: t f32,
column_spawn_snd: t usize,
char_group: t BitflagU32,
char_mask: t BitflagU32,
char_radius: t f32,
char_velocity: t f32,
char_time: t f32,
char_weight: t f32,
char_color: t Color,
char_layer: t Layer,
char_die_snd: t usize,
char_restart: t f32,
wall_group: t BitflagU32,
wall_mask: t BitflagU32,
wall_radius: t f32,
wall_color: t Color,
wall_layer: t Layer,
monster_vision_mask: t BitflagU32,
monster_killer_mask: t BitflagU32,
monster_kill_snd: t usize,
monster_die_snd: t usize,
monster_group: t BitflagU32,
monster_mask: t BitflagU32,
monster_vision_time: t f32,
monster_radius: t f32,
monster_velocity: t f32,
monster_time: t f32,
monster_weight: t f32,
monster_color: t Color,
monster_layer: t Layer,
monster_persistent_snd: t usize,
portal_end_color: t Color,
portal_end_layer: t Layer,
portal_start_color: t Color,
portal_start_layer: t Layer,
portal_snd: t usize,
},
levels: {
hall_length: t usize,
corridor_length: t usize,
dir: t VecStringPath,
entry_music: t VecStringPath,
check_level: e String [always,debug,never],
empty_col: t Array3U8,
char_col: t Array3U8,
portal_col: t Array3U8,
laser_col: t Array3U8,
monster_col: t Array3U8,
column_col: t Array3U8,
wall_col: t Array3U8,
},
audio: {
effect_dir: t VecStringPath,
music_dir: t VecStringPath,
global_volume: t f32 save global_volume,
music_volume: t f32 save music_volume,
effect_volume: t f32 save effect_volume,
distance_model: e String [linear,pow2],
distance_model_min: t f32,
distance_model_max: t f32,
short_effects: t VecVecStringPath,
persistent_effects: t VecVecStringPath,
transition_type: e String [instant,smooth,overlap],
transition_time: t u64,
},
window: {
dimension: t Dimension,
vsync: t bool,
multisampling: t u16,
fullscreen: t bool,
fullscreen_on_primary_monitor: t bool,
fullscreen_monitor: t usize,
},
graphics: {
base03: t Array4F32,
base02: t Array4F32,
base01: t Array4F32,
base00: t Array4F32,
base0: t Array4F32,
base1: t Array4F32,
base2: t Array4F32,
base3: t Array4F32,
yellow: t Array4F32,
orange: t Array4F32,
red: t Array4F32,
magenta: t Array4F32,
violet: t Array4F32,
blue: t Array4F32,
cyan: t Array4F32,
green: t Array4F32,
mode: e String [light,dark] save mode,
luminosity: t f32 save luminosity,
circle_precision: t usize,
font_file: t VecStringPath,
billboard_font_scale: t f32,
font_scale: t f32,
},
text: {
top: t i32,
bottom: t i32,
right: t i32,
left: t i32,
},
camera: {
zoom: t f32,
},
event_loop: {
ups: t u64,
max_fps: t u64,
},
);
|
{
if conf.keys.up.len() == 0
|| conf.keys.down.len() == 0
|| conf.keys.left.len() == 0
|| conf.keys.right.len() == 0 {
return Err("ERROR: configuration file invalid: keys mustn't be empty".into());
}
// assert persistent snd and static snd doesn't overlap
if conf.entities.monster_persistent_snd == conf.entities.laser_persistent_snd {
return Err("ERROR: configuration file invalid: monster_persistent_snd and laser_persistent_snd must be different".into());
}
Ok(())
}
|
identifier_body
|
conf.rs
|
use configuration::{ self, BitflagU32, VecStringPath };
use toml;
use std;
use levels as levelss;
use graphics::{ Color, Layer };
pub type VecVecStringPath = Vec<VecStringPath>;
pub type Dimension = [u32;2];
pub type Array4F32 = [f32;4];
pub type Array4F64 = [f64;4];
pub type VecF32 = Vec<f32>;
pub type VecU8 = Vec<u8>;
pub type Dungeons = Vec<levelss::Dungeon>;
pub type Array3U8 = [u8;3];
fn config_constraint(conf: &Config) -> Result<(),String> {
if conf.keys.up.len() == 0
|| conf.keys.down.len() == 0
|| conf.keys.left.len() == 0
|| conf.keys.right.len() == 0
|
// assert persistent snd and static snd doesn't overlap
if conf.entities.monster_persistent_snd == conf.entities.laser_persistent_snd {
return Err("ERROR: configuration file invalid: monster_persistent_snd and laser_persistent_snd must be different".into());
}
Ok(())
}
configure!(
file = "config.toml";
debug_file = "config.toml";
save_file = "save.toml";
constraint = config_constraint;
general: {
number_of_thread: t usize,
persistent_snd_cooldown: t usize,
difficulty: t f32 save difficulty,
},
keys: {
up: t VecU8,
down: t VecU8,
left: t VecU8,
right: t VecU8,
escape: t VecU8,
},
effect: {
color: t Color,
angles: t VecF32,
persistance: t f32,
thickness: t f32,
inner_length: t f32,
length: t f32,
},
physic: {
rate: t f32,
unit: t f32,
},
touch: {
joystick_rec: t Array4F64,
joystick_radius: t f64,
escape_rec: t Array4F64,
},
joystick: {
time_to_repeat: t f32,
time_to_start_repeating: t f32,
press_epsilon: t f32,
release_epsilon: t f32,
},
menu:{
entry_color: t Color,
cursor_color: t Color,
background_color: t Color,
clic_snd: t usize,
background_width: t f32,
background_height: t f32,
},
entities: {
text_color: t Color,
ball_group: t BitflagU32,
ball_mask: t BitflagU32,
ball_killer_mask: t BitflagU32,
ball_kill_snd: t usize,
ball_die_snd: t usize,
ball_radius: t f32,
ball_velocity: t f32,
ball_time: t f32,
ball_weight: t f32,
ball_color: t Color,
ball_layer: t Layer,
ball_vel_snd_coef: t f32,
ball_vel_snd: t usize,
laser_group: t BitflagU32,
laser_mask: t BitflagU32,
laser_killer_mask: t BitflagU32,
laser_kill_snd: t usize,
laser_radius: t f32,
laser_color: t Color,
laser_layer: t Layer,
laser_persistent_snd: t usize,
column_group: t BitflagU32,
column_mask: t BitflagU32,
column_radius: t f32,
column_color: t Color,
column_layer: t Layer,
column_cooldown: t f32,
column_spawn_snd: t usize,
char_group: t BitflagU32,
char_mask: t BitflagU32,
char_radius: t f32,
char_velocity: t f32,
char_time: t f32,
char_weight: t f32,
char_color: t Color,
char_layer: t Layer,
char_die_snd: t usize,
char_restart: t f32,
wall_group: t BitflagU32,
wall_mask: t BitflagU32,
wall_radius: t f32,
wall_color: t Color,
wall_layer: t Layer,
monster_vision_mask: t BitflagU32,
monster_killer_mask: t BitflagU32,
monster_kill_snd: t usize,
monster_die_snd: t usize,
monster_group: t BitflagU32,
monster_mask: t BitflagU32,
monster_vision_time: t f32,
monster_radius: t f32,
monster_velocity: t f32,
monster_time: t f32,
monster_weight: t f32,
monster_color: t Color,
monster_layer: t Layer,
monster_persistent_snd: t usize,
portal_end_color: t Color,
portal_end_layer: t Layer,
portal_start_color: t Color,
portal_start_layer: t Layer,
portal_snd: t usize,
},
levels: {
hall_length: t usize,
corridor_length: t usize,
dir: t VecStringPath,
entry_music: t VecStringPath,
check_level: e String [always,debug,never],
empty_col: t Array3U8,
char_col: t Array3U8,
portal_col: t Array3U8,
laser_col: t Array3U8,
monster_col: t Array3U8,
column_col: t Array3U8,
wall_col: t Array3U8,
},
audio: {
effect_dir: t VecStringPath,
music_dir: t VecStringPath,
global_volume: t f32 save global_volume,
music_volume: t f32 save music_volume,
effect_volume: t f32 save effect_volume,
distance_model: e String [linear,pow2],
distance_model_min: t f32,
distance_model_max: t f32,
short_effects: t VecVecStringPath,
persistent_effects: t VecVecStringPath,
transition_type: e String [instant,smooth,overlap],
transition_time: t u64,
},
window: {
dimension: t Dimension,
vsync: t bool,
multisampling: t u16,
fullscreen: t bool,
fullscreen_on_primary_monitor: t bool,
fullscreen_monitor: t usize,
},
graphics: {
base03: t Array4F32,
base02: t Array4F32,
base01: t Array4F32,
base00: t Array4F32,
base0: t Array4F32,
base1: t Array4F32,
base2: t Array4F32,
base3: t Array4F32,
yellow: t Array4F32,
orange: t Array4F32,
red: t Array4F32,
magenta: t Array4F32,
violet: t Array4F32,
blue: t Array4F32,
cyan: t Array4F32,
green: t Array4F32,
mode: e String [light,dark] save mode,
luminosity: t f32 save luminosity,
circle_precision: t usize,
font_file: t VecStringPath,
billboard_font_scale: t f32,
font_scale: t f32,
},
text: {
top: t i32,
bottom: t i32,
right: t i32,
left: t i32,
},
camera: {
zoom: t f32,
},
event_loop: {
ups: t u64,
max_fps: t u64,
},
);
|
{
return Err("ERROR: configuration file invalid: keys mustn't be empty".into());
}
|
conditional_block
|
conf.rs
|
use configuration::{ self, BitflagU32, VecStringPath };
use toml;
use std;
use levels as levelss;
use graphics::{ Color, Layer };
pub type VecVecStringPath = Vec<VecStringPath>;
pub type Dimension = [u32;2];
pub type Array4F32 = [f32;4];
pub type Array4F64 = [f64;4];
pub type VecF32 = Vec<f32>;
pub type VecU8 = Vec<u8>;
pub type Dungeons = Vec<levelss::Dungeon>;
pub type Array3U8 = [u8;3];
fn config_constraint(conf: &Config) -> Result<(),String> {
if conf.keys.up.len() == 0
|| conf.keys.down.len() == 0
|| conf.keys.left.len() == 0
|| conf.keys.right.len() == 0 {
return Err("ERROR: configuration file invalid: keys mustn't be empty".into());
}
// assert persistent snd and static snd doesn't overlap
if conf.entities.monster_persistent_snd == conf.entities.laser_persistent_snd {
return Err("ERROR: configuration file invalid: monster_persistent_snd and laser_persistent_snd must be different".into());
}
Ok(())
}
configure!(
file = "config.toml";
debug_file = "config.toml";
save_file = "save.toml";
constraint = config_constraint;
general: {
number_of_thread: t usize,
persistent_snd_cooldown: t usize,
difficulty: t f32 save difficulty,
},
keys: {
up: t VecU8,
down: t VecU8,
left: t VecU8,
right: t VecU8,
escape: t VecU8,
},
effect: {
color: t Color,
angles: t VecF32,
persistance: t f32,
thickness: t f32,
inner_length: t f32,
length: t f32,
},
physic: {
rate: t f32,
unit: t f32,
},
touch: {
joystick_rec: t Array4F64,
joystick_radius: t f64,
escape_rec: t Array4F64,
},
joystick: {
time_to_repeat: t f32,
time_to_start_repeating: t f32,
press_epsilon: t f32,
release_epsilon: t f32,
},
menu:{
entry_color: t Color,
cursor_color: t Color,
background_color: t Color,
clic_snd: t usize,
background_width: t f32,
background_height: t f32,
},
entities: {
text_color: t Color,
ball_group: t BitflagU32,
|
ball_radius: t f32,
ball_velocity: t f32,
ball_time: t f32,
ball_weight: t f32,
ball_color: t Color,
ball_layer: t Layer,
ball_vel_snd_coef: t f32,
ball_vel_snd: t usize,
laser_group: t BitflagU32,
laser_mask: t BitflagU32,
laser_killer_mask: t BitflagU32,
laser_kill_snd: t usize,
laser_radius: t f32,
laser_color: t Color,
laser_layer: t Layer,
laser_persistent_snd: t usize,
column_group: t BitflagU32,
column_mask: t BitflagU32,
column_radius: t f32,
column_color: t Color,
column_layer: t Layer,
column_cooldown: t f32,
column_spawn_snd: t usize,
char_group: t BitflagU32,
char_mask: t BitflagU32,
char_radius: t f32,
char_velocity: t f32,
char_time: t f32,
char_weight: t f32,
char_color: t Color,
char_layer: t Layer,
char_die_snd: t usize,
char_restart: t f32,
wall_group: t BitflagU32,
wall_mask: t BitflagU32,
wall_radius: t f32,
wall_color: t Color,
wall_layer: t Layer,
monster_vision_mask: t BitflagU32,
monster_killer_mask: t BitflagU32,
monster_kill_snd: t usize,
monster_die_snd: t usize,
monster_group: t BitflagU32,
monster_mask: t BitflagU32,
monster_vision_time: t f32,
monster_radius: t f32,
monster_velocity: t f32,
monster_time: t f32,
monster_weight: t f32,
monster_color: t Color,
monster_layer: t Layer,
monster_persistent_snd: t usize,
portal_end_color: t Color,
portal_end_layer: t Layer,
portal_start_color: t Color,
portal_start_layer: t Layer,
portal_snd: t usize,
},
levels: {
hall_length: t usize,
corridor_length: t usize,
dir: t VecStringPath,
entry_music: t VecStringPath,
check_level: e String [always,debug,never],
empty_col: t Array3U8,
char_col: t Array3U8,
portal_col: t Array3U8,
laser_col: t Array3U8,
monster_col: t Array3U8,
column_col: t Array3U8,
wall_col: t Array3U8,
},
audio: {
effect_dir: t VecStringPath,
music_dir: t VecStringPath,
global_volume: t f32 save global_volume,
music_volume: t f32 save music_volume,
effect_volume: t f32 save effect_volume,
distance_model: e String [linear,pow2],
distance_model_min: t f32,
distance_model_max: t f32,
short_effects: t VecVecStringPath,
persistent_effects: t VecVecStringPath,
transition_type: e String [instant,smooth,overlap],
transition_time: t u64,
},
window: {
dimension: t Dimension,
vsync: t bool,
multisampling: t u16,
fullscreen: t bool,
fullscreen_on_primary_monitor: t bool,
fullscreen_monitor: t usize,
},
graphics: {
base03: t Array4F32,
base02: t Array4F32,
base01: t Array4F32,
base00: t Array4F32,
base0: t Array4F32,
base1: t Array4F32,
base2: t Array4F32,
base3: t Array4F32,
yellow: t Array4F32,
orange: t Array4F32,
red: t Array4F32,
magenta: t Array4F32,
violet: t Array4F32,
blue: t Array4F32,
cyan: t Array4F32,
green: t Array4F32,
mode: e String [light,dark] save mode,
luminosity: t f32 save luminosity,
circle_precision: t usize,
font_file: t VecStringPath,
billboard_font_scale: t f32,
font_scale: t f32,
},
text: {
top: t i32,
bottom: t i32,
right: t i32,
left: t i32,
},
camera: {
zoom: t f32,
},
event_loop: {
ups: t u64,
max_fps: t u64,
},
);
|
ball_mask: t BitflagU32,
ball_killer_mask: t BitflagU32,
ball_kill_snd: t usize,
ball_die_snd: t usize,
|
random_line_split
|
shootout-binarytrees.rs
|
// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#![feature(rustc_private, core, step_by)]
extern crate arena;
use std::thread;
use arena::TypedArena;
struct Tree<'a> {
l: Option<&'a Tree<'a>>,
r: Option<&'a Tree<'a>>,
i: i32
}
fn item_check(t: &Option<&Tree>) -> i32 {
match *t {
None => 0,
Some(&Tree { ref l, ref r, i }) => i + item_check(l) - item_check(r)
}
}
fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: i32, depth: i32)
-> Option<&'r Tree<'r>> {
if depth > 0 {
let t: &Tree<'r> = arena.alloc(Tree {
l: bottom_up_tree(arena, 2 * item - 1, depth - 1),
r: bottom_up_tree(arena, 2 * item, depth - 1),
i: item
});
Some(t)
} else {
None
}
}
fn
|
(depth: i32, iterations: i32) -> String {
let mut chk = 0;
for i in 1.. iterations + 1 {
let arena = TypedArena::new();
let a = bottom_up_tree(&arena, i, depth);
let b = bottom_up_tree(&arena, -i, depth);
chk += item_check(&a) + item_check(&b);
}
format!("{}\t trees of depth {}\t check: {}",
iterations * 2, depth, chk)
}
fn main() {
let mut args = std::env::args();
let n = if std::env::var_os("RUST_BENCH").is_some() {
17
} else if args.len() <= 1 {
8
} else {
args.nth(1).unwrap().parse().unwrap()
};
let min_depth = 4;
let max_depth = if min_depth + 2 > n {min_depth + 2} else {n};
{
let arena = TypedArena::new();
let depth = max_depth + 1;
let tree = bottom_up_tree(&arena, 0, depth);
println!("stretch tree of depth {}\t check: {}",
depth, item_check(&tree));
}
let long_lived_arena = TypedArena::new();
let long_lived_tree = bottom_up_tree(&long_lived_arena, 0, max_depth);
let messages = (min_depth..max_depth + 1).step_by(2).map(|depth| {
let iterations = 2i32.pow((max_depth - depth + min_depth) as u32);
thread::spawn(move || inner(depth, iterations))
}).collect::<Vec<_>>();
for message in messages {
println!("{}", message.join().unwrap());
}
println!("long lived tree of depth {}\t check: {}",
max_depth, item_check(&long_lived_tree));
}
|
inner
|
identifier_name
|
shootout-binarytrees.rs
|
// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#![feature(rustc_private, core, step_by)]
extern crate arena;
use std::thread;
use arena::TypedArena;
struct Tree<'a> {
l: Option<&'a Tree<'a>>,
r: Option<&'a Tree<'a>>,
i: i32
}
fn item_check(t: &Option<&Tree>) -> i32 {
match *t {
None => 0,
Some(&Tree { ref l, ref r, i }) => i + item_check(l) - item_check(r)
}
}
fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: i32, depth: i32)
-> Option<&'r Tree<'r>> {
if depth > 0 {
let t: &Tree<'r> = arena.alloc(Tree {
l: bottom_up_tree(arena, 2 * item - 1, depth - 1),
r: bottom_up_tree(arena, 2 * item, depth - 1),
i: item
});
Some(t)
} else {
None
}
}
fn inner(depth: i32, iterations: i32) -> String {
let mut chk = 0;
for i in 1.. iterations + 1 {
let arena = TypedArena::new();
let a = bottom_up_tree(&arena, i, depth);
let b = bottom_up_tree(&arena, -i, depth);
chk += item_check(&a) + item_check(&b);
}
format!("{}\t trees of depth {}\t check: {}",
iterations * 2, depth, chk)
}
fn main()
|
let long_lived_arena = TypedArena::new();
let long_lived_tree = bottom_up_tree(&long_lived_arena, 0, max_depth);
let messages = (min_depth..max_depth + 1).step_by(2).map(|depth| {
let iterations = 2i32.pow((max_depth - depth + min_depth) as u32);
thread::spawn(move || inner(depth, iterations))
}).collect::<Vec<_>>();
for message in messages {
println!("{}", message.join().unwrap());
}
println!("long lived tree of depth {}\t check: {}",
max_depth, item_check(&long_lived_tree));
}
|
{
let mut args = std::env::args();
let n = if std::env::var_os("RUST_BENCH").is_some() {
17
} else if args.len() <= 1 {
8
} else {
args.nth(1).unwrap().parse().unwrap()
};
let min_depth = 4;
let max_depth = if min_depth + 2 > n {min_depth + 2} else {n};
{
let arena = TypedArena::new();
let depth = max_depth + 1;
let tree = bottom_up_tree(&arena, 0, depth);
println!("stretch tree of depth {}\t check: {}",
depth, item_check(&tree));
}
|
identifier_body
|
shootout-binarytrees.rs
|
// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#![feature(rustc_private, core, step_by)]
extern crate arena;
use std::thread;
use arena::TypedArena;
struct Tree<'a> {
l: Option<&'a Tree<'a>>,
r: Option<&'a Tree<'a>>,
i: i32
}
fn item_check(t: &Option<&Tree>) -> i32 {
match *t {
None => 0,
Some(&Tree { ref l, ref r, i }) => i + item_check(l) - item_check(r)
}
}
fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: i32, depth: i32)
-> Option<&'r Tree<'r>> {
if depth > 0 {
let t: &Tree<'r> = arena.alloc(Tree {
l: bottom_up_tree(arena, 2 * item - 1, depth - 1),
r: bottom_up_tree(arena, 2 * item, depth - 1),
i: item
});
Some(t)
} else {
None
}
}
fn inner(depth: i32, iterations: i32) -> String {
let mut chk = 0;
for i in 1.. iterations + 1 {
let arena = TypedArena::new();
let a = bottom_up_tree(&arena, i, depth);
let b = bottom_up_tree(&arena, -i, depth);
chk += item_check(&a) + item_check(&b);
}
format!("{}\t trees of depth {}\t check: {}",
|
fn main() {
let mut args = std::env::args();
let n = if std::env::var_os("RUST_BENCH").is_some() {
17
} else if args.len() <= 1 {
8
} else {
args.nth(1).unwrap().parse().unwrap()
};
let min_depth = 4;
let max_depth = if min_depth + 2 > n {min_depth + 2} else {n};
{
let arena = TypedArena::new();
let depth = max_depth + 1;
let tree = bottom_up_tree(&arena, 0, depth);
println!("stretch tree of depth {}\t check: {}",
depth, item_check(&tree));
}
let long_lived_arena = TypedArena::new();
let long_lived_tree = bottom_up_tree(&long_lived_arena, 0, max_depth);
let messages = (min_depth..max_depth + 1).step_by(2).map(|depth| {
let iterations = 2i32.pow((max_depth - depth + min_depth) as u32);
thread::spawn(move || inner(depth, iterations))
}).collect::<Vec<_>>();
for message in messages {
println!("{}", message.join().unwrap());
}
println!("long lived tree of depth {}\t check: {}",
max_depth, item_check(&long_lived_tree));
}
|
iterations * 2, depth, chk)
}
|
random_line_split
|
shootout-binarytrees.rs
|
// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#![feature(rustc_private, core, step_by)]
extern crate arena;
use std::thread;
use arena::TypedArena;
struct Tree<'a> {
l: Option<&'a Tree<'a>>,
r: Option<&'a Tree<'a>>,
i: i32
}
fn item_check(t: &Option<&Tree>) -> i32 {
match *t {
None => 0,
Some(&Tree { ref l, ref r, i }) => i + item_check(l) - item_check(r)
}
}
fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: i32, depth: i32)
-> Option<&'r Tree<'r>> {
if depth > 0 {
let t: &Tree<'r> = arena.alloc(Tree {
l: bottom_up_tree(arena, 2 * item - 1, depth - 1),
r: bottom_up_tree(arena, 2 * item, depth - 1),
i: item
});
Some(t)
} else {
None
}
}
fn inner(depth: i32, iterations: i32) -> String {
let mut chk = 0;
for i in 1.. iterations + 1 {
let arena = TypedArena::new();
let a = bottom_up_tree(&arena, i, depth);
let b = bottom_up_tree(&arena, -i, depth);
chk += item_check(&a) + item_check(&b);
}
format!("{}\t trees of depth {}\t check: {}",
iterations * 2, depth, chk)
}
fn main() {
let mut args = std::env::args();
let n = if std::env::var_os("RUST_BENCH").is_some() {
17
} else if args.len() <= 1 {
8
} else {
args.nth(1).unwrap().parse().unwrap()
};
let min_depth = 4;
let max_depth = if min_depth + 2 > n
|
else {n};
{
let arena = TypedArena::new();
let depth = max_depth + 1;
let tree = bottom_up_tree(&arena, 0, depth);
println!("stretch tree of depth {}\t check: {}",
depth, item_check(&tree));
}
let long_lived_arena = TypedArena::new();
let long_lived_tree = bottom_up_tree(&long_lived_arena, 0, max_depth);
let messages = (min_depth..max_depth + 1).step_by(2).map(|depth| {
let iterations = 2i32.pow((max_depth - depth + min_depth) as u32);
thread::spawn(move || inner(depth, iterations))
}).collect::<Vec<_>>();
for message in messages {
println!("{}", message.join().unwrap());
}
println!("long lived tree of depth {}\t check: {}",
max_depth, item_check(&long_lived_tree));
}
|
{min_depth + 2}
|
conditional_block
|
client.rs
|
use std::io;
use std::sync::Arc;
use std::time::Duration;
use futures::{future, Future};
use futures_cpupool::CpuPool;
use num_cpus;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_middleware::Timeout;
use tokio_proto::multiplex::ClientService;
use tokio_proto::TcpClient;
use tokio_service::Service;
use tokio_timer::Timer;
use super::STANDALONE_ADDRESS;
use bifrost_hasher::hash_str;
use tcp::proto::BytesClientProto;
use tcp::shortcut;
use DISABLE_SHORTCUT;
pub type ResFuture = Future<Item = Vec<u8>, Error = io::Error>;
lazy_static! {
pub static ref CONNECTING_POOL: CpuPool = CpuPool::new_num_cpus();
}
pub struct ClientCore {
inner: ClientService<TcpStream, BytesClientProto>,
}
pub struct Client {
client: Option<Timeout<ClientCore>>,
pub server_id: u64,
}
impl Service for ClientCore {
type Request = Vec<u8>;
type Response = Vec<u8>;
type Error = io::Error;
// Again for simplicity, we are just going to box a future
type Future = Box<Future<Item = Self::Response, Error = io::Error>>;
fn call(&self, req: Self::Request) -> Self::Future {
Box::new(self.inner.call(req))
}
}
impl Client {
pub fn connect_with_timeout(address: &String, timeout: Duration) -> io::Result<Client> {
let server_id = hash_str(address);
let client = {
if!DISABLE_SHORTCUT && shortcut::is_local(server_id) {
None
} else {
if address.eq(&STANDALONE_ADDRESS) {
return Err(io::Error::new(
io::ErrorKind::Other,
"STANDALONE server is not found",
));
}
let mut core = Core::new()?;
let socket_address = address.parse().unwrap();
let future = Box::new(
TcpClient::new(BytesClientProto)
.connect(&socket_address, &core.handle())
.map(|c| Timeout::new(ClientCore { inner: c }, Timer::default(), timeout)),
);
Some(core.run(future)?) // this is required, or client won't receive response
}
};
Ok(Client { client, server_id })
}
pub fn connect(address: &String) -> io::Result<Client> {
Client::connect_with_timeout(address, Duration::from_secs(5))
}
pub fn
|
(
address: String,
timeout: Duration,
) -> impl Future<Item = Client, Error = io::Error> {
CONNECTING_POOL.spawn_fn(move || Client::connect_with_timeout(&address, timeout))
}
pub fn connect_async(address: String) -> impl Future<Item = Client, Error = io::Error> {
CONNECTING_POOL
.spawn_fn(move || Client::connect_with_timeout(&address, Duration::from_secs(5)))
}
pub fn send_async(&self, msg: Vec<u8>) -> Box<ResFuture> {
if let Some(ref client) = self.client {
box client.call(msg)
} else {
shortcut::call(self.server_id, msg)
}
}
}
unsafe impl Send for Client {}
|
connect_with_timeout_async
|
identifier_name
|
client.rs
|
use std::io;
use std::sync::Arc;
use std::time::Duration;
use futures::{future, Future};
use futures_cpupool::CpuPool;
use num_cpus;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_middleware::Timeout;
use tokio_proto::multiplex::ClientService;
use tokio_proto::TcpClient;
use tokio_service::Service;
use tokio_timer::Timer;
use super::STANDALONE_ADDRESS;
use bifrost_hasher::hash_str;
use tcp::proto::BytesClientProto;
use tcp::shortcut;
use DISABLE_SHORTCUT;
pub type ResFuture = Future<Item = Vec<u8>, Error = io::Error>;
lazy_static! {
pub static ref CONNECTING_POOL: CpuPool = CpuPool::new_num_cpus();
}
pub struct ClientCore {
inner: ClientService<TcpStream, BytesClientProto>,
}
pub struct Client {
client: Option<Timeout<ClientCore>>,
pub server_id: u64,
}
impl Service for ClientCore {
type Request = Vec<u8>;
type Response = Vec<u8>;
type Error = io::Error;
// Again for simplicity, we are just going to box a future
type Future = Box<Future<Item = Self::Response, Error = io::Error>>;
fn call(&self, req: Self::Request) -> Self::Future {
Box::new(self.inner.call(req))
}
}
impl Client {
pub fn connect_with_timeout(address: &String, timeout: Duration) -> io::Result<Client> {
let server_id = hash_str(address);
let client = {
if!DISABLE_SHORTCUT && shortcut::is_local(server_id) {
None
} else {
if address.eq(&STANDALONE_ADDRESS) {
return Err(io::Error::new(
io::ErrorKind::Other,
"STANDALONE server is not found",
));
}
let mut core = Core::new()?;
let socket_address = address.parse().unwrap();
let future = Box::new(
TcpClient::new(BytesClientProto)
.connect(&socket_address, &core.handle())
.map(|c| Timeout::new(ClientCore { inner: c }, Timer::default(), timeout)),
);
Some(core.run(future)?) // this is required, or client won't receive response
}
};
Ok(Client { client, server_id })
}
pub fn connect(address: &String) -> io::Result<Client> {
Client::connect_with_timeout(address, Duration::from_secs(5))
}
pub fn connect_with_timeout_async(
address: String,
timeout: Duration,
) -> impl Future<Item = Client, Error = io::Error> {
CONNECTING_POOL.spawn_fn(move || Client::connect_with_timeout(&address, timeout))
}
pub fn connect_async(address: String) -> impl Future<Item = Client, Error = io::Error>
|
pub fn send_async(&self, msg: Vec<u8>) -> Box<ResFuture> {
if let Some(ref client) = self.client {
box client.call(msg)
} else {
shortcut::call(self.server_id, msg)
}
}
}
unsafe impl Send for Client {}
|
{
CONNECTING_POOL
.spawn_fn(move || Client::connect_with_timeout(&address, Duration::from_secs(5)))
}
|
identifier_body
|
client.rs
|
use std::io;
use std::sync::Arc;
use std::time::Duration;
use futures::{future, Future};
use futures_cpupool::CpuPool;
use num_cpus;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_middleware::Timeout;
use tokio_proto::multiplex::ClientService;
use tokio_proto::TcpClient;
use tokio_service::Service;
use tokio_timer::Timer;
use super::STANDALONE_ADDRESS;
use bifrost_hasher::hash_str;
use tcp::proto::BytesClientProto;
use tcp::shortcut;
use DISABLE_SHORTCUT;
pub type ResFuture = Future<Item = Vec<u8>, Error = io::Error>;
lazy_static! {
pub static ref CONNECTING_POOL: CpuPool = CpuPool::new_num_cpus();
}
pub struct ClientCore {
inner: ClientService<TcpStream, BytesClientProto>,
}
pub struct Client {
client: Option<Timeout<ClientCore>>,
pub server_id: u64,
}
impl Service for ClientCore {
type Request = Vec<u8>;
type Response = Vec<u8>;
type Error = io::Error;
// Again for simplicity, we are just going to box a future
type Future = Box<Future<Item = Self::Response, Error = io::Error>>;
fn call(&self, req: Self::Request) -> Self::Future {
Box::new(self.inner.call(req))
}
}
impl Client {
pub fn connect_with_timeout(address: &String, timeout: Duration) -> io::Result<Client> {
|
if!DISABLE_SHORTCUT && shortcut::is_local(server_id) {
None
} else {
if address.eq(&STANDALONE_ADDRESS) {
return Err(io::Error::new(
io::ErrorKind::Other,
"STANDALONE server is not found",
));
}
let mut core = Core::new()?;
let socket_address = address.parse().unwrap();
let future = Box::new(
TcpClient::new(BytesClientProto)
.connect(&socket_address, &core.handle())
.map(|c| Timeout::new(ClientCore { inner: c }, Timer::default(), timeout)),
);
Some(core.run(future)?) // this is required, or client won't receive response
}
};
Ok(Client { client, server_id })
}
pub fn connect(address: &String) -> io::Result<Client> {
Client::connect_with_timeout(address, Duration::from_secs(5))
}
pub fn connect_with_timeout_async(
address: String,
timeout: Duration,
) -> impl Future<Item = Client, Error = io::Error> {
CONNECTING_POOL.spawn_fn(move || Client::connect_with_timeout(&address, timeout))
}
pub fn connect_async(address: String) -> impl Future<Item = Client, Error = io::Error> {
CONNECTING_POOL
.spawn_fn(move || Client::connect_with_timeout(&address, Duration::from_secs(5)))
}
pub fn send_async(&self, msg: Vec<u8>) -> Box<ResFuture> {
if let Some(ref client) = self.client {
box client.call(msg)
} else {
shortcut::call(self.server_id, msg)
}
}
}
unsafe impl Send for Client {}
|
let server_id = hash_str(address);
let client = {
|
random_line_split
|
client.rs
|
use std::io;
use std::sync::Arc;
use std::time::Duration;
use futures::{future, Future};
use futures_cpupool::CpuPool;
use num_cpus;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_middleware::Timeout;
use tokio_proto::multiplex::ClientService;
use tokio_proto::TcpClient;
use tokio_service::Service;
use tokio_timer::Timer;
use super::STANDALONE_ADDRESS;
use bifrost_hasher::hash_str;
use tcp::proto::BytesClientProto;
use tcp::shortcut;
use DISABLE_SHORTCUT;
pub type ResFuture = Future<Item = Vec<u8>, Error = io::Error>;
lazy_static! {
pub static ref CONNECTING_POOL: CpuPool = CpuPool::new_num_cpus();
}
pub struct ClientCore {
inner: ClientService<TcpStream, BytesClientProto>,
}
pub struct Client {
client: Option<Timeout<ClientCore>>,
pub server_id: u64,
}
impl Service for ClientCore {
type Request = Vec<u8>;
type Response = Vec<u8>;
type Error = io::Error;
// Again for simplicity, we are just going to box a future
type Future = Box<Future<Item = Self::Response, Error = io::Error>>;
fn call(&self, req: Self::Request) -> Self::Future {
Box::new(self.inner.call(req))
}
}
impl Client {
pub fn connect_with_timeout(address: &String, timeout: Duration) -> io::Result<Client> {
let server_id = hash_str(address);
let client = {
if!DISABLE_SHORTCUT && shortcut::is_local(server_id) {
None
} else
|
};
Ok(Client { client, server_id })
}
pub fn connect(address: &String) -> io::Result<Client> {
Client::connect_with_timeout(address, Duration::from_secs(5))
}
pub fn connect_with_timeout_async(
address: String,
timeout: Duration,
) -> impl Future<Item = Client, Error = io::Error> {
CONNECTING_POOL.spawn_fn(move || Client::connect_with_timeout(&address, timeout))
}
pub fn connect_async(address: String) -> impl Future<Item = Client, Error = io::Error> {
CONNECTING_POOL
.spawn_fn(move || Client::connect_with_timeout(&address, Duration::from_secs(5)))
}
pub fn send_async(&self, msg: Vec<u8>) -> Box<ResFuture> {
if let Some(ref client) = self.client {
box client.call(msg)
} else {
shortcut::call(self.server_id, msg)
}
}
}
unsafe impl Send for Client {}
|
{
if address.eq(&STANDALONE_ADDRESS) {
return Err(io::Error::new(
io::ErrorKind::Other,
"STANDALONE server is not found",
));
}
let mut core = Core::new()?;
let socket_address = address.parse().unwrap();
let future = Box::new(
TcpClient::new(BytesClientProto)
.connect(&socket_address, &core.handle())
.map(|c| Timeout::new(ClientCore { inner: c }, Timer::default(), timeout)),
);
Some(core.run(future)?) // this is required, or client won't receive response
}
|
conditional_block
|
inprocess.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::webgl_thread::{WebGLThread, WebGLThreadInit, WebXRBridgeInit};
use canvas_traits::webgl::webgl_channel;
use canvas_traits::webgl::{WebGLContextId, WebGLMsg, WebGLThreads};
use euclid::default::Size2D;
use fnv::FnvHashMap;
use gleam;
use servo_config::pref;
use sparkle::gl;
use sparkle::gl::GlType;
use std::default::Default;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use surfman::Device;
use surfman::SurfaceInfo;
use surfman::SurfaceTexture;
use surfman_chains::SwapChains;
use surfman_chains_api::SwapChainAPI;
use surfman_chains_api::SwapChainsAPI;
use webrender_surfman::WebrenderSurfman;
use webrender_traits::{
WebrenderExternalImageApi, WebrenderExternalImageRegistry, WebrenderImageSource,
};
use webxr::SurfmanGL as WebXRSurfman;
use webxr_api::LayerGrandManager as WebXRLayerGrandManager;
pub struct WebGLComm {
pub webgl_threads: WebGLThreads,
pub image_handler: Box<dyn WebrenderExternalImageApi>,
pub output_handler: Option<Box<dyn webrender_api::OutputImageHandler>>,
pub webxr_layer_grand_manager: WebXRLayerGrandManager<WebXRSurfman>,
}
impl WebGLComm {
/// Creates a new `WebGLComm` object.
pub fn new(
surfman: WebrenderSurfman,
webrender_gl: Rc<dyn gleam::gl::Gl>,
webrender_api_sender: webrender_api::RenderApiSender,
webrender_doc: webrender_api::DocumentId,
external_images: Arc<Mutex<WebrenderExternalImageRegistry>>,
api_type: GlType,
) -> WebGLComm {
debug!("WebGLThreads::new()");
let (sender, receiver) = webgl_channel::<WebGLMsg>().unwrap();
let webrender_swap_chains = SwapChains::new();
let webxr_init = WebXRBridgeInit::new(sender.clone());
let webxr_layer_grand_manager = webxr_init.layer_grand_manager();
// This implementation creates a single `WebGLThread` for all the pipelines.
let init = WebGLThreadInit {
webrender_api_sender,
webrender_doc,
external_images,
sender: sender.clone(),
receiver,
webrender_swap_chains: webrender_swap_chains.clone(),
connection: surfman.connection(),
adapter: surfman.adapter(),
api_type,
webxr_init,
};
let output_handler = if pref!(dom.webgl.dom_to_texture.enabled) {
Some(Box::new(OutputHandler::new(webrender_gl.clone())))
} else {
None
};
let external = WebGLExternalImages::new(surfman, webrender_swap_chains);
WebGLThread::run_on_own_thread(init);
WebGLComm {
webgl_threads: WebGLThreads(sender),
image_handler: Box::new(external),
output_handler: output_handler.map(|b| b as Box<_>),
webxr_layer_grand_manager: webxr_layer_grand_manager,
}
}
}
/// Bridge between the webrender::ExternalImage callbacks and the WebGLThreads.
struct WebGLExternalImages {
surfman: WebrenderSurfman,
swap_chains: SwapChains<WebGLContextId, Device>,
locked_front_buffers: FnvHashMap<WebGLContextId, SurfaceTexture>,
}
impl WebGLExternalImages {
fn new(surfman: WebrenderSurfman, swap_chains: SwapChains<WebGLContextId, Device>) -> Self {
Self {
surfman,
swap_chains,
locked_front_buffers: FnvHashMap::default(),
}
}
fn lock_swap_chain(&mut self, id: WebGLContextId) -> Option<(u32, Size2D<i32>)> {
debug!("... locking chain {:?}", id);
let front_buffer = self.swap_chains.get(id)?.take_surface()?;
let SurfaceInfo {
id: front_buffer_id,
size,
..
} = self.surfman.surface_info(&front_buffer);
debug!("... getting texture for surface {:?}", front_buffer_id);
let front_buffer_texture = self.surfman.create_surface_texture(front_buffer).unwrap();
let gl_texture = self.surfman.surface_texture_object(&front_buffer_texture);
self.locked_front_buffers.insert(id, front_buffer_texture);
Some((gl_texture, size))
}
fn unlock_swap_chain(&mut self, id: WebGLContextId) -> Option<()> {
let locked_front_buffer = self.locked_front_buffers.remove(&id)?;
let locked_front_buffer = self
.surfman
.destroy_surface_texture(locked_front_buffer)
.unwrap();
debug!("... unlocked chain {:?}", id);
self.swap_chains
.get(id)?
.recycle_surface(locked_front_buffer);
Some(())
}
}
impl WebrenderExternalImageApi for WebGLExternalImages {
fn lock(&mut self, id: u64) -> (WebrenderImageSource, Size2D<i32>) {
let id = WebGLContextId(id);
let (texture_id, size) = self.lock_swap_chain(id).unwrap_or_default();
(WebrenderImageSource::TextureHandle(texture_id), size)
}
fn unlock(&mut self, id: u64) {
let id = WebGLContextId(id);
self.unlock_swap_chain(id);
}
}
/// struct used to implement DOMToTexture feature and webrender::OutputImageHandler trait.
struct OutputHandler {
webrender_gl: Rc<dyn gleam::gl::Gl>,
sync_objects: FnvHashMap<webrender_api::PipelineId, gleam::gl::GLsync>,
}
impl OutputHandler {
fn new(webrender_gl: Rc<dyn gleam::gl::Gl>) -> Self {
OutputHandler {
webrender_gl,
sync_objects: Default::default(),
}
}
}
/// Bridge between the WR frame outputs and WebGL to implement DOMToTexture synchronization.
impl webrender_api::OutputImageHandler for OutputHandler {
fn lock(
&mut self,
id: webrender_api::PipelineId,
) -> Option<(u32, webrender_api::units::FramebufferIntSize)> {
// Insert a fence in the WR command queue
let gl_sync = self
.webrender_gl
.fence_sync(gl::SYNC_GPU_COMMANDS_COMPLETE, 0);
self.sync_objects.insert(id, gl_sync);
// https://github.com/servo/servo/issues/24615
None
}
fn unlock(&mut self, id: webrender_api::PipelineId) {
if let Some(gl_sync) = self.sync_objects.remove(&id)
|
}
}
|
{
// Flush the Sync object into the GPU's command queue to guarantee that it it's signaled.
self.webrender_gl.flush();
// Mark the sync object for deletion.
self.webrender_gl.delete_sync(gl_sync);
}
|
conditional_block
|
inprocess.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::webgl_thread::{WebGLThread, WebGLThreadInit, WebXRBridgeInit};
use canvas_traits::webgl::webgl_channel;
use canvas_traits::webgl::{WebGLContextId, WebGLMsg, WebGLThreads};
use euclid::default::Size2D;
use fnv::FnvHashMap;
use gleam;
use servo_config::pref;
use sparkle::gl;
use sparkle::gl::GlType;
use std::default::Default;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use surfman::Device;
use surfman::SurfaceInfo;
use surfman::SurfaceTexture;
use surfman_chains::SwapChains;
use surfman_chains_api::SwapChainAPI;
use surfman_chains_api::SwapChainsAPI;
use webrender_surfman::WebrenderSurfman;
use webrender_traits::{
WebrenderExternalImageApi, WebrenderExternalImageRegistry, WebrenderImageSource,
};
use webxr::SurfmanGL as WebXRSurfman;
use webxr_api::LayerGrandManager as WebXRLayerGrandManager;
pub struct
|
{
pub webgl_threads: WebGLThreads,
pub image_handler: Box<dyn WebrenderExternalImageApi>,
pub output_handler: Option<Box<dyn webrender_api::OutputImageHandler>>,
pub webxr_layer_grand_manager: WebXRLayerGrandManager<WebXRSurfman>,
}
impl WebGLComm {
/// Creates a new `WebGLComm` object.
pub fn new(
surfman: WebrenderSurfman,
webrender_gl: Rc<dyn gleam::gl::Gl>,
webrender_api_sender: webrender_api::RenderApiSender,
webrender_doc: webrender_api::DocumentId,
external_images: Arc<Mutex<WebrenderExternalImageRegistry>>,
api_type: GlType,
) -> WebGLComm {
debug!("WebGLThreads::new()");
let (sender, receiver) = webgl_channel::<WebGLMsg>().unwrap();
let webrender_swap_chains = SwapChains::new();
let webxr_init = WebXRBridgeInit::new(sender.clone());
let webxr_layer_grand_manager = webxr_init.layer_grand_manager();
// This implementation creates a single `WebGLThread` for all the pipelines.
let init = WebGLThreadInit {
webrender_api_sender,
webrender_doc,
external_images,
sender: sender.clone(),
receiver,
webrender_swap_chains: webrender_swap_chains.clone(),
connection: surfman.connection(),
adapter: surfman.adapter(),
api_type,
webxr_init,
};
let output_handler = if pref!(dom.webgl.dom_to_texture.enabled) {
Some(Box::new(OutputHandler::new(webrender_gl.clone())))
} else {
None
};
let external = WebGLExternalImages::new(surfman, webrender_swap_chains);
WebGLThread::run_on_own_thread(init);
WebGLComm {
webgl_threads: WebGLThreads(sender),
image_handler: Box::new(external),
output_handler: output_handler.map(|b| b as Box<_>),
webxr_layer_grand_manager: webxr_layer_grand_manager,
}
}
}
/// Bridge between the webrender::ExternalImage callbacks and the WebGLThreads.
struct WebGLExternalImages {
surfman: WebrenderSurfman,
swap_chains: SwapChains<WebGLContextId, Device>,
locked_front_buffers: FnvHashMap<WebGLContextId, SurfaceTexture>,
}
impl WebGLExternalImages {
fn new(surfman: WebrenderSurfman, swap_chains: SwapChains<WebGLContextId, Device>) -> Self {
Self {
surfman,
swap_chains,
locked_front_buffers: FnvHashMap::default(),
}
}
fn lock_swap_chain(&mut self, id: WebGLContextId) -> Option<(u32, Size2D<i32>)> {
debug!("... locking chain {:?}", id);
let front_buffer = self.swap_chains.get(id)?.take_surface()?;
let SurfaceInfo {
id: front_buffer_id,
size,
..
} = self.surfman.surface_info(&front_buffer);
debug!("... getting texture for surface {:?}", front_buffer_id);
let front_buffer_texture = self.surfman.create_surface_texture(front_buffer).unwrap();
let gl_texture = self.surfman.surface_texture_object(&front_buffer_texture);
self.locked_front_buffers.insert(id, front_buffer_texture);
Some((gl_texture, size))
}
fn unlock_swap_chain(&mut self, id: WebGLContextId) -> Option<()> {
let locked_front_buffer = self.locked_front_buffers.remove(&id)?;
let locked_front_buffer = self
.surfman
.destroy_surface_texture(locked_front_buffer)
.unwrap();
debug!("... unlocked chain {:?}", id);
self.swap_chains
.get(id)?
.recycle_surface(locked_front_buffer);
Some(())
}
}
impl WebrenderExternalImageApi for WebGLExternalImages {
fn lock(&mut self, id: u64) -> (WebrenderImageSource, Size2D<i32>) {
let id = WebGLContextId(id);
let (texture_id, size) = self.lock_swap_chain(id).unwrap_or_default();
(WebrenderImageSource::TextureHandle(texture_id), size)
}
fn unlock(&mut self, id: u64) {
let id = WebGLContextId(id);
self.unlock_swap_chain(id);
}
}
/// struct used to implement DOMToTexture feature and webrender::OutputImageHandler trait.
struct OutputHandler {
webrender_gl: Rc<dyn gleam::gl::Gl>,
sync_objects: FnvHashMap<webrender_api::PipelineId, gleam::gl::GLsync>,
}
impl OutputHandler {
fn new(webrender_gl: Rc<dyn gleam::gl::Gl>) -> Self {
OutputHandler {
webrender_gl,
sync_objects: Default::default(),
}
}
}
/// Bridge between the WR frame outputs and WebGL to implement DOMToTexture synchronization.
impl webrender_api::OutputImageHandler for OutputHandler {
fn lock(
&mut self,
id: webrender_api::PipelineId,
) -> Option<(u32, webrender_api::units::FramebufferIntSize)> {
// Insert a fence in the WR command queue
let gl_sync = self
.webrender_gl
.fence_sync(gl::SYNC_GPU_COMMANDS_COMPLETE, 0);
self.sync_objects.insert(id, gl_sync);
// https://github.com/servo/servo/issues/24615
None
}
fn unlock(&mut self, id: webrender_api::PipelineId) {
if let Some(gl_sync) = self.sync_objects.remove(&id) {
// Flush the Sync object into the GPU's command queue to guarantee that it it's signaled.
self.webrender_gl.flush();
// Mark the sync object for deletion.
self.webrender_gl.delete_sync(gl_sync);
}
}
}
|
WebGLComm
|
identifier_name
|
inprocess.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::webgl_thread::{WebGLThread, WebGLThreadInit, WebXRBridgeInit};
use canvas_traits::webgl::webgl_channel;
use canvas_traits::webgl::{WebGLContextId, WebGLMsg, WebGLThreads};
use euclid::default::Size2D;
use fnv::FnvHashMap;
use gleam;
use servo_config::pref;
use sparkle::gl;
use sparkle::gl::GlType;
use std::default::Default;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use surfman::Device;
use surfman::SurfaceInfo;
use surfman::SurfaceTexture;
use surfman_chains::SwapChains;
use surfman_chains_api::SwapChainAPI;
use surfman_chains_api::SwapChainsAPI;
use webrender_surfman::WebrenderSurfman;
use webrender_traits::{
WebrenderExternalImageApi, WebrenderExternalImageRegistry, WebrenderImageSource,
};
use webxr::SurfmanGL as WebXRSurfman;
use webxr_api::LayerGrandManager as WebXRLayerGrandManager;
pub struct WebGLComm {
pub webgl_threads: WebGLThreads,
pub image_handler: Box<dyn WebrenderExternalImageApi>,
pub output_handler: Option<Box<dyn webrender_api::OutputImageHandler>>,
pub webxr_layer_grand_manager: WebXRLayerGrandManager<WebXRSurfman>,
}
impl WebGLComm {
/// Creates a new `WebGLComm` object.
pub fn new(
surfman: WebrenderSurfman,
webrender_gl: Rc<dyn gleam::gl::Gl>,
webrender_api_sender: webrender_api::RenderApiSender,
webrender_doc: webrender_api::DocumentId,
external_images: Arc<Mutex<WebrenderExternalImageRegistry>>,
api_type: GlType,
) -> WebGLComm {
debug!("WebGLThreads::new()");
let (sender, receiver) = webgl_channel::<WebGLMsg>().unwrap();
let webrender_swap_chains = SwapChains::new();
let webxr_init = WebXRBridgeInit::new(sender.clone());
let webxr_layer_grand_manager = webxr_init.layer_grand_manager();
// This implementation creates a single `WebGLThread` for all the pipelines.
let init = WebGLThreadInit {
webrender_api_sender,
webrender_doc,
external_images,
sender: sender.clone(),
receiver,
webrender_swap_chains: webrender_swap_chains.clone(),
connection: surfman.connection(),
adapter: surfman.adapter(),
api_type,
webxr_init,
};
let output_handler = if pref!(dom.webgl.dom_to_texture.enabled) {
Some(Box::new(OutputHandler::new(webrender_gl.clone())))
} else {
None
};
let external = WebGLExternalImages::new(surfman, webrender_swap_chains);
WebGLThread::run_on_own_thread(init);
WebGLComm {
webgl_threads: WebGLThreads(sender),
image_handler: Box::new(external),
output_handler: output_handler.map(|b| b as Box<_>),
webxr_layer_grand_manager: webxr_layer_grand_manager,
}
}
}
/// Bridge between the webrender::ExternalImage callbacks and the WebGLThreads.
struct WebGLExternalImages {
surfman: WebrenderSurfman,
swap_chains: SwapChains<WebGLContextId, Device>,
locked_front_buffers: FnvHashMap<WebGLContextId, SurfaceTexture>,
}
impl WebGLExternalImages {
fn new(surfman: WebrenderSurfman, swap_chains: SwapChains<WebGLContextId, Device>) -> Self {
Self {
surfman,
swap_chains,
locked_front_buffers: FnvHashMap::default(),
}
}
fn lock_swap_chain(&mut self, id: WebGLContextId) -> Option<(u32, Size2D<i32>)>
|
fn unlock_swap_chain(&mut self, id: WebGLContextId) -> Option<()> {
let locked_front_buffer = self.locked_front_buffers.remove(&id)?;
let locked_front_buffer = self
.surfman
.destroy_surface_texture(locked_front_buffer)
.unwrap();
debug!("... unlocked chain {:?}", id);
self.swap_chains
.get(id)?
.recycle_surface(locked_front_buffer);
Some(())
}
}
impl WebrenderExternalImageApi for WebGLExternalImages {
fn lock(&mut self, id: u64) -> (WebrenderImageSource, Size2D<i32>) {
let id = WebGLContextId(id);
let (texture_id, size) = self.lock_swap_chain(id).unwrap_or_default();
(WebrenderImageSource::TextureHandle(texture_id), size)
}
fn unlock(&mut self, id: u64) {
let id = WebGLContextId(id);
self.unlock_swap_chain(id);
}
}
/// struct used to implement DOMToTexture feature and webrender::OutputImageHandler trait.
struct OutputHandler {
webrender_gl: Rc<dyn gleam::gl::Gl>,
sync_objects: FnvHashMap<webrender_api::PipelineId, gleam::gl::GLsync>,
}
impl OutputHandler {
fn new(webrender_gl: Rc<dyn gleam::gl::Gl>) -> Self {
OutputHandler {
webrender_gl,
sync_objects: Default::default(),
}
}
}
/// Bridge between the WR frame outputs and WebGL to implement DOMToTexture synchronization.
impl webrender_api::OutputImageHandler for OutputHandler {
fn lock(
&mut self,
id: webrender_api::PipelineId,
) -> Option<(u32, webrender_api::units::FramebufferIntSize)> {
// Insert a fence in the WR command queue
let gl_sync = self
.webrender_gl
.fence_sync(gl::SYNC_GPU_COMMANDS_COMPLETE, 0);
self.sync_objects.insert(id, gl_sync);
// https://github.com/servo/servo/issues/24615
None
}
fn unlock(&mut self, id: webrender_api::PipelineId) {
if let Some(gl_sync) = self.sync_objects.remove(&id) {
// Flush the Sync object into the GPU's command queue to guarantee that it it's signaled.
self.webrender_gl.flush();
// Mark the sync object for deletion.
self.webrender_gl.delete_sync(gl_sync);
}
}
}
|
{
debug!("... locking chain {:?}", id);
let front_buffer = self.swap_chains.get(id)?.take_surface()?;
let SurfaceInfo {
id: front_buffer_id,
size,
..
} = self.surfman.surface_info(&front_buffer);
debug!("... getting texture for surface {:?}", front_buffer_id);
let front_buffer_texture = self.surfman.create_surface_texture(front_buffer).unwrap();
let gl_texture = self.surfman.surface_texture_object(&front_buffer_texture);
self.locked_front_buffers.insert(id, front_buffer_texture);
Some((gl_texture, size))
}
|
identifier_body
|
inprocess.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::webgl_thread::{WebGLThread, WebGLThreadInit, WebXRBridgeInit};
use canvas_traits::webgl::webgl_channel;
use canvas_traits::webgl::{WebGLContextId, WebGLMsg, WebGLThreads};
use euclid::default::Size2D;
use fnv::FnvHashMap;
use gleam;
use servo_config::pref;
use sparkle::gl;
use sparkle::gl::GlType;
use std::default::Default;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use surfman::Device;
use surfman::SurfaceInfo;
use surfman::SurfaceTexture;
use surfman_chains::SwapChains;
use surfman_chains_api::SwapChainAPI;
use surfman_chains_api::SwapChainsAPI;
use webrender_surfman::WebrenderSurfman;
use webrender_traits::{
WebrenderExternalImageApi, WebrenderExternalImageRegistry, WebrenderImageSource,
};
use webxr::SurfmanGL as WebXRSurfman;
use webxr_api::LayerGrandManager as WebXRLayerGrandManager;
pub struct WebGLComm {
pub webgl_threads: WebGLThreads,
pub image_handler: Box<dyn WebrenderExternalImageApi>,
pub output_handler: Option<Box<dyn webrender_api::OutputImageHandler>>,
pub webxr_layer_grand_manager: WebXRLayerGrandManager<WebXRSurfman>,
}
impl WebGLComm {
/// Creates a new `WebGLComm` object.
pub fn new(
surfman: WebrenderSurfman,
webrender_gl: Rc<dyn gleam::gl::Gl>,
webrender_api_sender: webrender_api::RenderApiSender,
webrender_doc: webrender_api::DocumentId,
external_images: Arc<Mutex<WebrenderExternalImageRegistry>>,
api_type: GlType,
) -> WebGLComm {
debug!("WebGLThreads::new()");
let (sender, receiver) = webgl_channel::<WebGLMsg>().unwrap();
let webrender_swap_chains = SwapChains::new();
let webxr_init = WebXRBridgeInit::new(sender.clone());
let webxr_layer_grand_manager = webxr_init.layer_grand_manager();
// This implementation creates a single `WebGLThread` for all the pipelines.
let init = WebGLThreadInit {
webrender_api_sender,
webrender_doc,
external_images,
sender: sender.clone(),
receiver,
webrender_swap_chains: webrender_swap_chains.clone(),
connection: surfman.connection(),
|
webxr_init,
};
let output_handler = if pref!(dom.webgl.dom_to_texture.enabled) {
Some(Box::new(OutputHandler::new(webrender_gl.clone())))
} else {
None
};
let external = WebGLExternalImages::new(surfman, webrender_swap_chains);
WebGLThread::run_on_own_thread(init);
WebGLComm {
webgl_threads: WebGLThreads(sender),
image_handler: Box::new(external),
output_handler: output_handler.map(|b| b as Box<_>),
webxr_layer_grand_manager: webxr_layer_grand_manager,
}
}
}
/// Bridge between the webrender::ExternalImage callbacks and the WebGLThreads.
struct WebGLExternalImages {
surfman: WebrenderSurfman,
swap_chains: SwapChains<WebGLContextId, Device>,
locked_front_buffers: FnvHashMap<WebGLContextId, SurfaceTexture>,
}
impl WebGLExternalImages {
fn new(surfman: WebrenderSurfman, swap_chains: SwapChains<WebGLContextId, Device>) -> Self {
Self {
surfman,
swap_chains,
locked_front_buffers: FnvHashMap::default(),
}
}
fn lock_swap_chain(&mut self, id: WebGLContextId) -> Option<(u32, Size2D<i32>)> {
debug!("... locking chain {:?}", id);
let front_buffer = self.swap_chains.get(id)?.take_surface()?;
let SurfaceInfo {
id: front_buffer_id,
size,
..
} = self.surfman.surface_info(&front_buffer);
debug!("... getting texture for surface {:?}", front_buffer_id);
let front_buffer_texture = self.surfman.create_surface_texture(front_buffer).unwrap();
let gl_texture = self.surfman.surface_texture_object(&front_buffer_texture);
self.locked_front_buffers.insert(id, front_buffer_texture);
Some((gl_texture, size))
}
fn unlock_swap_chain(&mut self, id: WebGLContextId) -> Option<()> {
let locked_front_buffer = self.locked_front_buffers.remove(&id)?;
let locked_front_buffer = self
.surfman
.destroy_surface_texture(locked_front_buffer)
.unwrap();
debug!("... unlocked chain {:?}", id);
self.swap_chains
.get(id)?
.recycle_surface(locked_front_buffer);
Some(())
}
}
impl WebrenderExternalImageApi for WebGLExternalImages {
fn lock(&mut self, id: u64) -> (WebrenderImageSource, Size2D<i32>) {
let id = WebGLContextId(id);
let (texture_id, size) = self.lock_swap_chain(id).unwrap_or_default();
(WebrenderImageSource::TextureHandle(texture_id), size)
}
fn unlock(&mut self, id: u64) {
let id = WebGLContextId(id);
self.unlock_swap_chain(id);
}
}
/// struct used to implement DOMToTexture feature and webrender::OutputImageHandler trait.
struct OutputHandler {
webrender_gl: Rc<dyn gleam::gl::Gl>,
sync_objects: FnvHashMap<webrender_api::PipelineId, gleam::gl::GLsync>,
}
impl OutputHandler {
fn new(webrender_gl: Rc<dyn gleam::gl::Gl>) -> Self {
OutputHandler {
webrender_gl,
sync_objects: Default::default(),
}
}
}
/// Bridge between the WR frame outputs and WebGL to implement DOMToTexture synchronization.
impl webrender_api::OutputImageHandler for OutputHandler {
fn lock(
&mut self,
id: webrender_api::PipelineId,
) -> Option<(u32, webrender_api::units::FramebufferIntSize)> {
// Insert a fence in the WR command queue
let gl_sync = self
.webrender_gl
.fence_sync(gl::SYNC_GPU_COMMANDS_COMPLETE, 0);
self.sync_objects.insert(id, gl_sync);
// https://github.com/servo/servo/issues/24615
None
}
fn unlock(&mut self, id: webrender_api::PipelineId) {
if let Some(gl_sync) = self.sync_objects.remove(&id) {
// Flush the Sync object into the GPU's command queue to guarantee that it it's signaled.
self.webrender_gl.flush();
// Mark the sync object for deletion.
self.webrender_gl.delete_sync(gl_sync);
}
}
}
|
adapter: surfman.adapter(),
api_type,
|
random_line_split
|
mod.rs
|
use std::ffi::CStr;
use std::mem;
use std::ptr;
use glutin;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
pub struct Context {
gl: gl::Gl
}
pub fn
|
(window: &glutin::Window) -> Context {
let gl = gl::Gl::load_with(|ptr| window.get_proc_address(ptr) as *const _);
let version = unsafe {
let data = CStr::from_ptr(gl.GetString(gl::VERSION) as *const _).to_bytes().to_vec();
String::from_utf8(data).unwrap()
};
println!("OpenGL version {}", version);
unsafe {
let vs = gl.CreateShader(gl::VERTEX_SHADER);
gl.ShaderSource(vs, 1, [VS_SRC.as_ptr() as *const i8].as_ptr(), ptr::null());
gl.CompileShader(vs);
let fs = gl.CreateShader(gl::FRAGMENT_SHADER);
gl.ShaderSource(fs, 1, [FS_SRC.as_ptr() as *const i8].as_ptr(), ptr::null());
gl.CompileShader(fs);
let program = gl.CreateProgram();
gl.AttachShader(program, vs);
gl.AttachShader(program, fs);
gl.LinkProgram(program);
gl.UseProgram(program);
let mut vb = mem::uninitialized();
gl.GenBuffers(1, &mut vb);
gl.BindBuffer(gl::ARRAY_BUFFER, vb);
gl.BufferData(gl::ARRAY_BUFFER,
(VERTEX_DATA.len() * mem::size_of::<f32>()) as gl::types::GLsizeiptr,
VERTEX_DATA.as_ptr() as *const _, gl::STATIC_DRAW);
if gl.BindVertexArray.is_loaded() {
let mut vao = mem::uninitialized();
gl.GenVertexArrays(1, &mut vao);
gl.BindVertexArray(vao);
}
let pos_attrib = gl.GetAttribLocation(program, b"position\0".as_ptr() as *const _);
let color_attrib = gl.GetAttribLocation(program, b"color\0".as_ptr() as *const _);
gl.VertexAttribPointer(pos_attrib as gl::types::GLuint, 2, gl::FLOAT, 0,
5 * mem::size_of::<f32>() as gl::types::GLsizei,
ptr::null());
gl.VertexAttribPointer(color_attrib as gl::types::GLuint, 3, gl::FLOAT, 0,
5 * mem::size_of::<f32>() as gl::types::GLsizei,
(2 * mem::size_of::<f32>()) as *const () as *const _);
gl.EnableVertexAttribArray(pos_attrib as gl::types::GLuint);
gl.EnableVertexAttribArray(color_attrib as gl::types::GLuint);
}
Context { gl: gl }
}
impl Context {
pub fn draw_frame(&self, color: (f32, f32, f32, f32)) {
unsafe {
self.gl.ClearColor(color.0, color.1, color.2, color.3);
self.gl.Clear(gl::COLOR_BUFFER_BIT);
self.gl.DrawArrays(gl::TRIANGLES, 0, 3);
}
}
}
static VERTEX_DATA: [f32; 15] = [
-0.5, -0.5, 1.0, 0.0, 0.0,
0.0, 0.5, 0.0, 1.0, 0.0,
0.5, -0.5, 0.0, 0.0, 1.0
];
const VS_SRC: &'static [u8] = b"
#version 100
precision mediump float;
attribute vec2 position;
attribute vec3 color;
varying vec3 v_color;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
v_color = color;
}
\0";
const FS_SRC: &'static [u8] = b"
#version 100
precision mediump float;
varying vec3 v_color;
void main() {
gl_FragColor = vec4(v_color, 1.0);
}
\0";
|
load
|
identifier_name
|
mod.rs
|
use std::ffi::CStr;
use std::mem;
use std::ptr;
use glutin;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
pub struct Context {
gl: gl::Gl
}
pub fn load(window: &glutin::Window) -> Context
|
gl.AttachShader(program, vs);
gl.AttachShader(program, fs);
gl.LinkProgram(program);
gl.UseProgram(program);
let mut vb = mem::uninitialized();
gl.GenBuffers(1, &mut vb);
gl.BindBuffer(gl::ARRAY_BUFFER, vb);
gl.BufferData(gl::ARRAY_BUFFER,
(VERTEX_DATA.len() * mem::size_of::<f32>()) as gl::types::GLsizeiptr,
VERTEX_DATA.as_ptr() as *const _, gl::STATIC_DRAW);
if gl.BindVertexArray.is_loaded() {
let mut vao = mem::uninitialized();
gl.GenVertexArrays(1, &mut vao);
gl.BindVertexArray(vao);
}
let pos_attrib = gl.GetAttribLocation(program, b"position\0".as_ptr() as *const _);
let color_attrib = gl.GetAttribLocation(program, b"color\0".as_ptr() as *const _);
gl.VertexAttribPointer(pos_attrib as gl::types::GLuint, 2, gl::FLOAT, 0,
5 * mem::size_of::<f32>() as gl::types::GLsizei,
ptr::null());
gl.VertexAttribPointer(color_attrib as gl::types::GLuint, 3, gl::FLOAT, 0,
5 * mem::size_of::<f32>() as gl::types::GLsizei,
(2 * mem::size_of::<f32>()) as *const () as *const _);
gl.EnableVertexAttribArray(pos_attrib as gl::types::GLuint);
gl.EnableVertexAttribArray(color_attrib as gl::types::GLuint);
}
Context { gl: gl }
}
impl Context {
pub fn draw_frame(&self, color: (f32, f32, f32, f32)) {
unsafe {
self.gl.ClearColor(color.0, color.1, color.2, color.3);
self.gl.Clear(gl::COLOR_BUFFER_BIT);
self.gl.DrawArrays(gl::TRIANGLES, 0, 3);
}
}
}
static VERTEX_DATA: [f32; 15] = [
-0.5, -0.5, 1.0, 0.0, 0.0,
0.0, 0.5, 0.0, 1.0, 0.0,
0.5, -0.5, 0.0, 0.0, 1.0
];
const VS_SRC: &'static [u8] = b"
#version 100
precision mediump float;
attribute vec2 position;
attribute vec3 color;
varying vec3 v_color;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
v_color = color;
}
\0";
const FS_SRC: &'static [u8] = b"
#version 100
precision mediump float;
varying vec3 v_color;
void main() {
gl_FragColor = vec4(v_color, 1.0);
}
\0";
|
{
let gl = gl::Gl::load_with(|ptr| window.get_proc_address(ptr) as *const _);
let version = unsafe {
let data = CStr::from_ptr(gl.GetString(gl::VERSION) as *const _).to_bytes().to_vec();
String::from_utf8(data).unwrap()
};
println!("OpenGL version {}", version);
unsafe {
let vs = gl.CreateShader(gl::VERTEX_SHADER);
gl.ShaderSource(vs, 1, [VS_SRC.as_ptr() as *const i8].as_ptr(), ptr::null());
gl.CompileShader(vs);
let fs = gl.CreateShader(gl::FRAGMENT_SHADER);
gl.ShaderSource(fs, 1, [FS_SRC.as_ptr() as *const i8].as_ptr(), ptr::null());
gl.CompileShader(fs);
let program = gl.CreateProgram();
|
identifier_body
|
mod.rs
|
use std::ffi::CStr;
use std::mem;
use std::ptr;
use glutin;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
pub struct Context {
gl: gl::Gl
}
pub fn load(window: &glutin::Window) -> Context {
let gl = gl::Gl::load_with(|ptr| window.get_proc_address(ptr) as *const _);
let version = unsafe {
let data = CStr::from_ptr(gl.GetString(gl::VERSION) as *const _).to_bytes().to_vec();
String::from_utf8(data).unwrap()
};
println!("OpenGL version {}", version);
unsafe {
let vs = gl.CreateShader(gl::VERTEX_SHADER);
gl.ShaderSource(vs, 1, [VS_SRC.as_ptr() as *const i8].as_ptr(), ptr::null());
gl.CompileShader(vs);
let fs = gl.CreateShader(gl::FRAGMENT_SHADER);
gl.ShaderSource(fs, 1, [FS_SRC.as_ptr() as *const i8].as_ptr(), ptr::null());
gl.CompileShader(fs);
let program = gl.CreateProgram();
gl.AttachShader(program, vs);
gl.AttachShader(program, fs);
gl.LinkProgram(program);
gl.UseProgram(program);
let mut vb = mem::uninitialized();
gl.GenBuffers(1, &mut vb);
gl.BindBuffer(gl::ARRAY_BUFFER, vb);
gl.BufferData(gl::ARRAY_BUFFER,
(VERTEX_DATA.len() * mem::size_of::<f32>()) as gl::types::GLsizeiptr,
VERTEX_DATA.as_ptr() as *const _, gl::STATIC_DRAW);
if gl.BindVertexArray.is_loaded()
|
let pos_attrib = gl.GetAttribLocation(program, b"position\0".as_ptr() as *const _);
let color_attrib = gl.GetAttribLocation(program, b"color\0".as_ptr() as *const _);
gl.VertexAttribPointer(pos_attrib as gl::types::GLuint, 2, gl::FLOAT, 0,
5 * mem::size_of::<f32>() as gl::types::GLsizei,
ptr::null());
gl.VertexAttribPointer(color_attrib as gl::types::GLuint, 3, gl::FLOAT, 0,
5 * mem::size_of::<f32>() as gl::types::GLsizei,
(2 * mem::size_of::<f32>()) as *const () as *const _);
gl.EnableVertexAttribArray(pos_attrib as gl::types::GLuint);
gl.EnableVertexAttribArray(color_attrib as gl::types::GLuint);
}
Context { gl: gl }
}
impl Context {
pub fn draw_frame(&self, color: (f32, f32, f32, f32)) {
unsafe {
self.gl.ClearColor(color.0, color.1, color.2, color.3);
self.gl.Clear(gl::COLOR_BUFFER_BIT);
self.gl.DrawArrays(gl::TRIANGLES, 0, 3);
}
}
}
static VERTEX_DATA: [f32; 15] = [
-0.5, -0.5, 1.0, 0.0, 0.0,
0.0, 0.5, 0.0, 1.0, 0.0,
0.5, -0.5, 0.0, 0.0, 1.0
];
const VS_SRC: &'static [u8] = b"
#version 100
precision mediump float;
attribute vec2 position;
attribute vec3 color;
varying vec3 v_color;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
v_color = color;
}
\0";
const FS_SRC: &'static [u8] = b"
#version 100
precision mediump float;
varying vec3 v_color;
void main() {
gl_FragColor = vec4(v_color, 1.0);
}
\0";
|
{
let mut vao = mem::uninitialized();
gl.GenVertexArrays(1, &mut vao);
gl.BindVertexArray(vao);
}
|
conditional_block
|
mod.rs
|
use std::ffi::CStr;
use std::mem;
use std::ptr;
use glutin;
mod gl {
pub use self::Gles2 as Gl;
include!(concat!(env!("OUT_DIR"), "/test_gl_bindings.rs"));
}
pub struct Context {
gl: gl::Gl
}
pub fn load(window: &glutin::Window) -> Context {
let gl = gl::Gl::load_with(|ptr| window.get_proc_address(ptr) as *const _);
let version = unsafe {
let data = CStr::from_ptr(gl.GetString(gl::VERSION) as *const _).to_bytes().to_vec();
String::from_utf8(data).unwrap()
};
println!("OpenGL version {}", version);
unsafe {
let vs = gl.CreateShader(gl::VERTEX_SHADER);
gl.ShaderSource(vs, 1, [VS_SRC.as_ptr() as *const i8].as_ptr(), ptr::null());
gl.CompileShader(vs);
let fs = gl.CreateShader(gl::FRAGMENT_SHADER);
gl.ShaderSource(fs, 1, [FS_SRC.as_ptr() as *const i8].as_ptr(), ptr::null());
gl.CompileShader(fs);
let program = gl.CreateProgram();
gl.AttachShader(program, vs);
gl.AttachShader(program, fs);
gl.LinkProgram(program);
gl.UseProgram(program);
let mut vb = mem::uninitialized();
gl.GenBuffers(1, &mut vb);
gl.BindBuffer(gl::ARRAY_BUFFER, vb);
gl.BufferData(gl::ARRAY_BUFFER,
(VERTEX_DATA.len() * mem::size_of::<f32>()) as gl::types::GLsizeiptr,
VERTEX_DATA.as_ptr() as *const _, gl::STATIC_DRAW);
if gl.BindVertexArray.is_loaded() {
let mut vao = mem::uninitialized();
gl.GenVertexArrays(1, &mut vao);
gl.BindVertexArray(vao);
}
let pos_attrib = gl.GetAttribLocation(program, b"position\0".as_ptr() as *const _);
let color_attrib = gl.GetAttribLocation(program, b"color\0".as_ptr() as *const _);
gl.VertexAttribPointer(pos_attrib as gl::types::GLuint, 2, gl::FLOAT, 0,
5 * mem::size_of::<f32>() as gl::types::GLsizei,
ptr::null());
gl.VertexAttribPointer(color_attrib as gl::types::GLuint, 3, gl::FLOAT, 0,
5 * mem::size_of::<f32>() as gl::types::GLsizei,
(2 * mem::size_of::<f32>()) as *const () as *const _);
gl.EnableVertexAttribArray(pos_attrib as gl::types::GLuint);
gl.EnableVertexAttribArray(color_attrib as gl::types::GLuint);
}
Context { gl: gl }
}
impl Context {
pub fn draw_frame(&self, color: (f32, f32, f32, f32)) {
unsafe {
self.gl.ClearColor(color.0, color.1, color.2, color.3);
self.gl.Clear(gl::COLOR_BUFFER_BIT);
self.gl.DrawArrays(gl::TRIANGLES, 0, 3);
}
}
|
0.5, -0.5, 0.0, 0.0, 1.0
];
const VS_SRC: &'static [u8] = b"
#version 100
precision mediump float;
attribute vec2 position;
attribute vec3 color;
varying vec3 v_color;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
v_color = color;
}
\0";
const FS_SRC: &'static [u8] = b"
#version 100
precision mediump float;
varying vec3 v_color;
void main() {
gl_FragColor = vec4(v_color, 1.0);
}
\0";
|
}
static VERTEX_DATA: [f32; 15] = [
-0.5, -0.5, 1.0, 0.0, 0.0,
0.0, 0.5, 0.0, 1.0, 0.0,
|
random_line_split
|
ast_map.rs
|
_ident_interner;
use parse::token::ident_interner;
use parse::token::special_idents;
use print::pprust;
use visit::{Visitor, fn_kind};
use visit;
use std::hashmap::HashMap;
use std::vec;
#[deriving(Clone, Eq)]
pub enum path_elt {
path_mod(Ident),
path_name(Ident),
// A pretty name can come from an `impl` block. We attempt to select a
// reasonable name for debuggers to see, but to guarantee uniqueness with
// other paths the hash should also be taken into account during symbol
// generation.
path_pretty_name(Ident, u64),
}
impl path_elt {
pub fn ident(&self) -> Ident {
match *self {
path_mod(ident) |
path_name(ident) |
path_pretty_name(ident, _) => ident
}
}
}
pub type path = ~[path_elt];
pub fn path_to_str_with_sep(p: &[path_elt], sep: &str, itr: @ident_interner)
-> ~str {
let strs = do p.map |e| {
match *e {
path_mod(s) | path_name(s) | path_pretty_name(s, _) => {
itr.get(s.name)
}
}
};
strs.connect(sep)
}
pub fn path_ident_to_str(p: &path, i: Ident, itr: @ident_interner) -> ~str {
if p.is_empty() {
itr.get(i.name).to_owned()
} else {
format!("{}::{}", path_to_str(*p, itr), itr.get(i.name))
}
}
pub fn path_to_str(p: &[path_elt], itr: @ident_interner) -> ~str {
path_to_str_with_sep(p, "::", itr)
}
pub fn path_elt_to_str(pe: path_elt, itr: @ident_interner) -> ~str {
match pe {
path_mod(s) | path_name(s) | path_pretty_name(s, _) => {
itr.get(s.name).to_owned()
}
}
}
pub fn impl_pretty_name(trait_ref: &Option<trait_ref>,
ty: &Ty, default: Ident) -> path_elt {
let itr = get_ident_interner();
let ty_ident = match ty.node {
ty_path(ref path, _, _) => path.segments.last().identifier,
_ => default
};
let hash = (trait_ref, ty).hash();
match *trait_ref {
None => path_pretty_name(ty_ident, hash),
Some(ref trait_ref) => {
// XXX: this dollar sign is actually a relic of being one of the
// very few valid symbol names on unix. These kinds of
// details shouldn't be exposed way up here in the ast.
let s = format!("{}${}",
itr.get(trait_ref.path.segments.last().identifier.name),
itr.get(ty_ident.name));
path_pretty_name(Ident::new(itr.gensym(s)), hash)
}
}
}
#[deriving(Clone)]
pub enum ast_node {
node_item(@item, @path),
node_foreign_item(@foreign_item, AbiSet, visibility, @path),
node_trait_method(@trait_method, DefId /* trait did */,
@path /* path to the trait */),
node_method(@method, DefId /* impl did */, @path /* path to the impl */),
node_variant(variant, @item, @path),
node_expr(@Expr),
node_stmt(@Stmt),
node_arg(@Pat),
node_local(Ident),
node_block(Block),
node_struct_ctor(@struct_def, @item, @path),
node_callee_scope(@Expr)
}
impl ast_node {
pub fn with_attrs<T>(&self, f: &fn(Option<&[Attribute]>) -> T) -> T {
let attrs = match *self {
node_item(i, _) => Some(i.attrs.as_slice()),
node_foreign_item(fi, _, _, _) => Some(fi.attrs.as_slice()),
node_trait_method(tm, _, _) => match *tm {
required(ref type_m) => Some(type_m.attrs.as_slice()),
provided(m) => Some(m.attrs.as_slice())
},
node_method(m, _, _) => Some(m.attrs.as_slice()),
node_variant(ref v, _, _) => Some(v.node.attrs.as_slice()),
// unit/tuple structs take the attributes straight from
// the struct definition.
node_struct_ctor(_, strct, _) => Some(strct.attrs.as_slice()),
_ => None
};
f(attrs)
}
}
pub type map = @mut HashMap<NodeId, ast_node>;
pub struct Ctx {
map: map,
path: path,
diag: @mut span_handler,
}
impl Ctx {
fn extend(&self, elt: path_elt) -> @path {
@vec::append(self.path.clone(), [elt])
}
fn map_method(&mut self,
impl_did: DefId,
impl_path: @path,
m: @method,
is_provided: bool) {
let entry = if is_provided {
node_trait_method(@provided(m), impl_did, impl_path)
} else {
node_method(m, impl_did, impl_path)
};
self.map.insert(m.id, entry);
self.map.insert(m.self_id, node_local(special_idents::self_));
}
fn map_struct_def(&mut self,
struct_def: @ast::struct_def,
parent_node: ast_node,
ident: ast::Ident) {
let p = self.extend(path_name(ident));
// If this is a tuple-like struct, register the constructor.
match struct_def.ctor_id {
None => {}
Some(ctor_id) => {
match parent_node {
node_item(item, _) => {
self.map.insert(ctor_id,
node_struct_ctor(struct_def,
item,
|
}
_ => fail2!("struct def parent wasn't an item")
}
}
}
}
fn map_expr(&mut self, ex: @Expr) {
self.map.insert(ex.id, node_expr(ex));
// Expressions which are or might be calls:
{
let r = ex.get_callee_id();
for callee_id in r.iter() {
self.map.insert(*callee_id, node_callee_scope(ex));
}
}
visit::walk_expr(self, ex, ());
}
fn map_fn(&mut self,
fk: &visit::fn_kind,
decl: &fn_decl,
body: &Block,
sp: codemap::Span,
id: NodeId) {
for a in decl.inputs.iter() {
self.map.insert(a.id, node_arg(a.pat));
}
match *fk {
visit::fk_method(name, _, _) => { self.path.push(path_name(name)) }
_ => {}
}
visit::walk_fn(self, fk, decl, body, sp, id, ());
match *fk {
visit::fk_method(*) => { self.path.pop(); }
_ => {}
}
}
fn map_stmt(&mut self, stmt: @Stmt) {
self.map.insert(stmt_id(stmt), node_stmt(stmt));
visit::walk_stmt(self, stmt, ());
}
fn map_block(&mut self, b: &Block) {
// clone is FIXME #2543
self.map.insert(b.id, node_block((*b).clone()));
visit::walk_block(self, b, ());
}
fn map_pat(&mut self, pat: @Pat) {
match pat.node {
PatIdent(_, ref path, _) => {
// Note: this is at least *potentially* a pattern...
self.map.insert(pat.id,
node_local(ast_util::path_to_ident(path)));
}
_ => ()
}
visit::walk_pat(self, pat, ());
}
}
impl Visitor<()> for Ctx {
fn visit_item(&mut self, i: @item, _: ()) {
// clone is FIXME #2543
let item_path = @self.path.clone();
self.map.insert(i.id, node_item(i, item_path));
match i.node {
item_impl(_, ref maybe_trait, ref ty, ref ms) => {
// Right now the ident on impls is __extensions__ which isn't
// very pretty when debugging, so attempt to select a better
// name to use.
let elt = impl_pretty_name(maybe_trait, ty, i.ident);
let impl_did = ast_util::local_def(i.id);
for m in ms.iter() {
let extended = { self.extend(elt) };
self.map_method(impl_did, extended, *m, false)
}
self.path.push(elt);
}
item_enum(ref enum_definition, _) => {
for v in (*enum_definition).variants.iter() {
let elt = path_name(i.ident);
// FIXME #2543: bad clone
self.map.insert(v.node.id,
node_variant((*v).clone(),
i,
self.extend(elt)));
}
}
item_foreign_mod(ref nm) => {
for nitem in nm.items.iter() {
// Compute the visibility for this native item.
let visibility = match nitem.vis {
public => public,
private => private,
inherited => i.vis
};
self.map.insert(nitem.id,
node_foreign_item(*nitem,
nm.abis,
visibility,
// FIXME (#2543)
// Anonymous extern
// mods go in the
// parent scope.
@self.path.clone()
));
}
}
item_struct(struct_def, _) => {
self.map_struct_def(struct_def,
node_item(i, item_path),
i.ident)
}
item_trait(_, ref traits, ref methods) => {
for p in traits.iter() {
self.map.insert(p.ref_id, node_item(i, item_path));
}
for tm in methods.iter() {
let ext = { self.extend(path_name(i.ident)) };
let d_id = ast_util::local_def(i.id);
match *tm {
required(ref m) => {
let entry =
node_trait_method(@(*tm).clone(), d_id, ext);
self.map.insert(m.id, entry);
}
provided(m) => {
self.map_method(d_id, ext, m, true);
}
}
}
}
_ => {}
}
match i.node {
item_mod(_) | item_foreign_mod(_) => {
self.path.push(path_mod(i.ident));
}
item_impl(*) => {} // this was guessed above.
_ => self.path.push(path_name(i.ident))
}
visit::walk_item(self, i, ());
self.path.pop();
}
fn visit_pat(&mut self, pat: @Pat, _: ()) {
self.map_pat(pat);
visit::walk_pat(self, pat, ())
}
fn visit_expr(&mut self, expr: @Expr, _: ()) {
self.map_expr(expr)
}
fn visit_stmt(&mut self, stmt: @Stmt, _: ()) {
self.map_stmt(stmt)
}
fn visit_fn(&mut self,
function_kind: &fn_kind,
function_declaration: &fn_decl,
block: &Block,
span: Span,
node_id: NodeId,
_: ()) {
self.map_fn(function_kind, function_declaration, block, span, node_id)
}
fn visit_block(&mut self, block: &Block, _: ()) {
self.map_block(block)
}
fn visit_ty(&mut self, typ: &Ty, _: ()) {
visit::walk_ty(self, typ, ())
}
}
pub fn map_crate(diag: @mut span_handler, c: &Crate) -> map {
let cx = @mut Ctx {
map: @mut HashMap::new(),
path: ~[],
diag: diag,
};
visit::walk_crate(cx, c, ());
cx.map
}
// Used for items loaded from external crate that are being inlined into this
// crate. The `path` should be the path to the item but should not include
// the item itself.
pub fn map_decoded_item(diag: @mut span_handler,
map: map,
path: path,
ii: &inlined_item) {
// I believe it is ok for the local IDs of inlined items from other crates
// to overlap with the local ids from this crate, so just generate the ids
// starting from 0.
let cx = @mut Ctx {
map: map,
path: path.clone(),
diag: diag,
};
// Methods get added to the AST map when their impl is visited. Since we
// don't decode and instantiate the impl, but just the method, we have to
// add it to the table now. Likewise with foreign items.
match *ii {
ii_item(*) => {} // fallthrough
ii_foreign(i) => {
cx.map.insert(i.id, node_foreign_item(i,
AbiSet::Intrinsic(),
i.vis, // Wrong but OK
@path));
}
ii_method(impl_did, is_provided, m) => {
cx.map_method(impl_did, @path, m, is_provided);
}
}
// visit the item / method contents and add those to the map:
ii.accept((), cx);
}
pub fn node_id_to_str(map: map, id: NodeId, itr: @ident_interner) -> ~str {
match map.find(&id) {
None => {
format!("unknown node (id={})", id)
}
Some(&node_item(item, path)) => {
let path_str = path_ident_to_str(path, item.ident, itr);
let item_str = match item.node {
item_static(*) => ~"static",
item_fn(*) => ~"fn",
item_mod(*) => ~"mod",
item_foreign_mod(*) => ~"foreign mod",
item_ty(*) => ~"ty",
item_enum(*) => ~"enum",
item_struct(*) => ~"struct",
item_trait(*) => ~"trait",
item_impl(*) => ~"impl",
item_mac(*) => ~"macro"
};
format!("{} {} (id={})", item_str, path_str, id)
}
Some(&node_foreign_item(item, abi, _, path)) => {
format!("foreign item {} with abi {:?} (id={})",
path_ident_to_str(path, item.ident, itr), abi, id)
}
Some(&node_method(m, _, path)) => {
format!("method {} in {} (id={})",
itr.get(m.ident.name), path_to_str(*path, itr), id)
}
Some(&node_trait_method(ref tm, _, path)) => {
let m = ast_util::trait_method_to_ty_method(&**tm);
format!("method {} in {} (id={})",
itr.get(m.ident.name), path_to_str(*path, itr), id)
}
Some(&node_variant(ref variant, _, path)) => {
format!("variant {} in {} (id={})",
itr.get(variant.node.name.name), path_to_str(*path, itr), id)
}
Some(&node_expr(expr)) => {
format!("expr {} (id={})", pprust::expr_to_str(expr, itr), id)
}
Some(&node_callee_scope(expr)) => {
format!("callee_scope {} (id={})", pprust::expr_to_str(expr, itr), id)
}
Some(&node_stmt(stmt))
|
p));
|
random_line_split
|
ast_map.rs
|
ident_interner;
use parse::token::ident_interner;
use parse::token::special_idents;
use print::pprust;
use visit::{Visitor, fn_kind};
use visit;
use std::hashmap::HashMap;
use std::vec;
#[deriving(Clone, Eq)]
pub enum path_elt {
path_mod(Ident),
path_name(Ident),
// A pretty name can come from an `impl` block. We attempt to select a
// reasonable name for debuggers to see, but to guarantee uniqueness with
// other paths the hash should also be taken into account during symbol
// generation.
path_pretty_name(Ident, u64),
}
impl path_elt {
pub fn ident(&self) -> Ident {
match *self {
path_mod(ident) |
path_name(ident) |
path_pretty_name(ident, _) => ident
}
}
}
pub type path = ~[path_elt];
pub fn path_to_str_with_sep(p: &[path_elt], sep: &str, itr: @ident_interner)
-> ~str {
let strs = do p.map |e| {
match *e {
path_mod(s) | path_name(s) | path_pretty_name(s, _) => {
itr.get(s.name)
}
}
};
strs.connect(sep)
}
pub fn path_ident_to_str(p: &path, i: Ident, itr: @ident_interner) -> ~str {
if p.is_empty() {
itr.get(i.name).to_owned()
} else {
format!("{}::{}", path_to_str(*p, itr), itr.get(i.name))
}
}
pub fn path_to_str(p: &[path_elt], itr: @ident_interner) -> ~str {
path_to_str_with_sep(p, "::", itr)
}
pub fn path_elt_to_str(pe: path_elt, itr: @ident_interner) -> ~str {
match pe {
path_mod(s) | path_name(s) | path_pretty_name(s, _) => {
itr.get(s.name).to_owned()
}
}
}
pub fn impl_pretty_name(trait_ref: &Option<trait_ref>,
ty: &Ty, default: Ident) -> path_elt {
let itr = get_ident_interner();
let ty_ident = match ty.node {
ty_path(ref path, _, _) => path.segments.last().identifier,
_ => default
};
let hash = (trait_ref, ty).hash();
match *trait_ref {
None => path_pretty_name(ty_ident, hash),
Some(ref trait_ref) => {
// XXX: this dollar sign is actually a relic of being one of the
// very few valid symbol names on unix. These kinds of
// details shouldn't be exposed way up here in the ast.
let s = format!("{}${}",
itr.get(trait_ref.path.segments.last().identifier.name),
itr.get(ty_ident.name));
path_pretty_name(Ident::new(itr.gensym(s)), hash)
}
}
}
#[deriving(Clone)]
pub enum ast_node {
node_item(@item, @path),
node_foreign_item(@foreign_item, AbiSet, visibility, @path),
node_trait_method(@trait_method, DefId /* trait did */,
@path /* path to the trait */),
node_method(@method, DefId /* impl did */, @path /* path to the impl */),
node_variant(variant, @item, @path),
node_expr(@Expr),
node_stmt(@Stmt),
node_arg(@Pat),
node_local(Ident),
node_block(Block),
node_struct_ctor(@struct_def, @item, @path),
node_callee_scope(@Expr)
}
impl ast_node {
pub fn with_attrs<T>(&self, f: &fn(Option<&[Attribute]>) -> T) -> T {
let attrs = match *self {
node_item(i, _) => Some(i.attrs.as_slice()),
node_foreign_item(fi, _, _, _) => Some(fi.attrs.as_slice()),
node_trait_method(tm, _, _) => match *tm {
required(ref type_m) => Some(type_m.attrs.as_slice()),
provided(m) => Some(m.attrs.as_slice())
},
node_method(m, _, _) => Some(m.attrs.as_slice()),
node_variant(ref v, _, _) => Some(v.node.attrs.as_slice()),
// unit/tuple structs take the attributes straight from
// the struct definition.
node_struct_ctor(_, strct, _) => Some(strct.attrs.as_slice()),
_ => None
};
f(attrs)
}
}
pub type map = @mut HashMap<NodeId, ast_node>;
pub struct Ctx {
map: map,
path: path,
diag: @mut span_handler,
}
impl Ctx {
fn extend(&self, elt: path_elt) -> @path {
@vec::append(self.path.clone(), [elt])
}
fn map_method(&mut self,
impl_did: DefId,
impl_path: @path,
m: @method,
is_provided: bool) {
let entry = if is_provided {
node_trait_method(@provided(m), impl_did, impl_path)
} else {
node_method(m, impl_did, impl_path)
};
self.map.insert(m.id, entry);
self.map.insert(m.self_id, node_local(special_idents::self_));
}
fn map_struct_def(&mut self,
struct_def: @ast::struct_def,
parent_node: ast_node,
ident: ast::Ident) {
let p = self.extend(path_name(ident));
// If this is a tuple-like struct, register the constructor.
match struct_def.ctor_id {
None => {}
Some(ctor_id) => {
match parent_node {
node_item(item, _) => {
self.map.insert(ctor_id,
node_struct_ctor(struct_def,
item,
p));
}
_ => fail2!("struct def parent wasn't an item")
}
}
}
}
fn map_expr(&mut self, ex: @Expr) {
self.map.insert(ex.id, node_expr(ex));
// Expressions which are or might be calls:
{
let r = ex.get_callee_id();
for callee_id in r.iter() {
self.map.insert(*callee_id, node_callee_scope(ex));
}
}
visit::walk_expr(self, ex, ());
}
fn map_fn(&mut self,
fk: &visit::fn_kind,
decl: &fn_decl,
body: &Block,
sp: codemap::Span,
id: NodeId) {
for a in decl.inputs.iter() {
self.map.insert(a.id, node_arg(a.pat));
}
match *fk {
visit::fk_method(name, _, _) => { self.path.push(path_name(name)) }
_ => {}
}
visit::walk_fn(self, fk, decl, body, sp, id, ());
match *fk {
visit::fk_method(*) => { self.path.pop(); }
_ => {}
}
}
fn map_stmt(&mut self, stmt: @Stmt) {
self.map.insert(stmt_id(stmt), node_stmt(stmt));
visit::walk_stmt(self, stmt, ());
}
fn map_block(&mut self, b: &Block) {
// clone is FIXME #2543
self.map.insert(b.id, node_block((*b).clone()));
visit::walk_block(self, b, ());
}
fn map_pat(&mut self, pat: @Pat) {
match pat.node {
PatIdent(_, ref path, _) => {
// Note: this is at least *potentially* a pattern...
self.map.insert(pat.id,
node_local(ast_util::path_to_ident(path)));
}
_ => ()
}
visit::walk_pat(self, pat, ());
}
}
impl Visitor<()> for Ctx {
fn visit_item(&mut self, i: @item, _: ()) {
// clone is FIXME #2543
let item_path = @self.path.clone();
self.map.insert(i.id, node_item(i, item_path));
match i.node {
item_impl(_, ref maybe_trait, ref ty, ref ms) => {
// Right now the ident on impls is __extensions__ which isn't
// very pretty when debugging, so attempt to select a better
// name to use.
let elt = impl_pretty_name(maybe_trait, ty, i.ident);
let impl_did = ast_util::local_def(i.id);
for m in ms.iter() {
let extended = { self.extend(elt) };
self.map_method(impl_did, extended, *m, false)
}
self.path.push(elt);
}
item_enum(ref enum_definition, _) => {
for v in (*enum_definition).variants.iter() {
let elt = path_name(i.ident);
// FIXME #2543: bad clone
self.map.insert(v.node.id,
node_variant((*v).clone(),
i,
self.extend(elt)));
}
}
item_foreign_mod(ref nm) => {
for nitem in nm.items.iter() {
// Compute the visibility for this native item.
let visibility = match nitem.vis {
public => public,
private => private,
inherited => i.vis
};
self.map.insert(nitem.id,
node_foreign_item(*nitem,
nm.abis,
visibility,
// FIXME (#2543)
// Anonymous extern
// mods go in the
// parent scope.
@self.path.clone()
));
}
}
item_struct(struct_def, _) => {
self.map_struct_def(struct_def,
node_item(i, item_path),
i.ident)
}
item_trait(_, ref traits, ref methods) => {
for p in traits.iter() {
self.map.insert(p.ref_id, node_item(i, item_path));
}
for tm in methods.iter() {
let ext = { self.extend(path_name(i.ident)) };
let d_id = ast_util::local_def(i.id);
match *tm {
required(ref m) => {
let entry =
node_trait_method(@(*tm).clone(), d_id, ext);
self.map.insert(m.id, entry);
}
provided(m) => {
self.map_method(d_id, ext, m, true);
}
}
}
}
_ => {}
}
match i.node {
item_mod(_) | item_foreign_mod(_) => {
self.path.push(path_mod(i.ident));
}
item_impl(*) => {} // this was guessed above.
_ => self.path.push(path_name(i.ident))
}
visit::walk_item(self, i, ());
self.path.pop();
}
fn visit_pat(&mut self, pat: @Pat, _: ()) {
self.map_pat(pat);
visit::walk_pat(self, pat, ())
}
fn visit_expr(&mut self, expr: @Expr, _: ())
|
fn visit_stmt(&mut self, stmt: @Stmt, _: ()) {
self.map_stmt(stmt)
}
fn visit_fn(&mut self,
function_kind: &fn_kind,
function_declaration: &fn_decl,
block: &Block,
span: Span,
node_id: NodeId,
_: ()) {
self.map_fn(function_kind, function_declaration, block, span, node_id)
}
fn visit_block(&mut self, block: &Block, _: ()) {
self.map_block(block)
}
fn visit_ty(&mut self, typ: &Ty, _: ()) {
visit::walk_ty(self, typ, ())
}
}
pub fn map_crate(diag: @mut span_handler, c: &Crate) -> map {
let cx = @mut Ctx {
map: @mut HashMap::new(),
path: ~[],
diag: diag,
};
visit::walk_crate(cx, c, ());
cx.map
}
// Used for items loaded from external crate that are being inlined into this
// crate. The `path` should be the path to the item but should not include
// the item itself.
pub fn map_decoded_item(diag: @mut span_handler,
map: map,
path: path,
ii: &inlined_item) {
// I believe it is ok for the local IDs of inlined items from other crates
// to overlap with the local ids from this crate, so just generate the ids
// starting from 0.
let cx = @mut Ctx {
map: map,
path: path.clone(),
diag: diag,
};
// Methods get added to the AST map when their impl is visited. Since we
// don't decode and instantiate the impl, but just the method, we have to
// add it to the table now. Likewise with foreign items.
match *ii {
ii_item(*) => {} // fallthrough
ii_foreign(i) => {
cx.map.insert(i.id, node_foreign_item(i,
AbiSet::Intrinsic(),
i.vis, // Wrong but OK
@path));
}
ii_method(impl_did, is_provided, m) => {
cx.map_method(impl_did, @path, m, is_provided);
}
}
// visit the item / method contents and add those to the map:
ii.accept((), cx);
}
pub fn node_id_to_str(map: map, id: NodeId, itr: @ident_interner) -> ~str {
match map.find(&id) {
None => {
format!("unknown node (id={})", id)
}
Some(&node_item(item, path)) => {
let path_str = path_ident_to_str(path, item.ident, itr);
let item_str = match item.node {
item_static(*) => ~"static",
item_fn(*) => ~"fn",
item_mod(*) => ~"mod",
item_foreign_mod(*) => ~"foreign mod",
item_ty(*) => ~"ty",
item_enum(*) => ~"enum",
item_struct(*) => ~"struct",
item_trait(*) => ~"trait",
item_impl(*) => ~"impl",
item_mac(*) => ~"macro"
};
format!("{} {} (id={})", item_str, path_str, id)
}
Some(&node_foreign_item(item, abi, _, path)) => {
format!("foreign item {} with abi {:?} (id={})",
path_ident_to_str(path, item.ident, itr), abi, id)
}
Some(&node_method(m, _, path)) => {
format!("method {} in {} (id={})",
itr.get(m.ident.name), path_to_str(*path, itr), id)
}
Some(&node_trait_method(ref tm, _, path)) => {
let m = ast_util::trait_method_to_ty_method(&**tm);
format!("method {} in {} (id={})",
itr.get(m.ident.name), path_to_str(*path, itr), id)
}
Some(&node_variant(ref variant, _, path)) => {
format!("variant {} in {} (id={})",
itr.get(variant.node.name.name), path_to_str(*path, itr), id)
}
Some(&node_expr(expr)) => {
format!("expr {} (id={})", pprust::expr_to_str(expr, itr), id)
}
Some(&node_callee_scope(expr)) => {
format!("callee_scope {} (id={})", pprust::expr_to_str(expr, itr), id)
}
Some(&node_stmt(
|
{
self.map_expr(expr)
}
|
identifier_body
|
ast_map.rs
|
ident_interner;
use parse::token::ident_interner;
use parse::token::special_idents;
use print::pprust;
use visit::{Visitor, fn_kind};
use visit;
use std::hashmap::HashMap;
use std::vec;
#[deriving(Clone, Eq)]
pub enum path_elt {
path_mod(Ident),
path_name(Ident),
// A pretty name can come from an `impl` block. We attempt to select a
// reasonable name for debuggers to see, but to guarantee uniqueness with
// other paths the hash should also be taken into account during symbol
// generation.
path_pretty_name(Ident, u64),
}
impl path_elt {
pub fn ident(&self) -> Ident {
match *self {
path_mod(ident) |
path_name(ident) |
path_pretty_name(ident, _) => ident
}
}
}
pub type path = ~[path_elt];
pub fn path_to_str_with_sep(p: &[path_elt], sep: &str, itr: @ident_interner)
-> ~str {
let strs = do p.map |e| {
match *e {
path_mod(s) | path_name(s) | path_pretty_name(s, _) => {
itr.get(s.name)
}
}
};
strs.connect(sep)
}
pub fn path_ident_to_str(p: &path, i: Ident, itr: @ident_interner) -> ~str {
if p.is_empty() {
itr.get(i.name).to_owned()
} else {
format!("{}::{}", path_to_str(*p, itr), itr.get(i.name))
}
}
pub fn path_to_str(p: &[path_elt], itr: @ident_interner) -> ~str {
path_to_str_with_sep(p, "::", itr)
}
pub fn
|
(pe: path_elt, itr: @ident_interner) -> ~str {
match pe {
path_mod(s) | path_name(s) | path_pretty_name(s, _) => {
itr.get(s.name).to_owned()
}
}
}
pub fn impl_pretty_name(trait_ref: &Option<trait_ref>,
ty: &Ty, default: Ident) -> path_elt {
let itr = get_ident_interner();
let ty_ident = match ty.node {
ty_path(ref path, _, _) => path.segments.last().identifier,
_ => default
};
let hash = (trait_ref, ty).hash();
match *trait_ref {
None => path_pretty_name(ty_ident, hash),
Some(ref trait_ref) => {
// XXX: this dollar sign is actually a relic of being one of the
// very few valid symbol names on unix. These kinds of
// details shouldn't be exposed way up here in the ast.
let s = format!("{}${}",
itr.get(trait_ref.path.segments.last().identifier.name),
itr.get(ty_ident.name));
path_pretty_name(Ident::new(itr.gensym(s)), hash)
}
}
}
#[deriving(Clone)]
pub enum ast_node {
node_item(@item, @path),
node_foreign_item(@foreign_item, AbiSet, visibility, @path),
node_trait_method(@trait_method, DefId /* trait did */,
@path /* path to the trait */),
node_method(@method, DefId /* impl did */, @path /* path to the impl */),
node_variant(variant, @item, @path),
node_expr(@Expr),
node_stmt(@Stmt),
node_arg(@Pat),
node_local(Ident),
node_block(Block),
node_struct_ctor(@struct_def, @item, @path),
node_callee_scope(@Expr)
}
impl ast_node {
pub fn with_attrs<T>(&self, f: &fn(Option<&[Attribute]>) -> T) -> T {
let attrs = match *self {
node_item(i, _) => Some(i.attrs.as_slice()),
node_foreign_item(fi, _, _, _) => Some(fi.attrs.as_slice()),
node_trait_method(tm, _, _) => match *tm {
required(ref type_m) => Some(type_m.attrs.as_slice()),
provided(m) => Some(m.attrs.as_slice())
},
node_method(m, _, _) => Some(m.attrs.as_slice()),
node_variant(ref v, _, _) => Some(v.node.attrs.as_slice()),
// unit/tuple structs take the attributes straight from
// the struct definition.
node_struct_ctor(_, strct, _) => Some(strct.attrs.as_slice()),
_ => None
};
f(attrs)
}
}
pub type map = @mut HashMap<NodeId, ast_node>;
pub struct Ctx {
map: map,
path: path,
diag: @mut span_handler,
}
impl Ctx {
fn extend(&self, elt: path_elt) -> @path {
@vec::append(self.path.clone(), [elt])
}
fn map_method(&mut self,
impl_did: DefId,
impl_path: @path,
m: @method,
is_provided: bool) {
let entry = if is_provided {
node_trait_method(@provided(m), impl_did, impl_path)
} else {
node_method(m, impl_did, impl_path)
};
self.map.insert(m.id, entry);
self.map.insert(m.self_id, node_local(special_idents::self_));
}
fn map_struct_def(&mut self,
struct_def: @ast::struct_def,
parent_node: ast_node,
ident: ast::Ident) {
let p = self.extend(path_name(ident));
// If this is a tuple-like struct, register the constructor.
match struct_def.ctor_id {
None => {}
Some(ctor_id) => {
match parent_node {
node_item(item, _) => {
self.map.insert(ctor_id,
node_struct_ctor(struct_def,
item,
p));
}
_ => fail2!("struct def parent wasn't an item")
}
}
}
}
fn map_expr(&mut self, ex: @Expr) {
self.map.insert(ex.id, node_expr(ex));
// Expressions which are or might be calls:
{
let r = ex.get_callee_id();
for callee_id in r.iter() {
self.map.insert(*callee_id, node_callee_scope(ex));
}
}
visit::walk_expr(self, ex, ());
}
fn map_fn(&mut self,
fk: &visit::fn_kind,
decl: &fn_decl,
body: &Block,
sp: codemap::Span,
id: NodeId) {
for a in decl.inputs.iter() {
self.map.insert(a.id, node_arg(a.pat));
}
match *fk {
visit::fk_method(name, _, _) => { self.path.push(path_name(name)) }
_ => {}
}
visit::walk_fn(self, fk, decl, body, sp, id, ());
match *fk {
visit::fk_method(*) => { self.path.pop(); }
_ => {}
}
}
fn map_stmt(&mut self, stmt: @Stmt) {
self.map.insert(stmt_id(stmt), node_stmt(stmt));
visit::walk_stmt(self, stmt, ());
}
fn map_block(&mut self, b: &Block) {
// clone is FIXME #2543
self.map.insert(b.id, node_block((*b).clone()));
visit::walk_block(self, b, ());
}
fn map_pat(&mut self, pat: @Pat) {
match pat.node {
PatIdent(_, ref path, _) => {
// Note: this is at least *potentially* a pattern...
self.map.insert(pat.id,
node_local(ast_util::path_to_ident(path)));
}
_ => ()
}
visit::walk_pat(self, pat, ());
}
}
impl Visitor<()> for Ctx {
fn visit_item(&mut self, i: @item, _: ()) {
// clone is FIXME #2543
let item_path = @self.path.clone();
self.map.insert(i.id, node_item(i, item_path));
match i.node {
item_impl(_, ref maybe_trait, ref ty, ref ms) => {
// Right now the ident on impls is __extensions__ which isn't
// very pretty when debugging, so attempt to select a better
// name to use.
let elt = impl_pretty_name(maybe_trait, ty, i.ident);
let impl_did = ast_util::local_def(i.id);
for m in ms.iter() {
let extended = { self.extend(elt) };
self.map_method(impl_did, extended, *m, false)
}
self.path.push(elt);
}
item_enum(ref enum_definition, _) => {
for v in (*enum_definition).variants.iter() {
let elt = path_name(i.ident);
// FIXME #2543: bad clone
self.map.insert(v.node.id,
node_variant((*v).clone(),
i,
self.extend(elt)));
}
}
item_foreign_mod(ref nm) => {
for nitem in nm.items.iter() {
// Compute the visibility for this native item.
let visibility = match nitem.vis {
public => public,
private => private,
inherited => i.vis
};
self.map.insert(nitem.id,
node_foreign_item(*nitem,
nm.abis,
visibility,
// FIXME (#2543)
// Anonymous extern
// mods go in the
// parent scope.
@self.path.clone()
));
}
}
item_struct(struct_def, _) => {
self.map_struct_def(struct_def,
node_item(i, item_path),
i.ident)
}
item_trait(_, ref traits, ref methods) => {
for p in traits.iter() {
self.map.insert(p.ref_id, node_item(i, item_path));
}
for tm in methods.iter() {
let ext = { self.extend(path_name(i.ident)) };
let d_id = ast_util::local_def(i.id);
match *tm {
required(ref m) => {
let entry =
node_trait_method(@(*tm).clone(), d_id, ext);
self.map.insert(m.id, entry);
}
provided(m) => {
self.map_method(d_id, ext, m, true);
}
}
}
}
_ => {}
}
match i.node {
item_mod(_) | item_foreign_mod(_) => {
self.path.push(path_mod(i.ident));
}
item_impl(*) => {} // this was guessed above.
_ => self.path.push(path_name(i.ident))
}
visit::walk_item(self, i, ());
self.path.pop();
}
fn visit_pat(&mut self, pat: @Pat, _: ()) {
self.map_pat(pat);
visit::walk_pat(self, pat, ())
}
fn visit_expr(&mut self, expr: @Expr, _: ()) {
self.map_expr(expr)
}
fn visit_stmt(&mut self, stmt: @Stmt, _: ()) {
self.map_stmt(stmt)
}
fn visit_fn(&mut self,
function_kind: &fn_kind,
function_declaration: &fn_decl,
block: &Block,
span: Span,
node_id: NodeId,
_: ()) {
self.map_fn(function_kind, function_declaration, block, span, node_id)
}
fn visit_block(&mut self, block: &Block, _: ()) {
self.map_block(block)
}
fn visit_ty(&mut self, typ: &Ty, _: ()) {
visit::walk_ty(self, typ, ())
}
}
pub fn map_crate(diag: @mut span_handler, c: &Crate) -> map {
let cx = @mut Ctx {
map: @mut HashMap::new(),
path: ~[],
diag: diag,
};
visit::walk_crate(cx, c, ());
cx.map
}
// Used for items loaded from external crate that are being inlined into this
// crate. The `path` should be the path to the item but should not include
// the item itself.
pub fn map_decoded_item(diag: @mut span_handler,
map: map,
path: path,
ii: &inlined_item) {
// I believe it is ok for the local IDs of inlined items from other crates
// to overlap with the local ids from this crate, so just generate the ids
// starting from 0.
let cx = @mut Ctx {
map: map,
path: path.clone(),
diag: diag,
};
// Methods get added to the AST map when their impl is visited. Since we
// don't decode and instantiate the impl, but just the method, we have to
// add it to the table now. Likewise with foreign items.
match *ii {
ii_item(*) => {} // fallthrough
ii_foreign(i) => {
cx.map.insert(i.id, node_foreign_item(i,
AbiSet::Intrinsic(),
i.vis, // Wrong but OK
@path));
}
ii_method(impl_did, is_provided, m) => {
cx.map_method(impl_did, @path, m, is_provided);
}
}
// visit the item / method contents and add those to the map:
ii.accept((), cx);
}
pub fn node_id_to_str(map: map, id: NodeId, itr: @ident_interner) -> ~str {
match map.find(&id) {
None => {
format!("unknown node (id={})", id)
}
Some(&node_item(item, path)) => {
let path_str = path_ident_to_str(path, item.ident, itr);
let item_str = match item.node {
item_static(*) => ~"static",
item_fn(*) => ~"fn",
item_mod(*) => ~"mod",
item_foreign_mod(*) => ~"foreign mod",
item_ty(*) => ~"ty",
item_enum(*) => ~"enum",
item_struct(*) => ~"struct",
item_trait(*) => ~"trait",
item_impl(*) => ~"impl",
item_mac(*) => ~"macro"
};
format!("{} {} (id={})", item_str, path_str, id)
}
Some(&node_foreign_item(item, abi, _, path)) => {
format!("foreign item {} with abi {:?} (id={})",
path_ident_to_str(path, item.ident, itr), abi, id)
}
Some(&node_method(m, _, path)) => {
format!("method {} in {} (id={})",
itr.get(m.ident.name), path_to_str(*path, itr), id)
}
Some(&node_trait_method(ref tm, _, path)) => {
let m = ast_util::trait_method_to_ty_method(&**tm);
format!("method {} in {} (id={})",
itr.get(m.ident.name), path_to_str(*path, itr), id)
}
Some(&node_variant(ref variant, _, path)) => {
format!("variant {} in {} (id={})",
itr.get(variant.node.name.name), path_to_str(*path, itr), id)
}
Some(&node_expr(expr)) => {
format!("expr {} (id={})", pprust::expr_to_str(expr, itr), id)
}
Some(&node_callee_scope(expr)) => {
format!("callee_scope {} (id={})", pprust::expr_to_str(expr, itr), id)
}
Some(&node_stmt(
|
path_elt_to_str
|
identifier_name
|
mod.rs
|
extern crate serde;
extern crate serde_json;
extern crate tera;
use std::io::prelude::*;
use std::fs::File;
use self::tera::Template;
#[derive(Debug)]
pub struct Product {
name: String,
manufacturer: String,
price: i32,
summary: String
}
impl Product {
#[allow(dead_code)]
pub fn new() -> Product {
Product {
name: "Moto G".to_owned(),
manufacturer: "Motorala".to_owned(),
summary: "A phone".to_owned(),
price: 100
}
}
}
// Impl Serialize by hand so tests pass on stable and beta
impl serde::Serialize for Product {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
let mut state = try!(serializer.serialize_struct("Product", 4));
try!(serializer.serialize_struct_elt(&mut state, "name", &self.name));
try!(serializer.serialize_struct_elt(&mut state, "manufacturer", &self.manufacturer));
try!(serializer.serialize_struct_elt(&mut state, "summary", &self.summary));
try!(serializer.serialize_struct_elt(&mut state, "price", &self.price));
serializer.serialize_struct_end(state)
}
}
#[derive(Debug)]
pub struct Review {
title: String,
paragraphs: Vec<String>
}
impl Review {
#[allow(dead_code)]
pub fn new() -> Review
|
}
// Impl Serialize by hand so tests pass on stable and beta
impl serde::Serialize for Review {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
let mut state = try!(serializer.serialize_struct("Review", 2));
try!(serializer.serialize_struct_elt(&mut state, "title", &self.title));
try!(serializer.serialize_struct_elt(&mut state, "paragraphs", &self.paragraphs));
serializer.serialize_struct_end(state)
}
}
#[allow(dead_code)]
pub fn load_template(path: &str) -> Template {
Template::new("tpl", &read_file(path))
}
#[allow(dead_code)]
pub fn read_file(path: &str) -> String {
let mut f = File::open(path).unwrap();
let mut input = String::new();
f.read_to_string(&mut input).unwrap();
input
}
|
{
Review {
title: "My review".to_owned(),
paragraphs: vec![
"A".to_owned(), "B".to_owned(), "C".to_owned()
]
}
}
|
identifier_body
|
mod.rs
|
extern crate serde;
extern crate serde_json;
extern crate tera;
use std::io::prelude::*;
use std::fs::File;
use self::tera::Template;
#[derive(Debug)]
pub struct Product {
name: String,
manufacturer: String,
price: i32,
summary: String
}
impl Product {
#[allow(dead_code)]
pub fn new() -> Product {
Product {
name: "Moto G".to_owned(),
manufacturer: "Motorala".to_owned(),
summary: "A phone".to_owned(),
price: 100
}
}
}
// Impl Serialize by hand so tests pass on stable and beta
impl serde::Serialize for Product {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
let mut state = try!(serializer.serialize_struct("Product", 4));
try!(serializer.serialize_struct_elt(&mut state, "name", &self.name));
try!(serializer.serialize_struct_elt(&mut state, "manufacturer", &self.manufacturer));
try!(serializer.serialize_struct_elt(&mut state, "summary", &self.summary));
try!(serializer.serialize_struct_elt(&mut state, "price", &self.price));
serializer.serialize_struct_end(state)
}
}
#[derive(Debug)]
pub struct Review {
title: String,
paragraphs: Vec<String>
}
impl Review {
#[allow(dead_code)]
pub fn new() -> Review {
Review {
title: "My review".to_owned(),
paragraphs: vec![
"A".to_owned(), "B".to_owned(), "C".to_owned()
|
]
}
}
}
// Impl Serialize by hand so tests pass on stable and beta
impl serde::Serialize for Review {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
let mut state = try!(serializer.serialize_struct("Review", 2));
try!(serializer.serialize_struct_elt(&mut state, "title", &self.title));
try!(serializer.serialize_struct_elt(&mut state, "paragraphs", &self.paragraphs));
serializer.serialize_struct_end(state)
}
}
#[allow(dead_code)]
pub fn load_template(path: &str) -> Template {
Template::new("tpl", &read_file(path))
}
#[allow(dead_code)]
pub fn read_file(path: &str) -> String {
let mut f = File::open(path).unwrap();
let mut input = String::new();
f.read_to_string(&mut input).unwrap();
input
}
|
random_line_split
|
|
mod.rs
|
extern crate serde;
extern crate serde_json;
extern crate tera;
use std::io::prelude::*;
use std::fs::File;
use self::tera::Template;
#[derive(Debug)]
pub struct Product {
name: String,
manufacturer: String,
price: i32,
summary: String
}
impl Product {
#[allow(dead_code)]
pub fn new() -> Product {
Product {
name: "Moto G".to_owned(),
manufacturer: "Motorala".to_owned(),
summary: "A phone".to_owned(),
price: 100
}
}
}
// Impl Serialize by hand so tests pass on stable and beta
impl serde::Serialize for Product {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
let mut state = try!(serializer.serialize_struct("Product", 4));
try!(serializer.serialize_struct_elt(&mut state, "name", &self.name));
try!(serializer.serialize_struct_elt(&mut state, "manufacturer", &self.manufacturer));
try!(serializer.serialize_struct_elt(&mut state, "summary", &self.summary));
try!(serializer.serialize_struct_elt(&mut state, "price", &self.price));
serializer.serialize_struct_end(state)
}
}
#[derive(Debug)]
pub struct Review {
title: String,
paragraphs: Vec<String>
}
impl Review {
#[allow(dead_code)]
pub fn
|
() -> Review {
Review {
title: "My review".to_owned(),
paragraphs: vec![
"A".to_owned(), "B".to_owned(), "C".to_owned()
]
}
}
}
// Impl Serialize by hand so tests pass on stable and beta
impl serde::Serialize for Review {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: serde::Serializer
{
let mut state = try!(serializer.serialize_struct("Review", 2));
try!(serializer.serialize_struct_elt(&mut state, "title", &self.title));
try!(serializer.serialize_struct_elt(&mut state, "paragraphs", &self.paragraphs));
serializer.serialize_struct_end(state)
}
}
#[allow(dead_code)]
pub fn load_template(path: &str) -> Template {
Template::new("tpl", &read_file(path))
}
#[allow(dead_code)]
pub fn read_file(path: &str) -> String {
let mut f = File::open(path).unwrap();
let mut input = String::new();
f.read_to_string(&mut input).unwrap();
input
}
|
new
|
identifier_name
|
maybe_owned_vec.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.
#![deprecated = "use std::vec::CowVec"]
pub use self::MaybeOwnedVector::*;
use std::cmp::Ordering;
use std::default::Default;
use std::fmt;
use std::iter::FromIterator;
use std::path::BytesContainer;
use std::slice;
// Note 1: It is not clear whether the flexibility of providing both
// the `Growable` and `FixedLen` variants is sufficiently useful.
// Consider restricting to just a two variant enum.
// Note 2: Once Dynamically Sized Types (DST) lands, it might be
// reasonable to replace this with something like `enum MaybeOwned<'a,
// U:?Sized>{ Owned(Box<U>), Borrowed(&'a U) }`; and then `U` could be
// instantiated with `[T]` or `str`, etc. Of course, that would imply
// removing the `Growable` variant, which relates to note 1 above.
// Alternatively, we might add `MaybeOwned` for the general case but
// keep some form of `MaybeOwnedVector` to avoid unnecessary copying
// of the contents of `Vec<T>`, since we anticipate that to be a
// frequent way to dynamically construct a vector.
/// MaybeOwnedVector<'a,T> abstracts over `Vec<T>`, `&'a [T]`.
///
/// Some clients will have a pre-allocated vector ready to hand off in
/// a slice; others will want to create the set on the fly and hand
/// off ownership, via `Growable`.
pub enum MaybeOwnedVector<'a,T:'a> {
Growable(Vec<T>),
Borrowed(&'a [T]),
}
/// Trait for moving into a `MaybeOwnedVector`
pub trait IntoMaybeOwnedVector<'a,T> {
/// Moves self into a `MaybeOwnedVector`
fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T>;
}
#[allow(deprecated)]
impl<'a,T:'a> IntoMaybeOwnedVector<'a,T> for Vec<T> {
#[allow(deprecated)]
#[inline]
fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T> { Growable(self) }
}
#[allow(deprecated)]
impl<'a,T> IntoMaybeOwnedVector<'a,T> for &'a [T] {
#[allow(deprecated)]
#[inline]
fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T> { Borrowed(self) }
}
impl<'a,T> MaybeOwnedVector<'a,T> {
pub fn iter(&'a self) -> slice::Iter<'a,T> {
match self {
&Growable(ref v) => v.as_slice().iter(),
&Borrowed(ref v) => v.iter(),
}
}
pub fn len(&self) -> uint { self.as_slice().len() }
#[allow(deprecated)]
pub fn is_empty(&self) -> bool { self.len() == 0 }
}
impl<'a, T: PartialEq> PartialEq for MaybeOwnedVector<'a, T> {
fn eq(&self, other: &MaybeOwnedVector<T>) -> bool {
self.as_slice() == other.as_slice()
}
}
impl<'a, T: Eq> Eq for MaybeOwnedVector<'a, T> {}
impl<'a, T: PartialOrd> PartialOrd for MaybeOwnedVector<'a, T> {
fn partial_cmp(&self, other: &MaybeOwnedVector<T>) -> Option<Ordering> {
self.as_slice().partial_cmp(other.as_slice())
}
}
impl<'a, T: Ord> Ord for MaybeOwnedVector<'a, T> {
fn cmp(&self, other: &MaybeOwnedVector<T>) -> Ordering {
self.as_slice().cmp(other.as_slice())
}
}
// The `Vector` trait is provided in the prelude and is implemented on
// both `&'a [T]` and `Vec<T>`, so it makes sense to try to support it
// seamlessly. The other vector related traits from the prelude do
// not appear to be implemented on both `&'a [T]` and `Vec<T>`. (It
// is possible that this is an oversight in some cases.)
//
// In any case, with `Vector` in place, the client can just use
// `as_slice` if they prefer that over `match`.
impl<'b,T> AsSlice<T> for MaybeOwnedVector<'b,T> {
fn as_slice<'a>(&'a self) -> &'a [T] {
match self {
&Growable(ref v) => v.as_slice(),
&Borrowed(ref v) => v.as_slice(),
}
}
}
impl<'a,T> FromIterator<T> for MaybeOwnedVector<'a,T> {
#[allow(deprecated)]
fn from_iter<I:Iterator<Item=T>>(iterator: I) -> MaybeOwnedVector<'a,T> {
// If we are building from scratch, might as well build the
// most flexible variant.
Growable(iterator.collect())
}
}
impl<'a,T:fmt::Show> fmt::Show for MaybeOwnedVector<'a,T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
|
}
impl<'a, T: Clone> Clone for MaybeOwnedVector<'a, T> {
#[allow(deprecated)]
fn clone(&self) -> MaybeOwnedVector<'a, T> {
match *self {
Growable(ref v) => Growable(v.clone()),
Borrowed(v) => Borrowed(v)
}
}
}
impl<'a, T> Default for MaybeOwnedVector<'a, T> {
#[allow(deprecated)]
fn default() -> MaybeOwnedVector<'a, T> {
Growable(Vec::new())
}
}
impl<'a> BytesContainer for MaybeOwnedVector<'a, u8> {
fn container_as_bytes(&self) -> &[u8] {
self.as_slice()
}
}
impl<'a,T:Clone> MaybeOwnedVector<'a,T> {
/// Convert `self` into a growable `Vec`, not making a copy if possible.
pub fn into_vec(self) -> Vec<T> {
match self {
Growable(v) => v,
Borrowed(v) => v.to_vec(),
}
}
}
|
{
self.as_slice().fmt(f)
}
|
identifier_body
|
maybe_owned_vec.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.
#![deprecated = "use std::vec::CowVec"]
pub use self::MaybeOwnedVector::*;
use std::cmp::Ordering;
use std::default::Default;
use std::fmt;
use std::iter::FromIterator;
use std::path::BytesContainer;
use std::slice;
// Note 1: It is not clear whether the flexibility of providing both
// the `Growable` and `FixedLen` variants is sufficiently useful.
// Consider restricting to just a two variant enum.
// Note 2: Once Dynamically Sized Types (DST) lands, it might be
// reasonable to replace this with something like `enum MaybeOwned<'a,
// U:?Sized>{ Owned(Box<U>), Borrowed(&'a U) }`; and then `U` could be
// instantiated with `[T]` or `str`, etc. Of course, that would imply
// removing the `Growable` variant, which relates to note 1 above.
// Alternatively, we might add `MaybeOwned` for the general case but
// keep some form of `MaybeOwnedVector` to avoid unnecessary copying
// of the contents of `Vec<T>`, since we anticipate that to be a
// frequent way to dynamically construct a vector.
/// MaybeOwnedVector<'a,T> abstracts over `Vec<T>`, `&'a [T]`.
///
/// Some clients will have a pre-allocated vector ready to hand off in
/// a slice; others will want to create the set on the fly and hand
/// off ownership, via `Growable`.
pub enum MaybeOwnedVector<'a,T:'a> {
Growable(Vec<T>),
Borrowed(&'a [T]),
}
/// Trait for moving into a `MaybeOwnedVector`
pub trait IntoMaybeOwnedVector<'a,T> {
/// Moves self into a `MaybeOwnedVector`
fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T>;
}
#[allow(deprecated)]
impl<'a,T:'a> IntoMaybeOwnedVector<'a,T> for Vec<T> {
#[allow(deprecated)]
#[inline]
fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T> { Growable(self) }
}
#[allow(deprecated)]
impl<'a,T> IntoMaybeOwnedVector<'a,T> for &'a [T] {
#[allow(deprecated)]
#[inline]
fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T> { Borrowed(self) }
}
impl<'a,T> MaybeOwnedVector<'a,T> {
pub fn iter(&'a self) -> slice::Iter<'a,T> {
match self {
&Growable(ref v) => v.as_slice().iter(),
&Borrowed(ref v) => v.iter(),
}
}
pub fn len(&self) -> uint { self.as_slice().len() }
|
}
impl<'a, T: PartialEq> PartialEq for MaybeOwnedVector<'a, T> {
fn eq(&self, other: &MaybeOwnedVector<T>) -> bool {
self.as_slice() == other.as_slice()
}
}
impl<'a, T: Eq> Eq for MaybeOwnedVector<'a, T> {}
impl<'a, T: PartialOrd> PartialOrd for MaybeOwnedVector<'a, T> {
fn partial_cmp(&self, other: &MaybeOwnedVector<T>) -> Option<Ordering> {
self.as_slice().partial_cmp(other.as_slice())
}
}
impl<'a, T: Ord> Ord for MaybeOwnedVector<'a, T> {
fn cmp(&self, other: &MaybeOwnedVector<T>) -> Ordering {
self.as_slice().cmp(other.as_slice())
}
}
// The `Vector` trait is provided in the prelude and is implemented on
// both `&'a [T]` and `Vec<T>`, so it makes sense to try to support it
// seamlessly. The other vector related traits from the prelude do
// not appear to be implemented on both `&'a [T]` and `Vec<T>`. (It
// is possible that this is an oversight in some cases.)
//
// In any case, with `Vector` in place, the client can just use
// `as_slice` if they prefer that over `match`.
impl<'b,T> AsSlice<T> for MaybeOwnedVector<'b,T> {
fn as_slice<'a>(&'a self) -> &'a [T] {
match self {
&Growable(ref v) => v.as_slice(),
&Borrowed(ref v) => v.as_slice(),
}
}
}
impl<'a,T> FromIterator<T> for MaybeOwnedVector<'a,T> {
#[allow(deprecated)]
fn from_iter<I:Iterator<Item=T>>(iterator: I) -> MaybeOwnedVector<'a,T> {
// If we are building from scratch, might as well build the
// most flexible variant.
Growable(iterator.collect())
}
}
impl<'a,T:fmt::Show> fmt::Show for MaybeOwnedVector<'a,T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.as_slice().fmt(f)
}
}
impl<'a, T: Clone> Clone for MaybeOwnedVector<'a, T> {
#[allow(deprecated)]
fn clone(&self) -> MaybeOwnedVector<'a, T> {
match *self {
Growable(ref v) => Growable(v.clone()),
Borrowed(v) => Borrowed(v)
}
}
}
impl<'a, T> Default for MaybeOwnedVector<'a, T> {
#[allow(deprecated)]
fn default() -> MaybeOwnedVector<'a, T> {
Growable(Vec::new())
}
}
impl<'a> BytesContainer for MaybeOwnedVector<'a, u8> {
fn container_as_bytes(&self) -> &[u8] {
self.as_slice()
}
}
impl<'a,T:Clone> MaybeOwnedVector<'a,T> {
/// Convert `self` into a growable `Vec`, not making a copy if possible.
pub fn into_vec(self) -> Vec<T> {
match self {
Growable(v) => v,
Borrowed(v) => v.to_vec(),
}
}
}
|
#[allow(deprecated)]
pub fn is_empty(&self) -> bool { self.len() == 0 }
|
random_line_split
|
maybe_owned_vec.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.
#![deprecated = "use std::vec::CowVec"]
pub use self::MaybeOwnedVector::*;
use std::cmp::Ordering;
use std::default::Default;
use std::fmt;
use std::iter::FromIterator;
use std::path::BytesContainer;
use std::slice;
// Note 1: It is not clear whether the flexibility of providing both
// the `Growable` and `FixedLen` variants is sufficiently useful.
// Consider restricting to just a two variant enum.
// Note 2: Once Dynamically Sized Types (DST) lands, it might be
// reasonable to replace this with something like `enum MaybeOwned<'a,
// U:?Sized>{ Owned(Box<U>), Borrowed(&'a U) }`; and then `U` could be
// instantiated with `[T]` or `str`, etc. Of course, that would imply
// removing the `Growable` variant, which relates to note 1 above.
// Alternatively, we might add `MaybeOwned` for the general case but
// keep some form of `MaybeOwnedVector` to avoid unnecessary copying
// of the contents of `Vec<T>`, since we anticipate that to be a
// frequent way to dynamically construct a vector.
/// MaybeOwnedVector<'a,T> abstracts over `Vec<T>`, `&'a [T]`.
///
/// Some clients will have a pre-allocated vector ready to hand off in
/// a slice; others will want to create the set on the fly and hand
/// off ownership, via `Growable`.
pub enum MaybeOwnedVector<'a,T:'a> {
Growable(Vec<T>),
Borrowed(&'a [T]),
}
/// Trait for moving into a `MaybeOwnedVector`
pub trait IntoMaybeOwnedVector<'a,T> {
/// Moves self into a `MaybeOwnedVector`
fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T>;
}
#[allow(deprecated)]
impl<'a,T:'a> IntoMaybeOwnedVector<'a,T> for Vec<T> {
#[allow(deprecated)]
#[inline]
fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T> { Growable(self) }
}
#[allow(deprecated)]
impl<'a,T> IntoMaybeOwnedVector<'a,T> for &'a [T] {
#[allow(deprecated)]
#[inline]
fn into_maybe_owned(self) -> MaybeOwnedVector<'a,T> { Borrowed(self) }
}
impl<'a,T> MaybeOwnedVector<'a,T> {
pub fn
|
(&'a self) -> slice::Iter<'a,T> {
match self {
&Growable(ref v) => v.as_slice().iter(),
&Borrowed(ref v) => v.iter(),
}
}
pub fn len(&self) -> uint { self.as_slice().len() }
#[allow(deprecated)]
pub fn is_empty(&self) -> bool { self.len() == 0 }
}
impl<'a, T: PartialEq> PartialEq for MaybeOwnedVector<'a, T> {
fn eq(&self, other: &MaybeOwnedVector<T>) -> bool {
self.as_slice() == other.as_slice()
}
}
impl<'a, T: Eq> Eq for MaybeOwnedVector<'a, T> {}
impl<'a, T: PartialOrd> PartialOrd for MaybeOwnedVector<'a, T> {
fn partial_cmp(&self, other: &MaybeOwnedVector<T>) -> Option<Ordering> {
self.as_slice().partial_cmp(other.as_slice())
}
}
impl<'a, T: Ord> Ord for MaybeOwnedVector<'a, T> {
fn cmp(&self, other: &MaybeOwnedVector<T>) -> Ordering {
self.as_slice().cmp(other.as_slice())
}
}
// The `Vector` trait is provided in the prelude and is implemented on
// both `&'a [T]` and `Vec<T>`, so it makes sense to try to support it
// seamlessly. The other vector related traits from the prelude do
// not appear to be implemented on both `&'a [T]` and `Vec<T>`. (It
// is possible that this is an oversight in some cases.)
//
// In any case, with `Vector` in place, the client can just use
// `as_slice` if they prefer that over `match`.
impl<'b,T> AsSlice<T> for MaybeOwnedVector<'b,T> {
fn as_slice<'a>(&'a self) -> &'a [T] {
match self {
&Growable(ref v) => v.as_slice(),
&Borrowed(ref v) => v.as_slice(),
}
}
}
impl<'a,T> FromIterator<T> for MaybeOwnedVector<'a,T> {
#[allow(deprecated)]
fn from_iter<I:Iterator<Item=T>>(iterator: I) -> MaybeOwnedVector<'a,T> {
// If we are building from scratch, might as well build the
// most flexible variant.
Growable(iterator.collect())
}
}
impl<'a,T:fmt::Show> fmt::Show for MaybeOwnedVector<'a,T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.as_slice().fmt(f)
}
}
impl<'a, T: Clone> Clone for MaybeOwnedVector<'a, T> {
#[allow(deprecated)]
fn clone(&self) -> MaybeOwnedVector<'a, T> {
match *self {
Growable(ref v) => Growable(v.clone()),
Borrowed(v) => Borrowed(v)
}
}
}
impl<'a, T> Default for MaybeOwnedVector<'a, T> {
#[allow(deprecated)]
fn default() -> MaybeOwnedVector<'a, T> {
Growable(Vec::new())
}
}
impl<'a> BytesContainer for MaybeOwnedVector<'a, u8> {
fn container_as_bytes(&self) -> &[u8] {
self.as_slice()
}
}
impl<'a,T:Clone> MaybeOwnedVector<'a,T> {
/// Convert `self` into a growable `Vec`, not making a copy if possible.
pub fn into_vec(self) -> Vec<T> {
match self {
Growable(v) => v,
Borrowed(v) => v.to_vec(),
}
}
}
|
iter
|
identifier_name
|
p2d.rs
|
use super::vector::Vector;
#[derive(Debug, Copy, Clone)]
pub struct P2d(pub f32, pub f32);
impl Vector for P2d {
type Scalar = f32;
fn new() -> Self {
P2d(0.0, 0.0)
}
|
fn reset(&mut self) {
self.0 = 0.0;
self.1 = 0.0;
}
fn scale(&self, factor: f32) -> Self {
P2d(self.0 * factor, self.1 * factor)
}
fn sub(&self, other: &Self) -> Self {
P2d(self.0 - other.0, self.1 - other.1)
}
fn add_scaled(&mut self, factor: f32, other: &P2d) {
self.0 += factor * other.0;
self.1 += factor * other.1;
}
fn clip_within(&self, min: &Self, max: &Self) -> Self {
P2d(if self.0 < min.0 {
min.0
} else if self.0 > max.0 {
max.0
} else {
self.0
},
if self.1 < min.1 {
min.1
} else if self.1 > max.1 {
max.1
} else {
self.1
})
}
}
|
fn length_squared(&self) -> f32 {
self.0 * self.0 + self.1 * self.1
}
|
random_line_split
|
p2d.rs
|
use super::vector::Vector;
#[derive(Debug, Copy, Clone)]
pub struct P2d(pub f32, pub f32);
impl Vector for P2d {
type Scalar = f32;
fn new() -> Self {
P2d(0.0, 0.0)
}
fn length_squared(&self) -> f32 {
self.0 * self.0 + self.1 * self.1
}
fn reset(&mut self) {
self.0 = 0.0;
self.1 = 0.0;
}
fn scale(&self, factor: f32) -> Self {
P2d(self.0 * factor, self.1 * factor)
}
fn
|
(&self, other: &Self) -> Self {
P2d(self.0 - other.0, self.1 - other.1)
}
fn add_scaled(&mut self, factor: f32, other: &P2d) {
self.0 += factor * other.0;
self.1 += factor * other.1;
}
fn clip_within(&self, min: &Self, max: &Self) -> Self {
P2d(if self.0 < min.0 {
min.0
} else if self.0 > max.0 {
max.0
} else {
self.0
},
if self.1 < min.1 {
min.1
} else if self.1 > max.1 {
max.1
} else {
self.1
})
}
}
|
sub
|
identifier_name
|
p2d.rs
|
use super::vector::Vector;
#[derive(Debug, Copy, Clone)]
pub struct P2d(pub f32, pub f32);
impl Vector for P2d {
type Scalar = f32;
fn new() -> Self {
P2d(0.0, 0.0)
}
fn length_squared(&self) -> f32 {
self.0 * self.0 + self.1 * self.1
}
fn reset(&mut self)
|
fn scale(&self, factor: f32) -> Self {
P2d(self.0 * factor, self.1 * factor)
}
fn sub(&self, other: &Self) -> Self {
P2d(self.0 - other.0, self.1 - other.1)
}
fn add_scaled(&mut self, factor: f32, other: &P2d) {
self.0 += factor * other.0;
self.1 += factor * other.1;
}
fn clip_within(&self, min: &Self, max: &Self) -> Self {
P2d(if self.0 < min.0 {
min.0
} else if self.0 > max.0 {
max.0
} else {
self.0
},
if self.1 < min.1 {
min.1
} else if self.1 > max.1 {
max.1
} else {
self.1
})
}
}
|
{
self.0 = 0.0;
self.1 = 0.0;
}
|
identifier_body
|
set_statement.rs
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
use crate::ast::SetStatement;
use crate::lexer::TokenType;
use crate::parser::Parser;
pub fn parse(parser: &mut Parser) -> Option<SetStatement> {
let option = parser.expect_identifier()?;
if parser.peek_token().token_type!= TokenType::Assign {
parser.expect_end_of_statement()?;
return Some(SetStatement {
option: option,
value: None,
});
}
parser.advance();
let value = parser.expect_identifier()?;
return Some(SetStatement {
|
#[cfg(test)]
mod tests {
use super::*;
use crate::lexer::Lexer;
use pretty_assertions::assert_eq;
use serde_json::json;
use serde_json::Value;
#[test]
fn parses_set_statement() {
let mut parser = Parser::new(Lexer::new("set paste"));
let program = parser.parse();
assert_eq!(parser.errors, &[]);
assert_eq!(
program.dump_for_testing(),
json!([{"set": {"option": "paste", "value": Value::Null}}])
);
}
#[test]
fn parses_set_statement_with_value() {
let mut parser = Parser::new(Lexer::new("set selection=exclusive"));
let program = parser.parse();
assert_eq!(parser.errors, &[]);
assert_eq!(
program.dump_for_testing(),
json!([{"set": {"option": "selection", "value": "exclusive"}}])
);
}
}
|
option: option,
value: Some(value),
});
}
|
random_line_split
|
set_statement.rs
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
use crate::ast::SetStatement;
use crate::lexer::TokenType;
use crate::parser::Parser;
pub fn
|
(parser: &mut Parser) -> Option<SetStatement> {
let option = parser.expect_identifier()?;
if parser.peek_token().token_type!= TokenType::Assign {
parser.expect_end_of_statement()?;
return Some(SetStatement {
option: option,
value: None,
});
}
parser.advance();
let value = parser.expect_identifier()?;
return Some(SetStatement {
option: option,
value: Some(value),
});
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lexer::Lexer;
use pretty_assertions::assert_eq;
use serde_json::json;
use serde_json::Value;
#[test]
fn parses_set_statement() {
let mut parser = Parser::new(Lexer::new("set paste"));
let program = parser.parse();
assert_eq!(parser.errors, &[]);
assert_eq!(
program.dump_for_testing(),
json!([{"set": {"option": "paste", "value": Value::Null}}])
);
}
#[test]
fn parses_set_statement_with_value() {
let mut parser = Parser::new(Lexer::new("set selection=exclusive"));
let program = parser.parse();
assert_eq!(parser.errors, &[]);
assert_eq!(
program.dump_for_testing(),
json!([{"set": {"option": "selection", "value": "exclusive"}}])
);
}
}
|
parse
|
identifier_name
|
set_statement.rs
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
use crate::ast::SetStatement;
use crate::lexer::TokenType;
use crate::parser::Parser;
pub fn parse(parser: &mut Parser) -> Option<SetStatement> {
let option = parser.expect_identifier()?;
if parser.peek_token().token_type!= TokenType::Assign {
parser.expect_end_of_statement()?;
return Some(SetStatement {
option: option,
value: None,
});
}
parser.advance();
let value = parser.expect_identifier()?;
return Some(SetStatement {
option: option,
value: Some(value),
});
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lexer::Lexer;
use pretty_assertions::assert_eq;
use serde_json::json;
use serde_json::Value;
#[test]
fn parses_set_statement() {
let mut parser = Parser::new(Lexer::new("set paste"));
let program = parser.parse();
assert_eq!(parser.errors, &[]);
assert_eq!(
program.dump_for_testing(),
json!([{"set": {"option": "paste", "value": Value::Null}}])
);
}
#[test]
fn parses_set_statement_with_value()
|
}
|
{
let mut parser = Parser::new(Lexer::new("set selection=exclusive"));
let program = parser.parse();
assert_eq!(parser.errors, &[]);
assert_eq!(
program.dump_for_testing(),
json!([{"set": {"option": "selection", "value": "exclusive"}}])
);
}
|
identifier_body
|
set_statement.rs
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
use crate::ast::SetStatement;
use crate::lexer::TokenType;
use crate::parser::Parser;
pub fn parse(parser: &mut Parser) -> Option<SetStatement> {
let option = parser.expect_identifier()?;
if parser.peek_token().token_type!= TokenType::Assign
|
parser.advance();
let value = parser.expect_identifier()?;
return Some(SetStatement {
option: option,
value: Some(value),
});
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lexer::Lexer;
use pretty_assertions::assert_eq;
use serde_json::json;
use serde_json::Value;
#[test]
fn parses_set_statement() {
let mut parser = Parser::new(Lexer::new("set paste"));
let program = parser.parse();
assert_eq!(parser.errors, &[]);
assert_eq!(
program.dump_for_testing(),
json!([{"set": {"option": "paste", "value": Value::Null}}])
);
}
#[test]
fn parses_set_statement_with_value() {
let mut parser = Parser::new(Lexer::new("set selection=exclusive"));
let program = parser.parse();
assert_eq!(parser.errors, &[]);
assert_eq!(
program.dump_for_testing(),
json!([{"set": {"option": "selection", "value": "exclusive"}}])
);
}
}
|
{
parser.expect_end_of_statement()?;
return Some(SetStatement {
option: option,
value: None,
});
}
|
conditional_block
|
main.rs
|
// Copyright 2015 Virgil Dupras
//
// This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
// which should be included with this package. The terms are also available at
// http://www.gnu.org/licenses/gpl-3.0.html
//
use std::path::Path;
use civng::game::Game;
use civng::unit::{Unit, UnitType, Player};
use civng::hexpos::{Pos, OffsetPos};
extern crate rustty;
extern crate civng;
fn
|
() {
let mut game = Game::new(Path::new("resources/pangea-duel.Civ5Map"));
let unitpos = game.map().first_passable(Pos::origin());
let _ = game.add_unit(Unit::new(UnitType::Melee, Player::Me, unitpos));
let unitpos = game.map().first_passable(Pos::origin());
let _ = game.add_unit(Unit::new(UnitType::Ranged, Player::Me, unitpos));
let unitpos = game.map().first_passable(OffsetPos::new(4, 3).to_pos());
let _ = game.add_unit(Unit::new(UnitType::Melee, Player::NotMe, unitpos));
let unitpos = game.map().first_passable(OffsetPos::new(4, 3).to_pos());
let _ = game.add_unit(Unit::new(UnitType::Melee, Player::NotMe, unitpos));
game.new_turn();
loop {
game.draw();
if!game.handle_events() {
break;
}
}
}
|
main
|
identifier_name
|
main.rs
|
// Copyright 2015 Virgil Dupras
//
// This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
// which should be included with this package. The terms are also available at
// http://www.gnu.org/licenses/gpl-3.0.html
//
use std::path::Path;
use civng::game::Game;
use civng::unit::{Unit, UnitType, Player};
use civng::hexpos::{Pos, OffsetPos};
extern crate rustty;
extern crate civng;
fn main() {
let mut game = Game::new(Path::new("resources/pangea-duel.Civ5Map"));
let unitpos = game.map().first_passable(Pos::origin());
let _ = game.add_unit(Unit::new(UnitType::Melee, Player::Me, unitpos));
let unitpos = game.map().first_passable(Pos::origin());
let _ = game.add_unit(Unit::new(UnitType::Ranged, Player::Me, unitpos));
let unitpos = game.map().first_passable(OffsetPos::new(4, 3).to_pos());
let _ = game.add_unit(Unit::new(UnitType::Melee, Player::NotMe, unitpos));
let unitpos = game.map().first_passable(OffsetPos::new(4, 3).to_pos());
let _ = game.add_unit(Unit::new(UnitType::Melee, Player::NotMe, unitpos));
game.new_turn();
loop {
game.draw();
if!game.handle_events() {
|
break;
}
}
}
|
random_line_split
|
|
main.rs
|
// Copyright 2015 Virgil Dupras
//
// This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
// which should be included with this package. The terms are also available at
// http://www.gnu.org/licenses/gpl-3.0.html
//
use std::path::Path;
use civng::game::Game;
use civng::unit::{Unit, UnitType, Player};
use civng::hexpos::{Pos, OffsetPos};
extern crate rustty;
extern crate civng;
fn main()
|
{
let mut game = Game::new(Path::new("resources/pangea-duel.Civ5Map"));
let unitpos = game.map().first_passable(Pos::origin());
let _ = game.add_unit(Unit::new(UnitType::Melee, Player::Me, unitpos));
let unitpos = game.map().first_passable(Pos::origin());
let _ = game.add_unit(Unit::new(UnitType::Ranged, Player::Me, unitpos));
let unitpos = game.map().first_passable(OffsetPos::new(4, 3).to_pos());
let _ = game.add_unit(Unit::new(UnitType::Melee, Player::NotMe, unitpos));
let unitpos = game.map().first_passable(OffsetPos::new(4, 3).to_pos());
let _ = game.add_unit(Unit::new(UnitType::Melee, Player::NotMe, unitpos));
game.new_turn();
loop {
game.draw();
if !game.handle_events() {
break;
}
}
}
|
identifier_body
|
|
main.rs
|
// Copyright 2015 Virgil Dupras
//
// This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
// which should be included with this package. The terms are also available at
// http://www.gnu.org/licenses/gpl-3.0.html
//
use std::path::Path;
use civng::game::Game;
use civng::unit::{Unit, UnitType, Player};
use civng::hexpos::{Pos, OffsetPos};
extern crate rustty;
extern crate civng;
fn main() {
let mut game = Game::new(Path::new("resources/pangea-duel.Civ5Map"));
let unitpos = game.map().first_passable(Pos::origin());
let _ = game.add_unit(Unit::new(UnitType::Melee, Player::Me, unitpos));
let unitpos = game.map().first_passable(Pos::origin());
let _ = game.add_unit(Unit::new(UnitType::Ranged, Player::Me, unitpos));
let unitpos = game.map().first_passable(OffsetPos::new(4, 3).to_pos());
let _ = game.add_unit(Unit::new(UnitType::Melee, Player::NotMe, unitpos));
let unitpos = game.map().first_passable(OffsetPos::new(4, 3).to_pos());
let _ = game.add_unit(Unit::new(UnitType::Melee, Player::NotMe, unitpos));
game.new_turn();
loop {
game.draw();
if!game.handle_events()
|
}
}
|
{
break;
}
|
conditional_block
|
mod.rs
|
use cursive::{self, views, Cursive};
use cursive::traits::{Boxable, Identifiable};
use fchat::{self, Ticket};
use chrono::{self, Timelike};
use futures::sync::mpsc::UnboundedSender;
use std;
use std::thread::spawn;
use std::sync::mpsc::{channel, Receiver, Sender};
use io;
pub enum Event {
ReceivedMessage(fchat::message::server::Message),
TextInput(String),
}
enum State {
Start,
Login(Receiver<(Ticket, String)>),
Connecting,
Connected,
Disconnected,
Quit,
}
struct Controller {
is_running: bool,
state: State,
siv: Cursive,
net_tx: UnboundedSender<io::Event>,
event_tx: Sender<Event>,
event_rx: Receiver<Event>,
}
impl Controller {
fn new(
net_tx: UnboundedSender<io::Event>,
event_tx: Sender<Event>,
event_rx: Receiver<Event>,
) -> Controller {
let mut siv = cursive::Cursive::new();
siv.set_fps(30);
Controller {
is_running: true,
siv,
net_tx,
event_tx,
event_rx,
state: State::Start,
}
}
fn step(&mut self) {
use std::sync::mpsc::TryRecvError;
let mut next_state = None;
match self.state {
State::Start => {
let (login_tx, login_rx) = channel();
self.siv.add_layer(login_dialog(login_tx));
next_state = Some(State::Login(login_rx));
}
State::Login(ref login_rx) => match login_rx.try_recv() {
Ok((ticket, character)) => {
self.net_tx
.unbounded_send(io::Event::Connect {
ticket,
character,
server: fchat::Server::Debug,
})
.unwrap();
next_state = Some(State::Connecting);
}
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => {
panic!("ui login_rx disconnected");
}
},
State::Connecting => {
std::thread::sleep(std::time::Duration::from_secs(5));
let message = fchat::message::client::Message::JCH {
channel: String::from("Development"),
};
self.net_tx
.unbounded_send(io::Event::SendMessage(message))
.unwrap();
debug_view(&mut self.siv, self.event_tx.clone());
next_state = Some(State::Connected);
}
State::Connected => match self.event_rx.try_recv() {
Ok(Event::ReceivedMessage(message)) => {
debug_message(&mut self.siv, message);
}
Ok(Event::TextInput(text)) => {
let message = fchat::message::client::Message::MSG {
channel: String::from("Development"),
message: text.clone(),
};
self.net_tx
.unbounded_send(io::Event::SendMessage(message))
.unwrap();
debug_message(&mut self.siv, text);
}
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => {
panic!("ui event_rx disconnected");
}
},
State::Disconnected => {
panic!("State::Disconnected");
}
State::Quit => {
self.is_running = false;
}
}
if let Some(state) = next_state
|
self.siv.step();
}
fn is_running(&self) -> bool {
self.is_running
}
}
pub fn login_dialog(result: Sender<(Ticket, String)>) -> views::Dialog {
use cursive::view::{Boxable, Identifiable};
let username = views::LinearLayout::horizontal()
.child(views::TextView::new("Username"))
.child(views::DummyView)
.child(views::EditView::new().with_id("username").min_width(30));
let password = views::LinearLayout::horizontal()
.child(views::TextView::new("Password"))
.child(views::DummyView)
.child(
views::EditView::new()
.secret()
.with_id("password")
.min_width(30),
);
let inputs = views::LinearLayout::vertical()
.child(username)
.child(password);
views::Dialog::around(inputs)
.button("Login", move |siv| select_character(siv, result.clone()))
.button("Quit", |siv| siv.quit())
}
fn select_character(siv: &mut Cursive, result: Sender<(Ticket, String)>) {
let username = siv.call_on_id("username", |text: &mut views::EditView| text.get_content())
.expect("Failed to find ID \"username\"");
let password = siv.call_on_id("password", |text: &mut views::EditView| text.get_content())
.expect("Failed to find ID \"password\"");
let ticket = Ticket::request(&username, &password).unwrap();
siv.pop_layer();
let mut characters = views::SelectView::new();
characters.add_all_str(ticket.characters().iter().cloned());
characters.set_on_submit::<_, (), str>(move |siv, character| {
result
.send((ticket.clone(), String::from(character)))
.unwrap();
siv.pop_layer();
});
siv.add_layer(characters);
}
fn debug_view(siv: &mut Cursive, event_tx: Sender<Event>) {
let textview = views::TextView::empty()
.scroll_strategy(cursive::view::ScrollStrategy::StickToBottom)
.with_id("debug_view")
.full_screen();
let input = views::EditView::new()
.on_submit(move |siv, text| {
event_tx.send(Event::TextInput(String::from(text))).unwrap();
siv.call_on_id("input", |input: &mut views::EditView| input.set_content(""));
})
.with_id("input");
let layer = views::LinearLayout::vertical()
.child(textview)
.child(input)
.full_screen();
siv.add_layer(layer);
}
fn debug_message<M: std::fmt::Debug>(siv: &mut Cursive, message: M) {
siv.call_on_id("debug_view", |view: &mut views::TextView| {
let now = chrono::Local::now();
let hour = now.hour();
let minute = now.minute();
let second = now.second();
view.append(format!(
"[{:02}:{:02}:{:02}] {:?}\n",
hour, minute, second, message
));
});
}
pub fn start(net_tx: UnboundedSender<io::Event>) -> Sender<Event> {
let (event_tx, event_rx) = std::sync::mpsc::channel();
let event_tx2 = event_tx.clone();
spawn(move || {
let mut controller = Controller::new(net_tx, event_tx, event_rx);
while controller.is_running() {
controller.step();
}
});
event_tx2
}
|
{
self.state = state;
}
|
conditional_block
|
mod.rs
|
use cursive::{self, views, Cursive};
use cursive::traits::{Boxable, Identifiable};
use fchat::{self, Ticket};
use chrono::{self, Timelike};
use futures::sync::mpsc::UnboundedSender;
use std;
use std::thread::spawn;
use std::sync::mpsc::{channel, Receiver, Sender};
use io;
pub enum Event {
ReceivedMessage(fchat::message::server::Message),
TextInput(String),
}
enum State {
Start,
Login(Receiver<(Ticket, String)>),
Connecting,
Connected,
Disconnected,
Quit,
}
struct Controller {
is_running: bool,
state: State,
siv: Cursive,
net_tx: UnboundedSender<io::Event>,
event_tx: Sender<Event>,
event_rx: Receiver<Event>,
}
impl Controller {
fn new(
net_tx: UnboundedSender<io::Event>,
event_tx: Sender<Event>,
event_rx: Receiver<Event>,
) -> Controller {
let mut siv = cursive::Cursive::new();
siv.set_fps(30);
Controller {
is_running: true,
siv,
net_tx,
event_tx,
event_rx,
state: State::Start,
}
}
fn
|
(&mut self) {
use std::sync::mpsc::TryRecvError;
let mut next_state = None;
match self.state {
State::Start => {
let (login_tx, login_rx) = channel();
self.siv.add_layer(login_dialog(login_tx));
next_state = Some(State::Login(login_rx));
}
State::Login(ref login_rx) => match login_rx.try_recv() {
Ok((ticket, character)) => {
self.net_tx
.unbounded_send(io::Event::Connect {
ticket,
character,
server: fchat::Server::Debug,
})
.unwrap();
next_state = Some(State::Connecting);
}
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => {
panic!("ui login_rx disconnected");
}
},
State::Connecting => {
std::thread::sleep(std::time::Duration::from_secs(5));
let message = fchat::message::client::Message::JCH {
channel: String::from("Development"),
};
self.net_tx
.unbounded_send(io::Event::SendMessage(message))
.unwrap();
debug_view(&mut self.siv, self.event_tx.clone());
next_state = Some(State::Connected);
}
State::Connected => match self.event_rx.try_recv() {
Ok(Event::ReceivedMessage(message)) => {
debug_message(&mut self.siv, message);
}
Ok(Event::TextInput(text)) => {
let message = fchat::message::client::Message::MSG {
channel: String::from("Development"),
message: text.clone(),
};
self.net_tx
.unbounded_send(io::Event::SendMessage(message))
.unwrap();
debug_message(&mut self.siv, text);
}
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => {
panic!("ui event_rx disconnected");
}
},
State::Disconnected => {
panic!("State::Disconnected");
}
State::Quit => {
self.is_running = false;
}
}
if let Some(state) = next_state {
self.state = state;
}
self.siv.step();
}
fn is_running(&self) -> bool {
self.is_running
}
}
pub fn login_dialog(result: Sender<(Ticket, String)>) -> views::Dialog {
use cursive::view::{Boxable, Identifiable};
let username = views::LinearLayout::horizontal()
.child(views::TextView::new("Username"))
.child(views::DummyView)
.child(views::EditView::new().with_id("username").min_width(30));
let password = views::LinearLayout::horizontal()
.child(views::TextView::new("Password"))
.child(views::DummyView)
.child(
views::EditView::new()
.secret()
.with_id("password")
.min_width(30),
);
let inputs = views::LinearLayout::vertical()
.child(username)
.child(password);
views::Dialog::around(inputs)
.button("Login", move |siv| select_character(siv, result.clone()))
.button("Quit", |siv| siv.quit())
}
fn select_character(siv: &mut Cursive, result: Sender<(Ticket, String)>) {
let username = siv.call_on_id("username", |text: &mut views::EditView| text.get_content())
.expect("Failed to find ID \"username\"");
let password = siv.call_on_id("password", |text: &mut views::EditView| text.get_content())
.expect("Failed to find ID \"password\"");
let ticket = Ticket::request(&username, &password).unwrap();
siv.pop_layer();
let mut characters = views::SelectView::new();
characters.add_all_str(ticket.characters().iter().cloned());
characters.set_on_submit::<_, (), str>(move |siv, character| {
result
.send((ticket.clone(), String::from(character)))
.unwrap();
siv.pop_layer();
});
siv.add_layer(characters);
}
fn debug_view(siv: &mut Cursive, event_tx: Sender<Event>) {
let textview = views::TextView::empty()
.scroll_strategy(cursive::view::ScrollStrategy::StickToBottom)
.with_id("debug_view")
.full_screen();
let input = views::EditView::new()
.on_submit(move |siv, text| {
event_tx.send(Event::TextInput(String::from(text))).unwrap();
siv.call_on_id("input", |input: &mut views::EditView| input.set_content(""));
})
.with_id("input");
let layer = views::LinearLayout::vertical()
.child(textview)
.child(input)
.full_screen();
siv.add_layer(layer);
}
fn debug_message<M: std::fmt::Debug>(siv: &mut Cursive, message: M) {
siv.call_on_id("debug_view", |view: &mut views::TextView| {
let now = chrono::Local::now();
let hour = now.hour();
let minute = now.minute();
let second = now.second();
view.append(format!(
"[{:02}:{:02}:{:02}] {:?}\n",
hour, minute, second, message
));
});
}
pub fn start(net_tx: UnboundedSender<io::Event>) -> Sender<Event> {
let (event_tx, event_rx) = std::sync::mpsc::channel();
let event_tx2 = event_tx.clone();
spawn(move || {
let mut controller = Controller::new(net_tx, event_tx, event_rx);
while controller.is_running() {
controller.step();
}
});
event_tx2
}
|
step
|
identifier_name
|
mod.rs
|
use cursive::{self, views, Cursive};
use cursive::traits::{Boxable, Identifiable};
use fchat::{self, Ticket};
use chrono::{self, Timelike};
use futures::sync::mpsc::UnboundedSender;
use std;
use std::thread::spawn;
use std::sync::mpsc::{channel, Receiver, Sender};
use io;
pub enum Event {
ReceivedMessage(fchat::message::server::Message),
TextInput(String),
}
enum State {
Start,
Login(Receiver<(Ticket, String)>),
Connecting,
Connected,
Disconnected,
Quit,
}
struct Controller {
is_running: bool,
state: State,
siv: Cursive,
net_tx: UnboundedSender<io::Event>,
event_tx: Sender<Event>,
event_rx: Receiver<Event>,
}
impl Controller {
fn new(
net_tx: UnboundedSender<io::Event>,
event_tx: Sender<Event>,
event_rx: Receiver<Event>,
) -> Controller {
let mut siv = cursive::Cursive::new();
siv.set_fps(30);
Controller {
is_running: true,
siv,
net_tx,
event_tx,
event_rx,
state: State::Start,
}
}
fn step(&mut self) {
use std::sync::mpsc::TryRecvError;
let mut next_state = None;
match self.state {
State::Start => {
let (login_tx, login_rx) = channel();
self.siv.add_layer(login_dialog(login_tx));
next_state = Some(State::Login(login_rx));
}
State::Login(ref login_rx) => match login_rx.try_recv() {
Ok((ticket, character)) => {
self.net_tx
.unbounded_send(io::Event::Connect {
ticket,
character,
server: fchat::Server::Debug,
})
.unwrap();
next_state = Some(State::Connecting);
}
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => {
panic!("ui login_rx disconnected");
}
},
State::Connecting => {
std::thread::sleep(std::time::Duration::from_secs(5));
let message = fchat::message::client::Message::JCH {
channel: String::from("Development"),
};
self.net_tx
.unbounded_send(io::Event::SendMessage(message))
.unwrap();
debug_view(&mut self.siv, self.event_tx.clone());
next_state = Some(State::Connected);
}
State::Connected => match self.event_rx.try_recv() {
Ok(Event::ReceivedMessage(message)) => {
debug_message(&mut self.siv, message);
}
Ok(Event::TextInput(text)) => {
let message = fchat::message::client::Message::MSG {
channel: String::from("Development"),
message: text.clone(),
};
self.net_tx
.unbounded_send(io::Event::SendMessage(message))
.unwrap();
debug_message(&mut self.siv, text);
}
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => {
panic!("ui event_rx disconnected");
}
},
State::Disconnected => {
panic!("State::Disconnected");
}
State::Quit => {
self.is_running = false;
}
}
if let Some(state) = next_state {
self.state = state;
}
self.siv.step();
}
fn is_running(&self) -> bool {
self.is_running
}
}
pub fn login_dialog(result: Sender<(Ticket, String)>) -> views::Dialog {
use cursive::view::{Boxable, Identifiable};
let username = views::LinearLayout::horizontal()
.child(views::TextView::new("Username"))
.child(views::DummyView)
.child(views::EditView::new().with_id("username").min_width(30));
let password = views::LinearLayout::horizontal()
.child(views::TextView::new("Password"))
.child(views::DummyView)
.child(
views::EditView::new()
.secret()
.with_id("password")
.min_width(30),
);
let inputs = views::LinearLayout::vertical()
.child(username)
.child(password);
views::Dialog::around(inputs)
.button("Login", move |siv| select_character(siv, result.clone()))
.button("Quit", |siv| siv.quit())
}
fn select_character(siv: &mut Cursive, result: Sender<(Ticket, String)>) {
let username = siv.call_on_id("username", |text: &mut views::EditView| text.get_content())
.expect("Failed to find ID \"username\"");
let password = siv.call_on_id("password", |text: &mut views::EditView| text.get_content())
.expect("Failed to find ID \"password\"");
let ticket = Ticket::request(&username, &password).unwrap();
siv.pop_layer();
let mut characters = views::SelectView::new();
characters.add_all_str(ticket.characters().iter().cloned());
characters.set_on_submit::<_, (), str>(move |siv, character| {
result
.send((ticket.clone(), String::from(character)))
.unwrap();
siv.pop_layer();
});
siv.add_layer(characters);
}
fn debug_view(siv: &mut Cursive, event_tx: Sender<Event>)
|
fn debug_message<M: std::fmt::Debug>(siv: &mut Cursive, message: M) {
siv.call_on_id("debug_view", |view: &mut views::TextView| {
let now = chrono::Local::now();
let hour = now.hour();
let minute = now.minute();
let second = now.second();
view.append(format!(
"[{:02}:{:02}:{:02}] {:?}\n",
hour, minute, second, message
));
});
}
pub fn start(net_tx: UnboundedSender<io::Event>) -> Sender<Event> {
let (event_tx, event_rx) = std::sync::mpsc::channel();
let event_tx2 = event_tx.clone();
spawn(move || {
let mut controller = Controller::new(net_tx, event_tx, event_rx);
while controller.is_running() {
controller.step();
}
});
event_tx2
}
|
{
let textview = views::TextView::empty()
.scroll_strategy(cursive::view::ScrollStrategy::StickToBottom)
.with_id("debug_view")
.full_screen();
let input = views::EditView::new()
.on_submit(move |siv, text| {
event_tx.send(Event::TextInput(String::from(text))).unwrap();
siv.call_on_id("input", |input: &mut views::EditView| input.set_content(""));
})
.with_id("input");
let layer = views::LinearLayout::vertical()
.child(textview)
.child(input)
.full_screen();
siv.add_layer(layer);
}
|
identifier_body
|
mod.rs
|
use cursive::{self, views, Cursive};
use cursive::traits::{Boxable, Identifiable};
use fchat::{self, Ticket};
use chrono::{self, Timelike};
use futures::sync::mpsc::UnboundedSender;
use std;
use std::thread::spawn;
use std::sync::mpsc::{channel, Receiver, Sender};
use io;
pub enum Event {
ReceivedMessage(fchat::message::server::Message),
TextInput(String),
}
enum State {
Start,
Login(Receiver<(Ticket, String)>),
Connecting,
Connected,
Disconnected,
Quit,
}
struct Controller {
is_running: bool,
state: State,
siv: Cursive,
net_tx: UnboundedSender<io::Event>,
event_tx: Sender<Event>,
event_rx: Receiver<Event>,
}
impl Controller {
fn new(
net_tx: UnboundedSender<io::Event>,
event_tx: Sender<Event>,
event_rx: Receiver<Event>,
) -> Controller {
let mut siv = cursive::Cursive::new();
siv.set_fps(30);
Controller {
is_running: true,
siv,
net_tx,
event_tx,
event_rx,
state: State::Start,
}
}
fn step(&mut self) {
use std::sync::mpsc::TryRecvError;
let mut next_state = None;
match self.state {
State::Start => {
let (login_tx, login_rx) = channel();
self.siv.add_layer(login_dialog(login_tx));
next_state = Some(State::Login(login_rx));
}
State::Login(ref login_rx) => match login_rx.try_recv() {
Ok((ticket, character)) => {
self.net_tx
.unbounded_send(io::Event::Connect {
ticket,
character,
server: fchat::Server::Debug,
})
.unwrap();
next_state = Some(State::Connecting);
}
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => {
panic!("ui login_rx disconnected");
}
},
State::Connecting => {
std::thread::sleep(std::time::Duration::from_secs(5));
let message = fchat::message::client::Message::JCH {
channel: String::from("Development"),
};
self.net_tx
.unbounded_send(io::Event::SendMessage(message))
.unwrap();
debug_view(&mut self.siv, self.event_tx.clone());
next_state = Some(State::Connected);
}
State::Connected => match self.event_rx.try_recv() {
Ok(Event::ReceivedMessage(message)) => {
debug_message(&mut self.siv, message);
}
Ok(Event::TextInput(text)) => {
let message = fchat::message::client::Message::MSG {
channel: String::from("Development"),
message: text.clone(),
};
self.net_tx
.unbounded_send(io::Event::SendMessage(message))
.unwrap();
debug_message(&mut self.siv, text);
}
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => {
panic!("ui event_rx disconnected");
}
},
State::Disconnected => {
panic!("State::Disconnected");
}
State::Quit => {
self.is_running = false;
}
}
if let Some(state) = next_state {
self.state = state;
}
self.siv.step();
}
fn is_running(&self) -> bool {
self.is_running
}
}
pub fn login_dialog(result: Sender<(Ticket, String)>) -> views::Dialog {
use cursive::view::{Boxable, Identifiable};
let username = views::LinearLayout::horizontal()
.child(views::TextView::new("Username"))
.child(views::DummyView)
.child(views::EditView::new().with_id("username").min_width(30));
let password = views::LinearLayout::horizontal()
.child(views::TextView::new("Password"))
.child(views::DummyView)
.child(
views::EditView::new()
.secret()
.with_id("password")
.min_width(30),
);
let inputs = views::LinearLayout::vertical()
.child(username)
|
.button("Login", move |siv| select_character(siv, result.clone()))
.button("Quit", |siv| siv.quit())
}
fn select_character(siv: &mut Cursive, result: Sender<(Ticket, String)>) {
let username = siv.call_on_id("username", |text: &mut views::EditView| text.get_content())
.expect("Failed to find ID \"username\"");
let password = siv.call_on_id("password", |text: &mut views::EditView| text.get_content())
.expect("Failed to find ID \"password\"");
let ticket = Ticket::request(&username, &password).unwrap();
siv.pop_layer();
let mut characters = views::SelectView::new();
characters.add_all_str(ticket.characters().iter().cloned());
characters.set_on_submit::<_, (), str>(move |siv, character| {
result
.send((ticket.clone(), String::from(character)))
.unwrap();
siv.pop_layer();
});
siv.add_layer(characters);
}
fn debug_view(siv: &mut Cursive, event_tx: Sender<Event>) {
let textview = views::TextView::empty()
.scroll_strategy(cursive::view::ScrollStrategy::StickToBottom)
.with_id("debug_view")
.full_screen();
let input = views::EditView::new()
.on_submit(move |siv, text| {
event_tx.send(Event::TextInput(String::from(text))).unwrap();
siv.call_on_id("input", |input: &mut views::EditView| input.set_content(""));
})
.with_id("input");
let layer = views::LinearLayout::vertical()
.child(textview)
.child(input)
.full_screen();
siv.add_layer(layer);
}
fn debug_message<M: std::fmt::Debug>(siv: &mut Cursive, message: M) {
siv.call_on_id("debug_view", |view: &mut views::TextView| {
let now = chrono::Local::now();
let hour = now.hour();
let minute = now.minute();
let second = now.second();
view.append(format!(
"[{:02}:{:02}:{:02}] {:?}\n",
hour, minute, second, message
));
});
}
pub fn start(net_tx: UnboundedSender<io::Event>) -> Sender<Event> {
let (event_tx, event_rx) = std::sync::mpsc::channel();
let event_tx2 = event_tx.clone();
spawn(move || {
let mut controller = Controller::new(net_tx, event_tx, event_rx);
while controller.is_running() {
controller.step();
}
});
event_tx2
}
|
.child(password);
views::Dialog::around(inputs)
|
random_line_split
|
version.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use json;
#[derive(Debug, PartialEq, Clone)]
pub enum Version {
V3,
}
impl From<json::Version> for Version {
fn from(json: json::Version) -> Self
|
}
impl Into<json::Version> for Version {
fn into(self) -> json::Version {
match self {
Version::V3 => json::Version::V3,
}
}
}
|
{
match json {
json::Version::V3 => Version::V3,
}
}
|
identifier_body
|
version.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use json;
#[derive(Debug, PartialEq, Clone)]
pub enum
|
{
V3,
}
impl From<json::Version> for Version {
fn from(json: json::Version) -> Self {
match json {
json::Version::V3 => Version::V3,
}
}
}
impl Into<json::Version> for Version {
fn into(self) -> json::Version {
match self {
Version::V3 => json::Version::V3,
}
}
}
|
Version
|
identifier_name
|
version.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
|
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use json;
#[derive(Debug, PartialEq, Clone)]
pub enum Version {
V3,
}
impl From<json::Version> for Version {
fn from(json: json::Version) -> Self {
match json {
json::Version::V3 => Version::V3,
}
}
}
impl Into<json::Version> for Version {
fn into(self) -> json::Version {
match self {
Version::V3 => json::Version::V3,
}
}
}
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.