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 |
---|---|---|---|---|
lib.rs | struct Lexer<'a> {
src: &'a [u8],
pos: usize
}
impl<'a> Lexer<'a> {
fn new(src: &'a [u8]) -> Lexer {
Lexer { src: src, pos: 0 }
}
}
impl<'a> Lexer<'a> {
fn ch(&self) -> u8 {
self.src[self.pos]
}
fn | (&self) -> bool {
self.pos >= self.src.len()
}
fn skip_ws(&mut self) -> usize {
let prev_pos = self.pos;
while self.valid_ws() {
self.pos += 1;
}
self.pos - prev_pos
}
fn string(&mut self) -> Option<String> {
let mut tok = Vec::<u8>::new();
loop {
if self.eof() {
break
}
match self.ch() {
b' ' => break,
b'\t' => break,
b'\r' => break,
b'\n' => break,
b'"' => break,
_ => ()
}
tok.push(self.ch());
self.pos += 1;
}
match tok.len() {
0 => None,
_ => Some(String::from_utf8(tok).unwrap())
}
}
fn quoted_string(&mut self) -> Option<String> {
let mut tok = Vec::<u8>::new();
self.pos += 1;
loop {
if self.eof() {
break;
}
match self.ch() {
b'"' => { self.pos += 1; break; },
_ => ()
}
tok.push(self.ch());
self.pos += 1;
}
match tok.len() {
0 => None,
_ => Some(String::from_utf8(tok).unwrap())
}
}
fn valid_ws(&self) -> bool {
if self.eof() {
return false;
}
match self.ch() {
b'' => true,
b'\t' => true,
b'\r' => true,
b'\n' => true,
_ => false
}
}
}
impl<'a> Iterator for Lexer<'a> {
type Item = String;
fn next(&mut self) -> Option<String> {
self.skip_ws();
if self.eof() {
return None;
}
match self.ch() {
b'"' => self.quoted_string(),
_ => self.string()
}
}
}
#[test]
fn tokenize() {
let src = b" foo bar \"a b\" baz ";
let lexer = Lexer::new(src);
let tokens: Vec<_> = lexer.collect();
assert_eq!(4, tokens.len());
assert_eq!("foo".to_string(), tokens[0]);
assert_eq!("bar".to_string(), tokens[1]);
assert_eq!("a b".to_string(), tokens[2]);
assert_eq!("baz".to_string(), tokens[3]);
} | eof | identifier_name |
lib.rs | struct Lexer<'a> {
src: &'a [u8],
pos: usize
}
impl<'a> Lexer<'a> {
fn new(src: &'a [u8]) -> Lexer |
}
impl<'a> Lexer<'a> {
fn ch(&self) -> u8 {
self.src[self.pos]
}
fn eof(&self) -> bool {
self.pos >= self.src.len()
}
fn skip_ws(&mut self) -> usize {
let prev_pos = self.pos;
while self.valid_ws() {
self.pos += 1;
}
self.pos - prev_pos
}
fn string(&mut self) -> Option<String> {
let mut tok = Vec::<u8>::new();
loop {
if self.eof() {
break
}
match self.ch() {
b' ' => break,
b'\t' => break,
b'\r' => break,
b'\n' => break,
b'"' => break,
_ => ()
}
tok.push(self.ch());
self.pos += 1;
}
match tok.len() {
0 => None,
_ => Some(String::from_utf8(tok).unwrap())
}
}
fn quoted_string(&mut self) -> Option<String> {
let mut tok = Vec::<u8>::new();
self.pos += 1;
loop {
if self.eof() {
break;
}
match self.ch() {
b'"' => { self.pos += 1; break; },
_ => ()
}
tok.push(self.ch());
self.pos += 1;
}
match tok.len() {
0 => None,
_ => Some(String::from_utf8(tok).unwrap())
}
}
fn valid_ws(&self) -> bool {
if self.eof() {
return false;
}
match self.ch() {
b'' => true,
b'\t' => true,
b'\r' => true,
b'\n' => true,
_ => false
}
}
}
impl<'a> Iterator for Lexer<'a> {
type Item = String;
fn next(&mut self) -> Option<String> {
self.skip_ws();
if self.eof() {
return None;
}
match self.ch() {
b'"' => self.quoted_string(),
_ => self.string()
}
}
}
#[test]
fn tokenize() {
let src = b" foo bar \"a b\" baz ";
let lexer = Lexer::new(src);
let tokens: Vec<_> = lexer.collect();
assert_eq!(4, tokens.len());
assert_eq!("foo".to_string(), tokens[0]);
assert_eq!("bar".to_string(), tokens[1]);
assert_eq!("a b".to_string(), tokens[2]);
assert_eq!("baz".to_string(), tokens[3]);
} | {
Lexer { src: src, pos: 0 }
} | identifier_body |
lib.rs | struct Lexer<'a> {
src: &'a [u8],
pos: usize
}
impl<'a> Lexer<'a> {
fn new(src: &'a [u8]) -> Lexer {
Lexer { src: src, pos: 0 }
}
}
impl<'a> Lexer<'a> {
fn ch(&self) -> u8 {
self.src[self.pos]
}
fn eof(&self) -> bool {
self.pos >= self.src.len()
}
fn skip_ws(&mut self) -> usize {
let prev_pos = self.pos;
while self.valid_ws() {
self.pos += 1;
}
self.pos - prev_pos
}
fn string(&mut self) -> Option<String> { |
match self.ch() {
b' ' => break,
b'\t' => break,
b'\r' => break,
b'\n' => break,
b'"' => break,
_ => ()
}
tok.push(self.ch());
self.pos += 1;
}
match tok.len() {
0 => None,
_ => Some(String::from_utf8(tok).unwrap())
}
}
fn quoted_string(&mut self) -> Option<String> {
let mut tok = Vec::<u8>::new();
self.pos += 1;
loop {
if self.eof() {
break;
}
match self.ch() {
b'"' => { self.pos += 1; break; },
_ => ()
}
tok.push(self.ch());
self.pos += 1;
}
match tok.len() {
0 => None,
_ => Some(String::from_utf8(tok).unwrap())
}
}
fn valid_ws(&self) -> bool {
if self.eof() {
return false;
}
match self.ch() {
b'' => true,
b'\t' => true,
b'\r' => true,
b'\n' => true,
_ => false
}
}
}
impl<'a> Iterator for Lexer<'a> {
type Item = String;
fn next(&mut self) -> Option<String> {
self.skip_ws();
if self.eof() {
return None;
}
match self.ch() {
b'"' => self.quoted_string(),
_ => self.string()
}
}
}
#[test]
fn tokenize() {
let src = b" foo bar \"a b\" baz ";
let lexer = Lexer::new(src);
let tokens: Vec<_> = lexer.collect();
assert_eq!(4, tokens.len());
assert_eq!("foo".to_string(), tokens[0]);
assert_eq!("bar".to_string(), tokens[1]);
assert_eq!("a b".to_string(), tokens[2]);
assert_eq!("baz".to_string(), tokens[3]);
} | let mut tok = Vec::<u8>::new();
loop {
if self.eof() {
break
} | random_line_split |
base64.rs | #[allow(non_snake_case_functions)]
#[allow(unnecessary_parens)]
// Author - Vikram
// Contact - @TheVikO_o
// License - MIT
mod Base64 {
// Debug Module
pub mod Debug {
use std::str;
// Print bytes as UTF-8 string
pub fn PrintBytes(data: Vec<u8>) {
println!("{}", str::from_utf8(data.as_slice()));
}
}
// Encode array of u8 bytes
pub fn EncodeBytes(source: &[u8])->Vec<u8> {
let bytes = source;
let mut i =0;
let mut output:Vec<u8> = vec![];
let maxLen = bytes.len();
while i < maxLen {
let b1 = (bytes[i] & 0b11111100) >> 2;
output.push(BaseIndex(b1));
if (i + 1) < maxLen {
let b2 = (((bytes[i] & 0b11) << 4) | ((bytes[i+1] & 0b11110000) >> 4));
output.push(BaseIndex(b2));
if (i + 2) < maxLen {
let b3 = (((bytes[i+1] & 0b1111) << 2) | ((bytes[i+2] & 0b11000000) >> 6));
output.push(BaseIndex(b3));
let b4 = bytes[i+2] & 0b111111;
output.push(BaseIndex(b4));
} else {
let b3 = ((bytes[i+1] & 0b1111) << 2);
output.push(BaseIndex(b3));
output.push(b'=');
}
} else {
output.push(BaseIndex(((bytes[i] & 0b11) << 4)));
output.push(b'=');
output.push(b'=');
}
i += 3;
}
output
}
// Encode str
pub fn EncodeStr(source: &str) -> Vec<u8> {
EncodeBytes(source.as_bytes())
}
// Decode array of u8 bytes
pub fn DecodeBytes(source:&[u8]) -> Vec<u8> {
let bytes = source;
let mut i =0;
let mut output:Vec<u8> = vec![];
let maxLen = bytes.len();
if source.len() % 4!= 0 {
return output;
}
while i < maxLen {
let value1:u8 = BaseIndexToByte(bytes[i]);
let value2:u8 = BaseIndexToByte(bytes[i+1]);
let value3:u8 = BaseIndexToByte(bytes[i+2]);
let value4:u8 = BaseIndexToByte(bytes[i+3]);
let b1: u8 = value1 << 2 | (value2 & 0b00110000) >> 4;
let b2: u8 = (value2 & 0b1111) << 4 | (value3 & 0b111100) >> 2;
let b3: u8 = (value3 & 0b11) << 6 | value4;
output.push(b1);
output.push(b2);
output.push(b3);
i += 4;
}
output
}
// Decode str
pub fn | (source:&str)->Vec<u8>{
DecodeBytes(source.as_bytes())
}
// Convert byte to base64 rep
fn BaseIndex(index:u8) -> u8 {
match index {
62 => {b'+'}
63 => {b'/'}
0..25 => { b'A' + index }
26..51 => { b'a' + index - 26 }
_ => { b'0' + index - 52 }
}
}
// Convert base64 rep to byte
fn BaseIndexToByte(source:u8)->u8{
match source {
b'+' => { 62 }
b'/' => { 63 }
b'A'..b'Z' => { source - b'A'}
b'a'..b'z' => { 26 + source - b'a'}
b'0'..b'9' => { 52 + source - b'0'}
_ => { 0 }
}
}
}
// Some tests
fn main() {
let mut encoded = ::Base64::EncodeStr("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut");
::Base64::Debug::PrintBytes(encoded);
let mut decoded = ::Base64::DecodeStr("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2ljaW5nIGVsaXQsIHNlZCBkbyBlaXVzbW9kIHRlbXBvciBpbmNpZGlkdW50IHV0");
::Base64::Debug::PrintBytes(decoded);
encoded = ::Base64::EncodeStr("ab");
::Base64::Debug::PrintBytes(encoded);
decoded = ::Base64::DecodeStr("YWI=");
::Base64::Debug::PrintBytes(decoded);
encoded = ::Base64::EncodeStr("easure.");
::Base64::Debug::PrintBytes(encoded);
decoded = ::Base64::DecodeStr("ZWFzdXJlLg==");
::Base64::Debug::PrintBytes(decoded);
encoded = ::Base64::EncodeStr("C:\\Users\\AppData\\Local\\Viky Notes\\VikyNotes.exe");
::Base64::Debug::PrintBytes(encoded);
decoded = ::Base64::DecodeStr("QzpcVXNlcnNcQXBwRGF0YVxMb2NhbFxWaWt5IE5vdGVzXFZpa3lOb3Rlcy5leGU=");
::Base64::Debug::PrintBytes(decoded);
decoded = ::Base64::DecodeStr("TW");
::Base64::Debug::PrintBytes(decoded);
} | DecodeStr | identifier_name |
base64.rs | #[allow(non_snake_case_functions)]
#[allow(unnecessary_parens)]
// Author - Vikram
// Contact - @TheVikO_o
// License - MIT
mod Base64 {
// Debug Module
pub mod Debug {
use std::str;
// Print bytes as UTF-8 string
pub fn PrintBytes(data: Vec<u8>) {
println!("{}", str::from_utf8(data.as_slice()));
}
}
// Encode array of u8 bytes
pub fn EncodeBytes(source: &[u8])->Vec<u8> {
let bytes = source;
let mut i =0;
let mut output:Vec<u8> = vec![];
let maxLen = bytes.len();
while i < maxLen {
let b1 = (bytes[i] & 0b11111100) >> 2;
output.push(BaseIndex(b1));
if (i + 1) < maxLen {
let b2 = (((bytes[i] & 0b11) << 4) | ((bytes[i+1] & 0b11110000) >> 4));
output.push(BaseIndex(b2));
if (i + 2) < maxLen {
let b3 = (((bytes[i+1] & 0b1111) << 2) | ((bytes[i+2] & 0b11000000) >> 6));
output.push(BaseIndex(b3));
let b4 = bytes[i+2] & 0b111111;
output.push(BaseIndex(b4));
} else {
let b3 = ((bytes[i+1] & 0b1111) << 2);
output.push(BaseIndex(b3));
output.push(b'=');
}
} else {
output.push(BaseIndex(((bytes[i] & 0b11) << 4)));
output.push(b'=');
output.push(b'=');
}
i += 3;
}
output
}
// Encode str
pub fn EncodeStr(source: &str) -> Vec<u8> {
EncodeBytes(source.as_bytes())
}
// Decode array of u8 bytes
pub fn DecodeBytes(source:&[u8]) -> Vec<u8> {
let bytes = source;
let mut i =0;
let mut output:Vec<u8> = vec![];
let maxLen = bytes.len();
if source.len() % 4!= 0 {
return output;
}
while i < maxLen {
let value1:u8 = BaseIndexToByte(bytes[i]);
let value2:u8 = BaseIndexToByte(bytes[i+1]);
let value3:u8 = BaseIndexToByte(bytes[i+2]);
let value4:u8 = BaseIndexToByte(bytes[i+3]);
let b1: u8 = value1 << 2 | (value2 & 0b00110000) >> 4;
let b2: u8 = (value2 & 0b1111) << 4 | (value3 & 0b111100) >> 2;
let b3: u8 = (value3 & 0b11) << 6 | value4;
output.push(b1);
output.push(b2);
output.push(b3);
i += 4;
}
output
}
// Decode str
pub fn DecodeStr(source:&str)->Vec<u8>{
DecodeBytes(source.as_bytes())
}
// Convert byte to base64 rep
fn BaseIndex(index:u8) -> u8 {
match index {
62 => {b'+'}
63 => {b'/'}
0..25 => { b'A' + index }
26..51 => { b'a' + index - 26 }
_ => { b'0' + index - 52 }
}
}
// Convert base64 rep to byte
fn BaseIndexToByte(source:u8)->u8{
match source {
b'+' => { 62 }
b'/' => { 63 }
b'A'..b'Z' => { source - b'A'} | }
}
// Some tests
fn main() {
let mut encoded = ::Base64::EncodeStr("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut");
::Base64::Debug::PrintBytes(encoded);
let mut decoded = ::Base64::DecodeStr("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2ljaW5nIGVsaXQsIHNlZCBkbyBlaXVzbW9kIHRlbXBvciBpbmNpZGlkdW50IHV0");
::Base64::Debug::PrintBytes(decoded);
encoded = ::Base64::EncodeStr("ab");
::Base64::Debug::PrintBytes(encoded);
decoded = ::Base64::DecodeStr("YWI=");
::Base64::Debug::PrintBytes(decoded);
encoded = ::Base64::EncodeStr("easure.");
::Base64::Debug::PrintBytes(encoded);
decoded = ::Base64::DecodeStr("ZWFzdXJlLg==");
::Base64::Debug::PrintBytes(decoded);
encoded = ::Base64::EncodeStr("C:\\Users\\AppData\\Local\\Viky Notes\\VikyNotes.exe");
::Base64::Debug::PrintBytes(encoded);
decoded = ::Base64::DecodeStr("QzpcVXNlcnNcQXBwRGF0YVxMb2NhbFxWaWt5IE5vdGVzXFZpa3lOb3Rlcy5leGU=");
::Base64::Debug::PrintBytes(decoded);
decoded = ::Base64::DecodeStr("TW");
::Base64::Debug::PrintBytes(decoded);
} | b'a'..b'z' => { 26 + source - b'a'}
b'0'..b'9' => { 52 + source - b'0'}
_ => { 0 }
} | random_line_split |
base64.rs | #[allow(non_snake_case_functions)]
#[allow(unnecessary_parens)]
// Author - Vikram
// Contact - @TheVikO_o
// License - MIT
mod Base64 {
// Debug Module
pub mod Debug {
use std::str;
// Print bytes as UTF-8 string
pub fn PrintBytes(data: Vec<u8>) {
println!("{}", str::from_utf8(data.as_slice()));
}
}
// Encode array of u8 bytes
pub fn EncodeBytes(source: &[u8])->Vec<u8> {
let bytes = source;
let mut i =0;
let mut output:Vec<u8> = vec![];
let maxLen = bytes.len();
while i < maxLen {
let b1 = (bytes[i] & 0b11111100) >> 2;
output.push(BaseIndex(b1));
if (i + 1) < maxLen {
let b2 = (((bytes[i] & 0b11) << 4) | ((bytes[i+1] & 0b11110000) >> 4));
output.push(BaseIndex(b2));
if (i + 2) < maxLen {
let b3 = (((bytes[i+1] & 0b1111) << 2) | ((bytes[i+2] & 0b11000000) >> 6));
output.push(BaseIndex(b3));
let b4 = bytes[i+2] & 0b111111;
output.push(BaseIndex(b4));
} else {
let b3 = ((bytes[i+1] & 0b1111) << 2);
output.push(BaseIndex(b3));
output.push(b'=');
}
} else {
output.push(BaseIndex(((bytes[i] & 0b11) << 4)));
output.push(b'=');
output.push(b'=');
}
i += 3;
}
output
}
// Encode str
pub fn EncodeStr(source: &str) -> Vec<u8> {
EncodeBytes(source.as_bytes())
}
// Decode array of u8 bytes
pub fn DecodeBytes(source:&[u8]) -> Vec<u8> {
let bytes = source;
let mut i =0;
let mut output:Vec<u8> = vec![];
let maxLen = bytes.len();
if source.len() % 4!= 0 {
return output;
}
while i < maxLen {
let value1:u8 = BaseIndexToByte(bytes[i]);
let value2:u8 = BaseIndexToByte(bytes[i+1]);
let value3:u8 = BaseIndexToByte(bytes[i+2]);
let value4:u8 = BaseIndexToByte(bytes[i+3]);
let b1: u8 = value1 << 2 | (value2 & 0b00110000) >> 4;
let b2: u8 = (value2 & 0b1111) << 4 | (value3 & 0b111100) >> 2;
let b3: u8 = (value3 & 0b11) << 6 | value4;
output.push(b1);
output.push(b2);
output.push(b3);
i += 4;
}
output
}
// Decode str
pub fn DecodeStr(source:&str)->Vec<u8>{
DecodeBytes(source.as_bytes())
}
// Convert byte to base64 rep
fn BaseIndex(index:u8) -> u8 |
// Convert base64 rep to byte
fn BaseIndexToByte(source:u8)->u8{
match source {
b'+' => { 62 }
b'/' => { 63 }
b'A'..b'Z' => { source - b'A'}
b'a'..b'z' => { 26 + source - b'a'}
b'0'..b'9' => { 52 + source - b'0'}
_ => { 0 }
}
}
}
// Some tests
fn main() {
let mut encoded = ::Base64::EncodeStr("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut");
::Base64::Debug::PrintBytes(encoded);
let mut decoded = ::Base64::DecodeStr("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2ljaW5nIGVsaXQsIHNlZCBkbyBlaXVzbW9kIHRlbXBvciBpbmNpZGlkdW50IHV0");
::Base64::Debug::PrintBytes(decoded);
encoded = ::Base64::EncodeStr("ab");
::Base64::Debug::PrintBytes(encoded);
decoded = ::Base64::DecodeStr("YWI=");
::Base64::Debug::PrintBytes(decoded);
encoded = ::Base64::EncodeStr("easure.");
::Base64::Debug::PrintBytes(encoded);
decoded = ::Base64::DecodeStr("ZWFzdXJlLg==");
::Base64::Debug::PrintBytes(decoded);
encoded = ::Base64::EncodeStr("C:\\Users\\AppData\\Local\\Viky Notes\\VikyNotes.exe");
::Base64::Debug::PrintBytes(encoded);
decoded = ::Base64::DecodeStr("QzpcVXNlcnNcQXBwRGF0YVxMb2NhbFxWaWt5IE5vdGVzXFZpa3lOb3Rlcy5leGU=");
::Base64::Debug::PrintBytes(decoded);
decoded = ::Base64::DecodeStr("TW");
::Base64::Debug::PrintBytes(decoded);
} | {
match index {
62 => {b'+'}
63 => {b'/'}
0..25 => { b'A' + index }
26..51 => { b'a' + index - 26 }
_ => { b'0' + index - 52 }
}
} | identifier_body |
base64.rs | #[allow(non_snake_case_functions)]
#[allow(unnecessary_parens)]
// Author - Vikram
// Contact - @TheVikO_o
// License - MIT
mod Base64 {
// Debug Module
pub mod Debug {
use std::str;
// Print bytes as UTF-8 string
pub fn PrintBytes(data: Vec<u8>) {
println!("{}", str::from_utf8(data.as_slice()));
}
}
// Encode array of u8 bytes
pub fn EncodeBytes(source: &[u8])->Vec<u8> {
let bytes = source;
let mut i =0;
let mut output:Vec<u8> = vec![];
let maxLen = bytes.len();
while i < maxLen {
let b1 = (bytes[i] & 0b11111100) >> 2;
output.push(BaseIndex(b1));
if (i + 1) < maxLen {
let b2 = (((bytes[i] & 0b11) << 4) | ((bytes[i+1] & 0b11110000) >> 4));
output.push(BaseIndex(b2));
if (i + 2) < maxLen {
let b3 = (((bytes[i+1] & 0b1111) << 2) | ((bytes[i+2] & 0b11000000) >> 6));
output.push(BaseIndex(b3));
let b4 = bytes[i+2] & 0b111111;
output.push(BaseIndex(b4));
} else {
let b3 = ((bytes[i+1] & 0b1111) << 2);
output.push(BaseIndex(b3));
output.push(b'=');
}
} else |
i += 3;
}
output
}
// Encode str
pub fn EncodeStr(source: &str) -> Vec<u8> {
EncodeBytes(source.as_bytes())
}
// Decode array of u8 bytes
pub fn DecodeBytes(source:&[u8]) -> Vec<u8> {
let bytes = source;
let mut i =0;
let mut output:Vec<u8> = vec![];
let maxLen = bytes.len();
if source.len() % 4!= 0 {
return output;
}
while i < maxLen {
let value1:u8 = BaseIndexToByte(bytes[i]);
let value2:u8 = BaseIndexToByte(bytes[i+1]);
let value3:u8 = BaseIndexToByte(bytes[i+2]);
let value4:u8 = BaseIndexToByte(bytes[i+3]);
let b1: u8 = value1 << 2 | (value2 & 0b00110000) >> 4;
let b2: u8 = (value2 & 0b1111) << 4 | (value3 & 0b111100) >> 2;
let b3: u8 = (value3 & 0b11) << 6 | value4;
output.push(b1);
output.push(b2);
output.push(b3);
i += 4;
}
output
}
// Decode str
pub fn DecodeStr(source:&str)->Vec<u8>{
DecodeBytes(source.as_bytes())
}
// Convert byte to base64 rep
fn BaseIndex(index:u8) -> u8 {
match index {
62 => {b'+'}
63 => {b'/'}
0..25 => { b'A' + index }
26..51 => { b'a' + index - 26 }
_ => { b'0' + index - 52 }
}
}
// Convert base64 rep to byte
fn BaseIndexToByte(source:u8)->u8{
match source {
b'+' => { 62 }
b'/' => { 63 }
b'A'..b'Z' => { source - b'A'}
b'a'..b'z' => { 26 + source - b'a'}
b'0'..b'9' => { 52 + source - b'0'}
_ => { 0 }
}
}
}
// Some tests
fn main() {
let mut encoded = ::Base64::EncodeStr("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut");
::Base64::Debug::PrintBytes(encoded);
let mut decoded = ::Base64::DecodeStr("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2ljaW5nIGVsaXQsIHNlZCBkbyBlaXVzbW9kIHRlbXBvciBpbmNpZGlkdW50IHV0");
::Base64::Debug::PrintBytes(decoded);
encoded = ::Base64::EncodeStr("ab");
::Base64::Debug::PrintBytes(encoded);
decoded = ::Base64::DecodeStr("YWI=");
::Base64::Debug::PrintBytes(decoded);
encoded = ::Base64::EncodeStr("easure.");
::Base64::Debug::PrintBytes(encoded);
decoded = ::Base64::DecodeStr("ZWFzdXJlLg==");
::Base64::Debug::PrintBytes(decoded);
encoded = ::Base64::EncodeStr("C:\\Users\\AppData\\Local\\Viky Notes\\VikyNotes.exe");
::Base64::Debug::PrintBytes(encoded);
decoded = ::Base64::DecodeStr("QzpcVXNlcnNcQXBwRGF0YVxMb2NhbFxWaWt5IE5vdGVzXFZpa3lOb3Rlcy5leGU=");
::Base64::Debug::PrintBytes(decoded);
decoded = ::Base64::DecodeStr("TW");
::Base64::Debug::PrintBytes(decoded);
} | {
output.push(BaseIndex(((bytes[i] & 0b11) << 4)));
output.push(b'=');
output.push(b'=');
} | conditional_block |
bitboard.rs | // use std::num::Int;
pub type Bitboard = u32;
pub trait BitMove {
fn up_left(&self) -> Self;
fn up_right(&self) -> Self;
fn down_left(&self) -> Self;
fn down_right(&self) -> Self;
fn is(&self) -> bool;
}
pub const S: [Bitboard; 32] = [
1 << 18, 1 << 12, 1 << 6, 1 << 0, | 1 << 3, 1 << 29, 1 << 23, 1 << 17,
1 << 10, 1 << 4, 1 << 30, 1 << 24,
1 << 11, 1 << 05, 1 << 31, 1 << 25];
pub const BP_INIT: Bitboard = S[0] | S[1] | S[2] | S[3] | S[4] | S[5] | S[6] | S[7]
| S[8] | S[9] | S[10] | S[11];
pub const WP_INIT: Bitboard = S[20] | S[21] | S[22] | S[23] | S[24] | S[25] | S[26]
| S[27] | S[28] | S[29] | S[30] | S[31];
pub const ROW_1: Bitboard = S[0] | S[1] | S[2] | S[3];
pub const ROW_2: Bitboard = S[4] | S[5] | S[6] | S[7];
pub const ROW_7: Bitboard = S[24] | S[25] | S[26] | S[27];
pub const ROW_8: Bitboard = S[28] | S[29] | S[30] | S[31];
pub const CAN_UPLEFT: Bitboard =!(S[0] | S[8] | S[16] | S[24] | ROW_8);
pub const CAN_UPRIGHT: Bitboard =!(S[7] | S[15] | S[23] | S[31] | ROW_8);
pub const CAN_DOWNLEFT: Bitboard =!(S[0] | S[8] | S[16] | S[24] | ROW_1);
pub const CAN_DOWNRIGHT: Bitboard =!(S[7] | S[15] | S[23] | S[31] | ROW_1);
#[derive(Clone, PartialEq, Show, Copy)]
pub struct Move {
pub src: u16,
pub dst: u16,
pub jump: bool,
__dummy: ()
}
#[derive(Clone, PartialEq, Show, Copy)]
pub enum Direction{
UpLeft,
UpRight,
DownLeft,
DownRight
}
impl Move {
pub fn new(src: u16, dst: u16, jump: bool) -> Move {
assert!(src < 32);
assert!(dst < 32);
Move {
src: src, dst: dst, jump: jump, __dummy: ()
}
}
pub fn calc_direction(&self) -> Option<Direction> {
let (src, dst) = (S[self.src as usize], S[self.dst as usize]);
if src.up_left() ^ dst == 0 {
Some(Direction::UpLeft)
} else if src.up_right() ^ dst == 0 {
Some(Direction::UpRight)
} else if src.down_right() ^ dst == 0 {
Some(Direction::DownRight)
} else if src.down_left() ^ dst == 0 {
Some(Direction::DownLeft)
} else {
None
}
}
}
#[derive(Clone, Copy)]
pub enum Cell {
Empty = 0,
Pw,
Pb,
Kw,
Kb
}
pub const CELLTABLE: [&'static str; 5] = [ "---", "WHI", "BLK", "KWH", "KBK" ];
#[derive(Show, Clone, Copy, PartialEq)]
pub enum MoveCode {
Success,
VoidPiece,
IllegalMove,
WrongPiece,
Quit,
InputFail
}
impl BitMove for Bitboard {
#[inline]
fn up_left(&self) -> Bitboard {
self.rotate_left(7)
}
#[inline]
fn up_right(&self) -> Bitboard {
self.rotate_left(1)
}
#[inline]
fn down_left(&self) -> Bitboard {
self.rotate_right(1)
}
#[inline]
fn down_right(&self) -> Bitboard {
self.rotate_right(7)
}
#[inline]
fn is(&self) -> bool {
*self!= 0
}
}
// Maps from Bitboard indicating a position to the number
// of that position itself
pub fn bbumap(b: Bitboard) -> Bitboard {
S.iter().position(|&x| x == b).unwrap() as u32
}
#[inline]
pub fn high_bit(mut board: Bitboard) -> Bitboard {
board |= board >> 1;
board |= board >> 2;
board |= board >> 4;
board |= board >> 8;
board |= board >> 16;
board - (board >> 1)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
#[should_panic(expected = "assertion failed")]
fn test_move_validation() {
let _ = Move::new(0, 100, false);
}
#[test]
fn test_move_validation2() {
let _ = Move::new(1,2,false);
let _ = Move::new(31,0,false);
}
#[test]
fn test_direction_calculation() {
let m = Move::new(9, 12, true);
assert_eq!(m.calc_direction(), Some(Direction::UpLeft));
let m = Move::new(9, 13, false);
assert_eq!(m.calc_direction(), Some(Direction::UpRight));
let m = Move::new(21, 17, false);
assert_eq!(m.calc_direction(), Some(Direction::DownLeft));
let m = Move::new(21, 18, false);
assert_eq!(m.calc_direction(), Some(Direction::DownRight));
let m = Move::new(21, 12, false);
assert_eq!(m.calc_direction(), None);
}
} | 1 << 19, 1 << 13, 1 << 7, 1 << 1,
1 << 26, 1 << 20, 1 << 14, 1 << 8,
1 << 27, 1 << 21, 1 << 15, 1 << 9,
1 << 2, 1 << 28, 1 << 22, 1 << 16, | random_line_split |
bitboard.rs | // use std::num::Int;
pub type Bitboard = u32;
pub trait BitMove {
fn up_left(&self) -> Self;
fn up_right(&self) -> Self;
fn down_left(&self) -> Self;
fn down_right(&self) -> Self;
fn is(&self) -> bool;
}
pub const S: [Bitboard; 32] = [
1 << 18, 1 << 12, 1 << 6, 1 << 0,
1 << 19, 1 << 13, 1 << 7, 1 << 1,
1 << 26, 1 << 20, 1 << 14, 1 << 8,
1 << 27, 1 << 21, 1 << 15, 1 << 9,
1 << 2, 1 << 28, 1 << 22, 1 << 16,
1 << 3, 1 << 29, 1 << 23, 1 << 17,
1 << 10, 1 << 4, 1 << 30, 1 << 24,
1 << 11, 1 << 05, 1 << 31, 1 << 25];
pub const BP_INIT: Bitboard = S[0] | S[1] | S[2] | S[3] | S[4] | S[5] | S[6] | S[7]
| S[8] | S[9] | S[10] | S[11];
pub const WP_INIT: Bitboard = S[20] | S[21] | S[22] | S[23] | S[24] | S[25] | S[26]
| S[27] | S[28] | S[29] | S[30] | S[31];
pub const ROW_1: Bitboard = S[0] | S[1] | S[2] | S[3];
pub const ROW_2: Bitboard = S[4] | S[5] | S[6] | S[7];
pub const ROW_7: Bitboard = S[24] | S[25] | S[26] | S[27];
pub const ROW_8: Bitboard = S[28] | S[29] | S[30] | S[31];
pub const CAN_UPLEFT: Bitboard =!(S[0] | S[8] | S[16] | S[24] | ROW_8);
pub const CAN_UPRIGHT: Bitboard =!(S[7] | S[15] | S[23] | S[31] | ROW_8);
pub const CAN_DOWNLEFT: Bitboard =!(S[0] | S[8] | S[16] | S[24] | ROW_1);
pub const CAN_DOWNRIGHT: Bitboard =!(S[7] | S[15] | S[23] | S[31] | ROW_1);
#[derive(Clone, PartialEq, Show, Copy)]
pub struct Move {
pub src: u16,
pub dst: u16,
pub jump: bool,
__dummy: ()
}
#[derive(Clone, PartialEq, Show, Copy)]
pub enum Direction{
UpLeft,
UpRight,
DownLeft,
DownRight
}
impl Move {
pub fn new(src: u16, dst: u16, jump: bool) -> Move {
assert!(src < 32);
assert!(dst < 32);
Move {
src: src, dst: dst, jump: jump, __dummy: ()
}
}
pub fn calc_direction(&self) -> Option<Direction> {
let (src, dst) = (S[self.src as usize], S[self.dst as usize]);
if src.up_left() ^ dst == 0 {
Some(Direction::UpLeft)
} else if src.up_right() ^ dst == 0 {
Some(Direction::UpRight)
} else if src.down_right() ^ dst == 0 {
Some(Direction::DownRight)
} else if src.down_left() ^ dst == 0 {
Some(Direction::DownLeft)
} else {
None
}
}
}
#[derive(Clone, Copy)]
pub enum Cell {
Empty = 0,
Pw,
Pb,
Kw,
Kb
}
pub const CELLTABLE: [&'static str; 5] = [ "---", "WHI", "BLK", "KWH", "KBK" ];
#[derive(Show, Clone, Copy, PartialEq)]
pub enum MoveCode {
Success,
VoidPiece,
IllegalMove,
WrongPiece,
Quit,
InputFail
}
impl BitMove for Bitboard {
#[inline]
fn up_left(&self) -> Bitboard {
self.rotate_left(7)
}
#[inline]
fn up_right(&self) -> Bitboard {
self.rotate_left(1)
}
#[inline]
fn down_left(&self) -> Bitboard {
self.rotate_right(1)
}
#[inline]
fn down_right(&self) -> Bitboard {
self.rotate_right(7)
}
#[inline]
fn is(&self) -> bool |
}
// Maps from Bitboard indicating a position to the number
// of that position itself
pub fn bbumap(b: Bitboard) -> Bitboard {
S.iter().position(|&x| x == b).unwrap() as u32
}
#[inline]
pub fn high_bit(mut board: Bitboard) -> Bitboard {
board |= board >> 1;
board |= board >> 2;
board |= board >> 4;
board |= board >> 8;
board |= board >> 16;
board - (board >> 1)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
#[should_panic(expected = "assertion failed")]
fn test_move_validation() {
let _ = Move::new(0, 100, false);
}
#[test]
fn test_move_validation2() {
let _ = Move::new(1,2,false);
let _ = Move::new(31,0,false);
}
#[test]
fn test_direction_calculation() {
let m = Move::new(9, 12, true);
assert_eq!(m.calc_direction(), Some(Direction::UpLeft));
let m = Move::new(9, 13, false);
assert_eq!(m.calc_direction(), Some(Direction::UpRight));
let m = Move::new(21, 17, false);
assert_eq!(m.calc_direction(), Some(Direction::DownLeft));
let m = Move::new(21, 18, false);
assert_eq!(m.calc_direction(), Some(Direction::DownRight));
let m = Move::new(21, 12, false);
assert_eq!(m.calc_direction(), None);
}
} | {
*self != 0
} | identifier_body |
bitboard.rs | // use std::num::Int;
pub type Bitboard = u32;
pub trait BitMove {
fn up_left(&self) -> Self;
fn up_right(&self) -> Self;
fn down_left(&self) -> Self;
fn down_right(&self) -> Self;
fn is(&self) -> bool;
}
pub const S: [Bitboard; 32] = [
1 << 18, 1 << 12, 1 << 6, 1 << 0,
1 << 19, 1 << 13, 1 << 7, 1 << 1,
1 << 26, 1 << 20, 1 << 14, 1 << 8,
1 << 27, 1 << 21, 1 << 15, 1 << 9,
1 << 2, 1 << 28, 1 << 22, 1 << 16,
1 << 3, 1 << 29, 1 << 23, 1 << 17,
1 << 10, 1 << 4, 1 << 30, 1 << 24,
1 << 11, 1 << 05, 1 << 31, 1 << 25];
pub const BP_INIT: Bitboard = S[0] | S[1] | S[2] | S[3] | S[4] | S[5] | S[6] | S[7]
| S[8] | S[9] | S[10] | S[11];
pub const WP_INIT: Bitboard = S[20] | S[21] | S[22] | S[23] | S[24] | S[25] | S[26]
| S[27] | S[28] | S[29] | S[30] | S[31];
pub const ROW_1: Bitboard = S[0] | S[1] | S[2] | S[3];
pub const ROW_2: Bitboard = S[4] | S[5] | S[6] | S[7];
pub const ROW_7: Bitboard = S[24] | S[25] | S[26] | S[27];
pub const ROW_8: Bitboard = S[28] | S[29] | S[30] | S[31];
pub const CAN_UPLEFT: Bitboard =!(S[0] | S[8] | S[16] | S[24] | ROW_8);
pub const CAN_UPRIGHT: Bitboard =!(S[7] | S[15] | S[23] | S[31] | ROW_8);
pub const CAN_DOWNLEFT: Bitboard =!(S[0] | S[8] | S[16] | S[24] | ROW_1);
pub const CAN_DOWNRIGHT: Bitboard =!(S[7] | S[15] | S[23] | S[31] | ROW_1);
#[derive(Clone, PartialEq, Show, Copy)]
pub struct Move {
pub src: u16,
pub dst: u16,
pub jump: bool,
__dummy: ()
}
#[derive(Clone, PartialEq, Show, Copy)]
pub enum Direction{
UpLeft,
UpRight,
DownLeft,
DownRight
}
impl Move {
pub fn | (src: u16, dst: u16, jump: bool) -> Move {
assert!(src < 32);
assert!(dst < 32);
Move {
src: src, dst: dst, jump: jump, __dummy: ()
}
}
pub fn calc_direction(&self) -> Option<Direction> {
let (src, dst) = (S[self.src as usize], S[self.dst as usize]);
if src.up_left() ^ dst == 0 {
Some(Direction::UpLeft)
} else if src.up_right() ^ dst == 0 {
Some(Direction::UpRight)
} else if src.down_right() ^ dst == 0 {
Some(Direction::DownRight)
} else if src.down_left() ^ dst == 0 {
Some(Direction::DownLeft)
} else {
None
}
}
}
#[derive(Clone, Copy)]
pub enum Cell {
Empty = 0,
Pw,
Pb,
Kw,
Kb
}
pub const CELLTABLE: [&'static str; 5] = [ "---", "WHI", "BLK", "KWH", "KBK" ];
#[derive(Show, Clone, Copy, PartialEq)]
pub enum MoveCode {
Success,
VoidPiece,
IllegalMove,
WrongPiece,
Quit,
InputFail
}
impl BitMove for Bitboard {
#[inline]
fn up_left(&self) -> Bitboard {
self.rotate_left(7)
}
#[inline]
fn up_right(&self) -> Bitboard {
self.rotate_left(1)
}
#[inline]
fn down_left(&self) -> Bitboard {
self.rotate_right(1)
}
#[inline]
fn down_right(&self) -> Bitboard {
self.rotate_right(7)
}
#[inline]
fn is(&self) -> bool {
*self!= 0
}
}
// Maps from Bitboard indicating a position to the number
// of that position itself
pub fn bbumap(b: Bitboard) -> Bitboard {
S.iter().position(|&x| x == b).unwrap() as u32
}
#[inline]
pub fn high_bit(mut board: Bitboard) -> Bitboard {
board |= board >> 1;
board |= board >> 2;
board |= board >> 4;
board |= board >> 8;
board |= board >> 16;
board - (board >> 1)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
#[should_panic(expected = "assertion failed")]
fn test_move_validation() {
let _ = Move::new(0, 100, false);
}
#[test]
fn test_move_validation2() {
let _ = Move::new(1,2,false);
let _ = Move::new(31,0,false);
}
#[test]
fn test_direction_calculation() {
let m = Move::new(9, 12, true);
assert_eq!(m.calc_direction(), Some(Direction::UpLeft));
let m = Move::new(9, 13, false);
assert_eq!(m.calc_direction(), Some(Direction::UpRight));
let m = Move::new(21, 17, false);
assert_eq!(m.calc_direction(), Some(Direction::DownLeft));
let m = Move::new(21, 18, false);
assert_eq!(m.calc_direction(), Some(Direction::DownRight));
let m = Move::new(21, 12, false);
assert_eq!(m.calc_direction(), None);
}
} | new | identifier_name |
lmcons.rs | // Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
//! This file contains constants used throughout the LAN Manager API header files.
pub const CNLEN: ::DWORD = 15;
pub const LM20_CNLEN: ::DWORD = 15;
pub const DNLEN: ::DWORD = CNLEN;
pub const LM20_DNLEN: ::DWORD = LM20_CNLEN;
pub const UNCLEN: ::DWORD = CNLEN + 2;
pub const LM20_UNCLEN: ::DWORD = LM20_CNLEN + 2;
pub const NNLEN: ::DWORD = 80;
pub const LM20_NNLEN: ::DWORD = 12;
pub const RMLEN: ::DWORD = UNCLEN + 1 + NNLEN;
pub const LM20_RMLEN: ::DWORD = LM20_UNCLEN + 1 + LM20_NNLEN;
pub const SNLEN: ::DWORD = 80;
pub const LM20_SNLEN: ::DWORD = 15;
pub const STXTLEN: ::DWORD = 256;
pub const LM20_STXTLEN: ::DWORD = 63;
pub const PATHLEN: ::DWORD = 256;
pub const LM20_PATHLEN: ::DWORD = 256;
pub const DEVLEN: ::DWORD = 80;
pub const LM20_DEVLEN: ::DWORD = 8;
pub const EVLEN: ::DWORD = 16;
pub const UNLEN: ::DWORD = 256;
pub const LM20_UNLEN: ::DWORD = 20;
pub const GNLEN: ::DWORD = UNLEN;
pub const LM20_GNLEN: ::DWORD = LM20_UNLEN;
pub const PWLEN: ::DWORD = 256;
pub const LM20_PWLEN: ::DWORD = 14;
pub const SHPWLEN: ::DWORD = 8;
pub const CLTYPE_LEN: ::DWORD = 12;
pub const MAXCOMMENTSZ: ::DWORD = 256;
pub const LM20_MAXCOMMENTSZ: ::DWORD = 48;
pub const QNLEN: ::DWORD = NNLEN;
pub const LM20_QNLEN: ::DWORD = LM20_NNLEN;
pub const ALERTSZ: ::DWORD = 128;
pub const MAXDEVENTRIES: ::DWORD = 4 * 8; // FIXME: sizeof(int) instead of 4
pub const NETBIOS_NAME_LEN: ::DWORD = 16;
pub const MAX_PREFERRED_LENGTH: ::DWORD = -1i32 as ::DWORD;
pub const CRYPT_KEY_LEN: ::DWORD = 7;
pub const CRYPT_TXT_LEN: ::DWORD = 8;
pub const ENCRYPTED_PWLEN: usize = 16;
pub const SESSION_PWLEN: ::DWORD = 24;
pub const SESSION_CRYPT_KLEN: ::DWORD = 21;
pub const PARM_ERROR_UNKNOWN: ::DWORD = -1i32 as ::DWORD;
pub const PARM_ERROR_NONE: ::DWORD = 0;
pub const PARMNUM_BASE_INFOLEVEL: ::DWORD = 1000;
pub type LMSTR = ::LPWSTR;
pub type LMCSTR = ::LPCWSTR;
pub type NET_API_STATUS = ::DWORD; | pub const PLATFORM_ID_NT: ::DWORD = 500;
pub const PLATFORM_ID_OSF: ::DWORD = 600;
pub const PLATFORM_ID_VMS: ::DWORD = 700; | pub type API_RET_TYPE = NET_API_STATUS;
pub const PLATFORM_ID_DOS: ::DWORD = 300;
pub const PLATFORM_ID_OS2: ::DWORD = 400; | random_line_split |
lint-unused-imports.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.
#![feature(globs)]
#![deny(unused_imports)]
#![allow(dead_code)]
#![allow(deprecated_owned_vector)]
use cal = bar::c::cc;
use std::mem::*; // shouldn't get errors for not using
// everything imported
// Should get errors for both 'Some' and 'None'
use std::option::{Some, None}; //~ ERROR unused import
//~^ ERROR unused import
use test::A; //~ ERROR unused import
// Be sure that if we just bring some methods into scope that they're also
// counted as being used.
use test::B;
// Make sure this import is warned about when at least one of its imported names
// is unused
use std::slice::{from_fn, from_elem}; //~ ERROR unused import
mod test {
pub trait A { fn a(&self) {} }
pub trait B { fn b(&self) {} }
pub struct C;
impl A for C {}
impl B for C {}
}
mod foo {
pub struct Point{x: int, y: int}
pub struct Square{p: Point, h: uint, w: uint}
}
mod bar {
// Don't ignore on 'pub use' because we're not sure if it's used or not
pub use std::cmp::Eq;
pub mod c {
use foo::Point;
use foo::Square; //~ ERROR unused import
pub fn | (p: Point) -> int { return 2 * (p.x + p.y); }
}
#[allow(unused_imports)]
mod foo {
use std::cmp::Eq;
}
}
fn main() {
cal(foo::Point{x:3, y:9});
let mut a = 3;
let mut b = 4;
swap(&mut a, &mut b);
test::C.b();
let _a = from_elem(0, 0);
}
| cc | identifier_name |
lint-unused-imports.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.
#![feature(globs)]
#![deny(unused_imports)]
#![allow(dead_code)]
#![allow(deprecated_owned_vector)]
use cal = bar::c::cc;
use std::mem::*; // shouldn't get errors for not using
// everything imported
// Should get errors for both 'Some' and 'None'
use std::option::{Some, None}; //~ ERROR unused import
//~^ ERROR unused import
use test::A; //~ ERROR unused import
// Be sure that if we just bring some methods into scope that they're also | // Make sure this import is warned about when at least one of its imported names
// is unused
use std::slice::{from_fn, from_elem}; //~ ERROR unused import
mod test {
pub trait A { fn a(&self) {} }
pub trait B { fn b(&self) {} }
pub struct C;
impl A for C {}
impl B for C {}
}
mod foo {
pub struct Point{x: int, y: int}
pub struct Square{p: Point, h: uint, w: uint}
}
mod bar {
// Don't ignore on 'pub use' because we're not sure if it's used or not
pub use std::cmp::Eq;
pub mod c {
use foo::Point;
use foo::Square; //~ ERROR unused import
pub fn cc(p: Point) -> int { return 2 * (p.x + p.y); }
}
#[allow(unused_imports)]
mod foo {
use std::cmp::Eq;
}
}
fn main() {
cal(foo::Point{x:3, y:9});
let mut a = 3;
let mut b = 4;
swap(&mut a, &mut b);
test::C.b();
let _a = from_elem(0, 0);
} | // counted as being used.
use test::B;
| random_line_split |
svg.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/. */
//! Generic types for CSS values in SVG
use crate::parser::{Parse, ParserContext};
use cssparser::Parser;
use style_traits::ParseError;
/// The fallback of an SVG paint server value.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
Parse,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
pub enum GenericSVGPaintFallback<C> {
/// The `none` keyword.
None,
/// A magic value that represents no fallback specified and serializes to
/// the empty string.
#[css(skip)]
Unset,
/// A color.
Color(C),
}
pub use self::GenericSVGPaintFallback as SVGPaintFallback;
/// An SVG paint value
///
/// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint>
#[animation(no_bound(Url))]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C)]
pub struct GenericSVGPaint<Color, Url> {
/// The paint source.
pub kind: GenericSVGPaintKind<Color, Url>,
/// The fallback color.
pub fallback: GenericSVGPaintFallback<Color>,
}
pub use self::GenericSVGPaint as SVGPaint;
impl<C, U> Default for SVGPaint<C, U> {
fn default() -> Self {
Self {
kind: SVGPaintKind::None,
fallback: SVGPaintFallback::Unset,
}
}
}
/// An SVG paint value without the fallback.
///
/// Whereas the spec only allows PaintServer to have a fallback, Gecko lets the
/// context properties have a fallback as well.
#[animation(no_bound(U))]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
Parse,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
pub enum GenericSVGPaintKind<C, U> {
/// `none`
#[animation(error)]
None,
/// `<color>`
Color(C),
/// `url(...)`
#[animation(error)]
PaintServer(U),
/// `context-fill`
ContextFill,
/// `context-stroke`
ContextStroke,
}
pub use self::GenericSVGPaintKind as SVGPaintKind;
impl<C: Parse, U: Parse> Parse for SVGPaint<C, U> {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let kind = SVGPaintKind::parse(context, input)?;
if matches!(kind, SVGPaintKind::None | SVGPaintKind::Color(..)) {
return Ok(SVGPaint {
kind,
fallback: SVGPaintFallback::Unset,
});
}
let fallback = input
.try(|i| SVGPaintFallback::parse(context, i))
.unwrap_or(SVGPaintFallback::Unset);
Ok(SVGPaint { kind, fallback })
}
}
/// An SVG length value supports `context-value` in addition to length.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
pub enum SVGLength<L> {
/// `<length> | <percentage> | <number>`
LengthPercentage(L),
/// `context-value`
#[animation(error)]
ContextValue,
}
/// Generic value for stroke-dasharray.
#[derive(
Clone,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
pub enum GenericSVGStrokeDashArray<L> {
/// `[ <length> | <percentage> | <number> ]#`
#[css(comma)]
Values(#[css(if_empty = "none", iterable)] crate::OwnedSlice<L>),
/// `context-value`
ContextValue,
}
pub use self::GenericSVGStrokeDashArray as SVGStrokeDashArray;
/// An SVG opacity value accepts `context-{fill,stroke}-opacity` in
/// addition to opacity value.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf, | ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
pub enum GenericSVGOpacity<OpacityType> {
/// `<opacity-value>`
Opacity(OpacityType),
/// `context-fill-opacity`
#[animation(error)]
ContextFillOpacity,
/// `context-stroke-opacity`
#[animation(error)]
ContextStrokeOpacity,
}
pub use self::GenericSVGOpacity as SVGOpacity; | PartialEq,
Parse,
SpecifiedValueInfo,
ToAnimatedZero, | random_line_split |
svg.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/. */
//! Generic types for CSS values in SVG
use crate::parser::{Parse, ParserContext};
use cssparser::Parser;
use style_traits::ParseError;
/// The fallback of an SVG paint server value.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
Parse,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
pub enum GenericSVGPaintFallback<C> {
/// The `none` keyword.
None,
/// A magic value that represents no fallback specified and serializes to
/// the empty string.
#[css(skip)]
Unset,
/// A color.
Color(C),
}
pub use self::GenericSVGPaintFallback as SVGPaintFallback;
/// An SVG paint value
///
/// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint>
#[animation(no_bound(Url))]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C)]
pub struct GenericSVGPaint<Color, Url> {
/// The paint source.
pub kind: GenericSVGPaintKind<Color, Url>,
/// The fallback color.
pub fallback: GenericSVGPaintFallback<Color>,
}
pub use self::GenericSVGPaint as SVGPaint;
impl<C, U> Default for SVGPaint<C, U> {
fn | () -> Self {
Self {
kind: SVGPaintKind::None,
fallback: SVGPaintFallback::Unset,
}
}
}
/// An SVG paint value without the fallback.
///
/// Whereas the spec only allows PaintServer to have a fallback, Gecko lets the
/// context properties have a fallback as well.
#[animation(no_bound(U))]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
Parse,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
pub enum GenericSVGPaintKind<C, U> {
/// `none`
#[animation(error)]
None,
/// `<color>`
Color(C),
/// `url(...)`
#[animation(error)]
PaintServer(U),
/// `context-fill`
ContextFill,
/// `context-stroke`
ContextStroke,
}
pub use self::GenericSVGPaintKind as SVGPaintKind;
impl<C: Parse, U: Parse> Parse for SVGPaint<C, U> {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let kind = SVGPaintKind::parse(context, input)?;
if matches!(kind, SVGPaintKind::None | SVGPaintKind::Color(..)) {
return Ok(SVGPaint {
kind,
fallback: SVGPaintFallback::Unset,
});
}
let fallback = input
.try(|i| SVGPaintFallback::parse(context, i))
.unwrap_or(SVGPaintFallback::Unset);
Ok(SVGPaint { kind, fallback })
}
}
/// An SVG length value supports `context-value` in addition to length.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
pub enum SVGLength<L> {
/// `<length> | <percentage> | <number>`
LengthPercentage(L),
/// `context-value`
#[animation(error)]
ContextValue,
}
/// Generic value for stroke-dasharray.
#[derive(
Clone,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
pub enum GenericSVGStrokeDashArray<L> {
/// `[ <length> | <percentage> | <number> ]#`
#[css(comma)]
Values(#[css(if_empty = "none", iterable)] crate::OwnedSlice<L>),
/// `context-value`
ContextValue,
}
pub use self::GenericSVGStrokeDashArray as SVGStrokeDashArray;
/// An SVG opacity value accepts `context-{fill,stroke}-opacity` in
/// addition to opacity value.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
Parse,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
pub enum GenericSVGOpacity<OpacityType> {
/// `<opacity-value>`
Opacity(OpacityType),
/// `context-fill-opacity`
#[animation(error)]
ContextFillOpacity,
/// `context-stroke-opacity`
#[animation(error)]
ContextStrokeOpacity,
}
pub use self::GenericSVGOpacity as SVGOpacity;
| default | identifier_name |
svg.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/. */
//! Generic types for CSS values in SVG
use crate::parser::{Parse, ParserContext};
use cssparser::Parser;
use style_traits::ParseError;
/// The fallback of an SVG paint server value.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
Parse,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
pub enum GenericSVGPaintFallback<C> {
/// The `none` keyword.
None,
/// A magic value that represents no fallback specified and serializes to
/// the empty string.
#[css(skip)]
Unset,
/// A color.
Color(C),
}
pub use self::GenericSVGPaintFallback as SVGPaintFallback;
/// An SVG paint value
///
/// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint>
#[animation(no_bound(Url))]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C)]
pub struct GenericSVGPaint<Color, Url> {
/// The paint source.
pub kind: GenericSVGPaintKind<Color, Url>,
/// The fallback color.
pub fallback: GenericSVGPaintFallback<Color>,
}
pub use self::GenericSVGPaint as SVGPaint;
impl<C, U> Default for SVGPaint<C, U> {
fn default() -> Self {
Self {
kind: SVGPaintKind::None,
fallback: SVGPaintFallback::Unset,
}
}
}
/// An SVG paint value without the fallback.
///
/// Whereas the spec only allows PaintServer to have a fallback, Gecko lets the
/// context properties have a fallback as well.
#[animation(no_bound(U))]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Debug,
MallocSizeOf,
PartialEq,
Parse,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
pub enum GenericSVGPaintKind<C, U> {
/// `none`
#[animation(error)]
None,
/// `<color>`
Color(C),
/// `url(...)`
#[animation(error)]
PaintServer(U),
/// `context-fill`
ContextFill,
/// `context-stroke`
ContextStroke,
}
pub use self::GenericSVGPaintKind as SVGPaintKind;
impl<C: Parse, U: Parse> Parse for SVGPaint<C, U> {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let kind = SVGPaintKind::parse(context, input)?;
if matches!(kind, SVGPaintKind::None | SVGPaintKind::Color(..)) |
let fallback = input
.try(|i| SVGPaintFallback::parse(context, i))
.unwrap_or(SVGPaintFallback::Unset);
Ok(SVGPaint { kind, fallback })
}
}
/// An SVG length value supports `context-value` in addition to length.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
pub enum SVGLength<L> {
/// `<length> | <percentage> | <number>`
LengthPercentage(L),
/// `context-value`
#[animation(error)]
ContextValue,
}
/// Generic value for stroke-dasharray.
#[derive(
Clone,
Debug,
MallocSizeOf,
PartialEq,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
pub enum GenericSVGStrokeDashArray<L> {
/// `[ <length> | <percentage> | <number> ]#`
#[css(comma)]
Values(#[css(if_empty = "none", iterable)] crate::OwnedSlice<L>),
/// `context-value`
ContextValue,
}
pub use self::GenericSVGStrokeDashArray as SVGStrokeDashArray;
/// An SVG opacity value accepts `context-{fill,stroke}-opacity` in
/// addition to opacity value.
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
MallocSizeOf,
PartialEq,
Parse,
SpecifiedValueInfo,
ToAnimatedZero,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
pub enum GenericSVGOpacity<OpacityType> {
/// `<opacity-value>`
Opacity(OpacityType),
/// `context-fill-opacity`
#[animation(error)]
ContextFillOpacity,
/// `context-stroke-opacity`
#[animation(error)]
ContextStrokeOpacity,
}
pub use self::GenericSVGOpacity as SVGOpacity;
| {
return Ok(SVGPaint {
kind,
fallback: SVGPaintFallback::Unset,
});
} | conditional_block |
rexpect.rs | #![cfg(unix)]
extern crate rexpect;
use std::process::Command;
use rexpect::errors::*;
use rexpect::session::{spawn_command, PtySession};
struct REPL {
session: PtySession,
prompt: &'static str,
}
impl REPL {
fn new() -> REPL {
let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err));
repl
}
/// Defines the command, timeout, and prompt settings.
/// Wraps a rexpect::session::PtySession. expecting the prompt after launch.
fn new_() -> Result<REPL> {
let timeout: u64 = 30_000;
let prompt: &'static str = "REXPECT> ";
let mut command = Command::new("../target/debug/gluon");
command
.args(&["-i", "--color", "never", "--prompt", prompt])
.env("GLUON_PATH", "..");
let mut session = spawn_command(command, Some(timeout))?;
session.exp_string(prompt)?;
Ok(REPL { session, prompt })
}
fn test(&mut self, send: &str, expect: Option<&str>) {
self.test_(send, expect)
.unwrap_or_else(|err| panic!("{}", err));
}
/// Ensures certain lines are expected to reduce race conditions.
/// If no ouput is expected or desired to be tested, pass it an Option::None,
/// causing rexpect to wait for the next prompt.
fn test_(&mut self, send: &str, expect: Option<&str>) -> Result<()> {
self.session.send_line(send)?;
self.session.exp_string(send)?;
if let Some(string) = expect {
self.session.exp_string(string)?;
}
self.session.exp_string(self.prompt)?;
Ok(())
}
fn quit(&mut self) {
self.quit_().unwrap_or_else(|err| panic!("{}", err));
}
fn quit_(&mut self) -> Result<()> {
let line: &'static str = ":q";
self.session.send_line(line)?;
self.session.exp_string(line)?;
self.session.exp_eof()?;
Ok(())
}
}
#[test]
fn prompt() {
let _repl = REPL::new();
}
#[test]
fn quit() {
let mut repl = REPL::new();
repl.quit();
}
#[test]
fn hello_world() {
let mut repl = REPL::new();
repl.test("let io = import! std.io", None);
repl.test("io.println \"Hello world\"", Some("Hello world"));
}
#[test]
fn expression_types() {
let mut repl = REPL::new();
repl.test(":t 5", Some("Int"));
repl.test(":t 5 + 5", Some("Int"));
repl.test(":t \"gluon\"", Some("String"));
}
#[test]
fn names() {
let mut repl = REPL::new();
repl.test(
":i std.prelude.show",
Some("std.prelude.show: forall a. [std.show.Show a] -> a -> String"),
);
}
#[test]
fn comments() {
let mut repl = REPL::new();
repl.test("1 + 2 // Calls the + function on 1 and 2", Some("3"));
repl.test("1 + 2 /* Calls the + function on 1 and 2 */", Some("3"));
}
#[test]
fn | () {
let mut repl = REPL::new();
repl.test("if True then 1 else 0", Some("1"));
repl.test("if False then 1 else 0", Some("0"));
}
#[test]
fn records() {
let mut repl = REPL::new();
repl.test("let record = { pi = 3.14, add1 = (+) 1.0 }", None);
repl.test("record.pi", Some("3.14"));
repl.test("let record_2 = {x = 1.. record }", None);
repl.test("record_2.x", Some("1"));
repl.test("record_2.pi", Some("3.14"));
}
#[test]
fn arrays() {
let mut repl = REPL::new();
repl.test("let array = import! std.array", None);
repl.test("array.len [1, 2, 3]", Some("3"));
}
#[test]
fn comment() {
let mut repl = REPL::new();
repl.test("// test", None);
}
#[test]
fn error_reports_correct_line() {
let mut repl = REPL::new();
repl.test("let { x } = {}", Some("let { x } = {}"));
}
#[test]
fn import() {
let mut repl = REPL::new();
repl.test("let { assert } = import! std.test", None);
}
#[test]
fn assert() {
let mut repl = REPL::new();
repl.test("let { assert } = import! std.test", None);
repl.test("assert False", None);
}
| if_expressions | identifier_name |
rexpect.rs | #![cfg(unix)]
extern crate rexpect;
use std::process::Command;
use rexpect::errors::*;
use rexpect::session::{spawn_command, PtySession};
struct REPL {
session: PtySession,
prompt: &'static str,
}
impl REPL {
fn new() -> REPL {
let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err));
repl
}
/// Defines the command, timeout, and prompt settings.
/// Wraps a rexpect::session::PtySession. expecting the prompt after launch.
fn new_() -> Result<REPL> {
let timeout: u64 = 30_000;
let prompt: &'static str = "REXPECT> ";
let mut command = Command::new("../target/debug/gluon");
command
.args(&["-i", "--color", "never", "--prompt", prompt])
.env("GLUON_PATH", "..");
let mut session = spawn_command(command, Some(timeout))?;
session.exp_string(prompt)?;
Ok(REPL { session, prompt })
}
fn test(&mut self, send: &str, expect: Option<&str>) {
self.test_(send, expect)
.unwrap_or_else(|err| panic!("{}", err));
}
/// Ensures certain lines are expected to reduce race conditions.
/// If no ouput is expected or desired to be tested, pass it an Option::None,
/// causing rexpect to wait for the next prompt.
fn test_(&mut self, send: &str, expect: Option<&str>) -> Result<()> {
self.session.send_line(send)?;
self.session.exp_string(send)?;
if let Some(string) = expect {
self.session.exp_string(string)?;
}
self.session.exp_string(self.prompt)?;
Ok(())
}
fn quit(&mut self) {
self.quit_().unwrap_or_else(|err| panic!("{}", err));
}
fn quit_(&mut self) -> Result<()> {
let line: &'static str = ":q";
self.session.send_line(line)?;
self.session.exp_string(line)?;
self.session.exp_eof()?;
Ok(())
}
}
#[test]
fn prompt() {
let _repl = REPL::new();
}
#[test]
fn quit() {
let mut repl = REPL::new();
repl.quit();
}
#[test]
fn hello_world() {
let mut repl = REPL::new();
repl.test("let io = import! std.io", None);
repl.test("io.println \"Hello world\"", Some("Hello world"));
}
#[test]
fn expression_types() {
let mut repl = REPL::new();
repl.test(":t 5", Some("Int"));
repl.test(":t 5 + 5", Some("Int"));
repl.test(":t \"gluon\"", Some("String"));
}
#[test]
fn names() {
let mut repl = REPL::new();
repl.test(
":i std.prelude.show",
Some("std.prelude.show: forall a. [std.show.Show a] -> a -> String"),
);
}
#[test]
fn comments() {
let mut repl = REPL::new();
repl.test("1 + 2 // Calls the + function on 1 and 2", Some("3"));
repl.test("1 + 2 /* Calls the + function on 1 and 2 */", Some("3"));
}
#[test]
fn if_expressions() {
let mut repl = REPL::new();
repl.test("if True then 1 else 0", Some("1"));
repl.test("if False then 1 else 0", Some("0"));
}
#[test]
fn records() {
let mut repl = REPL::new();
repl.test("let record = { pi = 3.14, add1 = (+) 1.0 }", None);
repl.test("record.pi", Some("3.14"));
repl.test("let record_2 = {x = 1.. record }", None);
repl.test("record_2.x", Some("1"));
repl.test("record_2.pi", Some("3.14"));
}
#[test]
fn arrays() {
let mut repl = REPL::new();
repl.test("let array = import! std.array", None);
repl.test("array.len [1, 2, 3]", Some("3"));
}
#[test]
fn comment() {
let mut repl = REPL::new();
repl.test("// test", None);
}
#[test]
fn error_reports_correct_line() {
let mut repl = REPL::new();
repl.test("let { x } = {}", Some("let { x } = {}"));
}
#[test]
fn import() |
#[test]
fn assert() {
let mut repl = REPL::new();
repl.test("let { assert } = import! std.test", None);
repl.test("assert False", None);
}
| {
let mut repl = REPL::new();
repl.test("let { assert } = import! std.test", None);
} | identifier_body |
rexpect.rs | #![cfg(unix)]
extern crate rexpect;
use std::process::Command;
use rexpect::errors::*;
use rexpect::session::{spawn_command, PtySession};
struct REPL {
session: PtySession,
prompt: &'static str,
}
impl REPL {
fn new() -> REPL {
let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err));
repl
}
/// Defines the command, timeout, and prompt settings.
/// Wraps a rexpect::session::PtySession. expecting the prompt after launch.
fn new_() -> Result<REPL> {
let timeout: u64 = 30_000;
let prompt: &'static str = "REXPECT> ";
let mut command = Command::new("../target/debug/gluon");
command
.args(&["-i", "--color", "never", "--prompt", prompt])
.env("GLUON_PATH", "..");
let mut session = spawn_command(command, Some(timeout))?;
session.exp_string(prompt)?;
Ok(REPL { session, prompt })
}
fn test(&mut self, send: &str, expect: Option<&str>) {
self.test_(send, expect)
.unwrap_or_else(|err| panic!("{}", err));
}
/// Ensures certain lines are expected to reduce race conditions.
/// If no ouput is expected or desired to be tested, pass it an Option::None,
/// causing rexpect to wait for the next prompt.
fn test_(&mut self, send: &str, expect: Option<&str>) -> Result<()> {
self.session.send_line(send)?;
self.session.exp_string(send)?;
if let Some(string) = expect { |
self.session.exp_string(self.prompt)?;
Ok(())
}
fn quit(&mut self) {
self.quit_().unwrap_or_else(|err| panic!("{}", err));
}
fn quit_(&mut self) -> Result<()> {
let line: &'static str = ":q";
self.session.send_line(line)?;
self.session.exp_string(line)?;
self.session.exp_eof()?;
Ok(())
}
}
#[test]
fn prompt() {
let _repl = REPL::new();
}
#[test]
fn quit() {
let mut repl = REPL::new();
repl.quit();
}
#[test]
fn hello_world() {
let mut repl = REPL::new();
repl.test("let io = import! std.io", None);
repl.test("io.println \"Hello world\"", Some("Hello world"));
}
#[test]
fn expression_types() {
let mut repl = REPL::new();
repl.test(":t 5", Some("Int"));
repl.test(":t 5 + 5", Some("Int"));
repl.test(":t \"gluon\"", Some("String"));
}
#[test]
fn names() {
let mut repl = REPL::new();
repl.test(
":i std.prelude.show",
Some("std.prelude.show: forall a. [std.show.Show a] -> a -> String"),
);
}
#[test]
fn comments() {
let mut repl = REPL::new();
repl.test("1 + 2 // Calls the + function on 1 and 2", Some("3"));
repl.test("1 + 2 /* Calls the + function on 1 and 2 */", Some("3"));
}
#[test]
fn if_expressions() {
let mut repl = REPL::new();
repl.test("if True then 1 else 0", Some("1"));
repl.test("if False then 1 else 0", Some("0"));
}
#[test]
fn records() {
let mut repl = REPL::new();
repl.test("let record = { pi = 3.14, add1 = (+) 1.0 }", None);
repl.test("record.pi", Some("3.14"));
repl.test("let record_2 = {x = 1.. record }", None);
repl.test("record_2.x", Some("1"));
repl.test("record_2.pi", Some("3.14"));
}
#[test]
fn arrays() {
let mut repl = REPL::new();
repl.test("let array = import! std.array", None);
repl.test("array.len [1, 2, 3]", Some("3"));
}
#[test]
fn comment() {
let mut repl = REPL::new();
repl.test("// test", None);
}
#[test]
fn error_reports_correct_line() {
let mut repl = REPL::new();
repl.test("let { x } = {}", Some("let { x } = {}"));
}
#[test]
fn import() {
let mut repl = REPL::new();
repl.test("let { assert } = import! std.test", None);
}
#[test]
fn assert() {
let mut repl = REPL::new();
repl.test("let { assert } = import! std.test", None);
repl.test("assert False", None);
} | self.session.exp_string(string)?;
} | random_line_split |
rexpect.rs | #![cfg(unix)]
extern crate rexpect;
use std::process::Command;
use rexpect::errors::*;
use rexpect::session::{spawn_command, PtySession};
struct REPL {
session: PtySession,
prompt: &'static str,
}
impl REPL {
fn new() -> REPL {
let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err));
repl
}
/// Defines the command, timeout, and prompt settings.
/// Wraps a rexpect::session::PtySession. expecting the prompt after launch.
fn new_() -> Result<REPL> {
let timeout: u64 = 30_000;
let prompt: &'static str = "REXPECT> ";
let mut command = Command::new("../target/debug/gluon");
command
.args(&["-i", "--color", "never", "--prompt", prompt])
.env("GLUON_PATH", "..");
let mut session = spawn_command(command, Some(timeout))?;
session.exp_string(prompt)?;
Ok(REPL { session, prompt })
}
fn test(&mut self, send: &str, expect: Option<&str>) {
self.test_(send, expect)
.unwrap_or_else(|err| panic!("{}", err));
}
/// Ensures certain lines are expected to reduce race conditions.
/// If no ouput is expected or desired to be tested, pass it an Option::None,
/// causing rexpect to wait for the next prompt.
fn test_(&mut self, send: &str, expect: Option<&str>) -> Result<()> {
self.session.send_line(send)?;
self.session.exp_string(send)?;
if let Some(string) = expect |
self.session.exp_string(self.prompt)?;
Ok(())
}
fn quit(&mut self) {
self.quit_().unwrap_or_else(|err| panic!("{}", err));
}
fn quit_(&mut self) -> Result<()> {
let line: &'static str = ":q";
self.session.send_line(line)?;
self.session.exp_string(line)?;
self.session.exp_eof()?;
Ok(())
}
}
#[test]
fn prompt() {
let _repl = REPL::new();
}
#[test]
fn quit() {
let mut repl = REPL::new();
repl.quit();
}
#[test]
fn hello_world() {
let mut repl = REPL::new();
repl.test("let io = import! std.io", None);
repl.test("io.println \"Hello world\"", Some("Hello world"));
}
#[test]
fn expression_types() {
let mut repl = REPL::new();
repl.test(":t 5", Some("Int"));
repl.test(":t 5 + 5", Some("Int"));
repl.test(":t \"gluon\"", Some("String"));
}
#[test]
fn names() {
let mut repl = REPL::new();
repl.test(
":i std.prelude.show",
Some("std.prelude.show: forall a. [std.show.Show a] -> a -> String"),
);
}
#[test]
fn comments() {
let mut repl = REPL::new();
repl.test("1 + 2 // Calls the + function on 1 and 2", Some("3"));
repl.test("1 + 2 /* Calls the + function on 1 and 2 */", Some("3"));
}
#[test]
fn if_expressions() {
let mut repl = REPL::new();
repl.test("if True then 1 else 0", Some("1"));
repl.test("if False then 1 else 0", Some("0"));
}
#[test]
fn records() {
let mut repl = REPL::new();
repl.test("let record = { pi = 3.14, add1 = (+) 1.0 }", None);
repl.test("record.pi", Some("3.14"));
repl.test("let record_2 = {x = 1.. record }", None);
repl.test("record_2.x", Some("1"));
repl.test("record_2.pi", Some("3.14"));
}
#[test]
fn arrays() {
let mut repl = REPL::new();
repl.test("let array = import! std.array", None);
repl.test("array.len [1, 2, 3]", Some("3"));
}
#[test]
fn comment() {
let mut repl = REPL::new();
repl.test("// test", None);
}
#[test]
fn error_reports_correct_line() {
let mut repl = REPL::new();
repl.test("let { x } = {}", Some("let { x } = {}"));
}
#[test]
fn import() {
let mut repl = REPL::new();
repl.test("let { assert } = import! std.test", None);
}
#[test]
fn assert() {
let mut repl = REPL::new();
repl.test("let { assert } = import! std.test", None);
repl.test("assert False", None);
}
| {
self.session.exp_string(string)?;
} | conditional_block |
aspect_frame.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! A frame that constrains its child to a particular aspect ratio |
use glib::translate::ToGlibPtr;
use gtk::cast::GTK_ASPECTFRAME;
use gtk::{self, ffi};
use glib::to_gboolean;
/// AspectFrame — A frame that constrains its child to a particular aspect ratio
struct_Widget!(AspectFrame);
impl AspectFrame {
pub fn new(label: Option<&str>, x_align: f32, y_align: f32, ratio: f32, obey_child: bool) -> Option<AspectFrame> {
let tmp_pointer = unsafe {
ffi::gtk_aspect_frame_new(label.borrow_to_glib().0,
x_align as c_float, y_align as c_float,
ratio as c_float, to_gboolean(obey_child))
};
check_pointer!(tmp_pointer, AspectFrame)
}
pub fn set(&mut self,
x_align: f32,
y_align: f32,
ratio: f32,
obey_child: bool) -> () {
unsafe {
ffi::gtk_aspect_frame_set(GTK_ASPECTFRAME(self.pointer), x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child));
}
}
}
impl_drop!(AspectFrame);
impl_TraitWidget!(AspectFrame);
impl gtk::FrameTrait for AspectFrame {}
impl gtk::ContainerTrait for AspectFrame {}
impl_widget_events!(AspectFrame); |
use libc::c_float; | random_line_split |
aspect_frame.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! A frame that constrains its child to a particular aspect ratio
use libc::c_float;
use glib::translate::ToGlibPtr;
use gtk::cast::GTK_ASPECTFRAME;
use gtk::{self, ffi};
use glib::to_gboolean;
/// AspectFrame — A frame that constrains its child to a particular aspect ratio
struct_Widget!(AspectFrame);
impl AspectFrame {
pub fn new(label: Option<&str>, x_align: f32, y_align: f32, ratio: f32, obey_child: bool) -> Option<AspectFrame> {
let tmp_pointer = unsafe {
ffi::gtk_aspect_frame_new(label.borrow_to_glib().0,
x_align as c_float, y_align as c_float,
ratio as c_float, to_gboolean(obey_child))
};
check_pointer!(tmp_pointer, AspectFrame)
}
pub fn se | mut self,
x_align: f32,
y_align: f32,
ratio: f32,
obey_child: bool) -> () {
unsafe {
ffi::gtk_aspect_frame_set(GTK_ASPECTFRAME(self.pointer), x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child));
}
}
}
impl_drop!(AspectFrame);
impl_TraitWidget!(AspectFrame);
impl gtk::FrameTrait for AspectFrame {}
impl gtk::ContainerTrait for AspectFrame {}
impl_widget_events!(AspectFrame);
| t(& | identifier_name |
aspect_frame.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! A frame that constrains its child to a particular aspect ratio
use libc::c_float;
use glib::translate::ToGlibPtr;
use gtk::cast::GTK_ASPECTFRAME;
use gtk::{self, ffi};
use glib::to_gboolean;
/// AspectFrame — A frame that constrains its child to a particular aspect ratio
struct_Widget!(AspectFrame);
impl AspectFrame {
pub fn new(label: Option<&str>, x_align: f32, y_align: f32, ratio: f32, obey_child: bool) -> Option<AspectFrame> {
| pub fn set(&mut self,
x_align: f32,
y_align: f32,
ratio: f32,
obey_child: bool) -> () {
unsafe {
ffi::gtk_aspect_frame_set(GTK_ASPECTFRAME(self.pointer), x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child));
}
}
}
impl_drop!(AspectFrame);
impl_TraitWidget!(AspectFrame);
impl gtk::FrameTrait for AspectFrame {}
impl gtk::ContainerTrait for AspectFrame {}
impl_widget_events!(AspectFrame);
| let tmp_pointer = unsafe {
ffi::gtk_aspect_frame_new(label.borrow_to_glib().0,
x_align as c_float, y_align as c_float,
ratio as c_float, to_gboolean(obey_child))
};
check_pointer!(tmp_pointer, AspectFrame)
}
| identifier_body |
util.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt;
use std::str;
// A struct that divide a name into serveral parts that meets rust's guidelines.
struct NameSpliter<'a> {
name: &'a [u8],
pos: usize,
}
impl<'a> NameSpliter<'a> {
fn new(s: &str) -> NameSpliter {
NameSpliter {
name: s.as_bytes(),
pos: 0,
}
}
}
impl<'a> Iterator for NameSpliter<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
if self.pos == self.name.len() {
return None;
}
// skip all prefix '_'
while self.pos < self.name.len() && self.name[self.pos] == b'_' {
self.pos += 1;
}
let mut pos = self.name.len();
let mut upper_len = 0;
let mut meet_lower = false;
for i in self.pos..self.name.len() {
let c = self.name[i];
if (b'A'..=b'Z').contains(&c) {
if meet_lower {
// So it should be AaA or aaA
pos = i;
break;
}
upper_len += 1;
} else if c == b'_' {
pos = i;
break;
} else {
meet_lower = true;
if upper_len > 1 {
// So it should be AAa
pos = i - 1;
break;
}
}
}
let s = str::from_utf8(&self.name[self.pos..pos]).unwrap();
self.pos = pos;
Some(s)
}
}
/// Adjust method name to follow rust-guidelines.
pub fn to_snake_case(name: &str) -> String {
let mut snake_method_name = String::with_capacity(name.len());
for s in NameSpliter::new(name) {
snake_method_name.push_str(&s.to_lowercase());
snake_method_name.push('_');
}
snake_method_name.pop();
snake_method_name
}
#[cfg(feature = "protobuf-codec")]
pub fn to_camel_case(name: &str) -> String {
let mut camel_case_name = String::with_capacity(name.len());
for s in NameSpliter::new(name) {
let mut chs = s.chars();
camel_case_name.extend(chs.next().unwrap().to_uppercase());
camel_case_name.push_str(&s[1..].to_lowercase());
}
camel_case_name
}
pub fn fq_grpc(item: &str) -> String {
format!("::grpcio::{}", item)
}
pub enum MethodType {
Unary,
ClientStreaming,
ServerStreaming,
Duplex,
}
impl fmt::Display for MethodType {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
MethodType::Unary => "MethodType::Unary",
MethodType::ClientStreaming => "MethodType::ClientStreaming",
MethodType::ServerStreaming => "MethodType::ServerStreaming",
MethodType::Duplex => "MethodType::Duplex",
}
)
}
}
#[cfg(test)]
mod test {
#[test]
fn test_snake_name() {
let cases = vec![
("AsyncRequest", "async_request"),
("asyncRequest", "async_request"),
("async_request", "async_request"),
("createID", "create_id"),
("AsyncRClient", "async_r_client"),
("CreateIDForReq", "create_id_for_req"),
("Create_ID_For_Req", "create_id_for_req"),
("Create_ID_For__Req", "create_id_for_req"),
("ID", "id"),
("id", "id"),
];
for (origin, exp) in cases {
let res = super::to_snake_case(&origin);
assert_eq!(res, exp);
}
}
#[test]
#[cfg(feature = "protobuf-codec")]
fn test_camel_name() {
let cases = vec![
("AsyncRequest", "AsyncRequest"),
("asyncRequest", "AsyncRequest"),
("async_request", "AsyncRequest"),
("createID", "CreateId"),
("AsyncRClient", "AsyncRClient"),
("async_r_client", "AsyncRClient"),
("CreateIDForReq", "CreateIdForReq"),
("Create_ID_For_Req", "CreateIdForReq"),
("Create_ID_For__Req", "CreateIdForReq"),
("ID", "Id"),
("id", "Id"),
];
for (origin, exp) in cases {
let res = super::to_camel_case(&origin);
assert_eq!(res, exp);
}
}
}
| fmt | identifier_name |
util.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt;
use std::str;
// A struct that divide a name into serveral parts that meets rust's guidelines.
struct NameSpliter<'a> {
name: &'a [u8],
pos: usize,
}
impl<'a> NameSpliter<'a> {
fn new(s: &str) -> NameSpliter {
NameSpliter {
name: s.as_bytes(),
pos: 0,
}
}
}
impl<'a> Iterator for NameSpliter<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
if self.pos == self.name.len() {
return None;
}
// skip all prefix '_'
while self.pos < self.name.len() && self.name[self.pos] == b'_' {
self.pos += 1;
}
let mut pos = self.name.len();
let mut upper_len = 0;
let mut meet_lower = false;
for i in self.pos..self.name.len() {
let c = self.name[i];
if (b'A'..=b'Z').contains(&c) | else if c == b'_' {
pos = i;
break;
} else {
meet_lower = true;
if upper_len > 1 {
// So it should be AAa
pos = i - 1;
break;
}
}
}
let s = str::from_utf8(&self.name[self.pos..pos]).unwrap();
self.pos = pos;
Some(s)
}
}
/// Adjust method name to follow rust-guidelines.
pub fn to_snake_case(name: &str) -> String {
let mut snake_method_name = String::with_capacity(name.len());
for s in NameSpliter::new(name) {
snake_method_name.push_str(&s.to_lowercase());
snake_method_name.push('_');
}
snake_method_name.pop();
snake_method_name
}
#[cfg(feature = "protobuf-codec")]
pub fn to_camel_case(name: &str) -> String {
let mut camel_case_name = String::with_capacity(name.len());
for s in NameSpliter::new(name) {
let mut chs = s.chars();
camel_case_name.extend(chs.next().unwrap().to_uppercase());
camel_case_name.push_str(&s[1..].to_lowercase());
}
camel_case_name
}
pub fn fq_grpc(item: &str) -> String {
format!("::grpcio::{}", item)
}
pub enum MethodType {
Unary,
ClientStreaming,
ServerStreaming,
Duplex,
}
impl fmt::Display for MethodType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
MethodType::Unary => "MethodType::Unary",
MethodType::ClientStreaming => "MethodType::ClientStreaming",
MethodType::ServerStreaming => "MethodType::ServerStreaming",
MethodType::Duplex => "MethodType::Duplex",
}
)
}
}
#[cfg(test)]
mod test {
#[test]
fn test_snake_name() {
let cases = vec![
("AsyncRequest", "async_request"),
("asyncRequest", "async_request"),
("async_request", "async_request"),
("createID", "create_id"),
("AsyncRClient", "async_r_client"),
("CreateIDForReq", "create_id_for_req"),
("Create_ID_For_Req", "create_id_for_req"),
("Create_ID_For__Req", "create_id_for_req"),
("ID", "id"),
("id", "id"),
];
for (origin, exp) in cases {
let res = super::to_snake_case(&origin);
assert_eq!(res, exp);
}
}
#[test]
#[cfg(feature = "protobuf-codec")]
fn test_camel_name() {
let cases = vec![
("AsyncRequest", "AsyncRequest"),
("asyncRequest", "AsyncRequest"),
("async_request", "AsyncRequest"),
("createID", "CreateId"),
("AsyncRClient", "AsyncRClient"),
("async_r_client", "AsyncRClient"),
("CreateIDForReq", "CreateIdForReq"),
("Create_ID_For_Req", "CreateIdForReq"),
("Create_ID_For__Req", "CreateIdForReq"),
("ID", "Id"),
("id", "Id"),
];
for (origin, exp) in cases {
let res = super::to_camel_case(&origin);
assert_eq!(res, exp);
}
}
}
| {
if meet_lower {
// So it should be AaA or aaA
pos = i;
break;
}
upper_len += 1;
} | conditional_block |
util.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt;
use std::str;
// A struct that divide a name into serveral parts that meets rust's guidelines.
struct NameSpliter<'a> {
name: &'a [u8],
pos: usize,
}
impl<'a> NameSpliter<'a> {
fn new(s: &str) -> NameSpliter {
NameSpliter {
name: s.as_bytes(),
pos: 0,
}
}
}
impl<'a> Iterator for NameSpliter<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
if self.pos == self.name.len() {
return None;
}
// skip all prefix '_'
while self.pos < self.name.len() && self.name[self.pos] == b'_' {
self.pos += 1;
}
let mut pos = self.name.len();
let mut upper_len = 0;
let mut meet_lower = false;
for i in self.pos..self.name.len() {
let c = self.name[i];
if (b'A'..=b'Z').contains(&c) {
if meet_lower {
// So it should be AaA or aaA
pos = i;
break;
}
upper_len += 1;
} else if c == b'_' {
pos = i;
break;
} else {
meet_lower = true;
if upper_len > 1 {
// So it should be AAa
pos = i - 1;
break;
}
}
}
let s = str::from_utf8(&self.name[self.pos..pos]).unwrap();
self.pos = pos;
Some(s)
}
}
/// Adjust method name to follow rust-guidelines.
pub fn to_snake_case(name: &str) -> String {
let mut snake_method_name = String::with_capacity(name.len());
for s in NameSpliter::new(name) {
snake_method_name.push_str(&s.to_lowercase());
snake_method_name.push('_');
}
snake_method_name.pop();
snake_method_name
}
#[cfg(feature = "protobuf-codec")]
pub fn to_camel_case(name: &str) -> String {
let mut camel_case_name = String::with_capacity(name.len());
for s in NameSpliter::new(name) {
let mut chs = s.chars();
camel_case_name.extend(chs.next().unwrap().to_uppercase());
camel_case_name.push_str(&s[1..].to_lowercase());
}
camel_case_name
}
pub fn fq_grpc(item: &str) -> String {
format!("::grpcio::{}", item)
}
pub enum MethodType {
Unary,
ClientStreaming,
ServerStreaming,
Duplex,
}
impl fmt::Display for MethodType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
MethodType::Unary => "MethodType::Unary",
MethodType::ClientStreaming => "MethodType::ClientStreaming",
MethodType::ServerStreaming => "MethodType::ServerStreaming",
MethodType::Duplex => "MethodType::Duplex",
}
)
}
}
#[cfg(test)]
mod test { | ("async_request", "async_request"),
("createID", "create_id"),
("AsyncRClient", "async_r_client"),
("CreateIDForReq", "create_id_for_req"),
("Create_ID_For_Req", "create_id_for_req"),
("Create_ID_For__Req", "create_id_for_req"),
("ID", "id"),
("id", "id"),
];
for (origin, exp) in cases {
let res = super::to_snake_case(&origin);
assert_eq!(res, exp);
}
}
#[test]
#[cfg(feature = "protobuf-codec")]
fn test_camel_name() {
let cases = vec![
("AsyncRequest", "AsyncRequest"),
("asyncRequest", "AsyncRequest"),
("async_request", "AsyncRequest"),
("createID", "CreateId"),
("AsyncRClient", "AsyncRClient"),
("async_r_client", "AsyncRClient"),
("CreateIDForReq", "CreateIdForReq"),
("Create_ID_For_Req", "CreateIdForReq"),
("Create_ID_For__Req", "CreateIdForReq"),
("ID", "Id"),
("id", "Id"),
];
for (origin, exp) in cases {
let res = super::to_camel_case(&origin);
assert_eq!(res, exp);
}
}
} | #[test]
fn test_snake_name() {
let cases = vec![
("AsyncRequest", "async_request"),
("asyncRequest", "async_request"), | random_line_split |
expr.rs | #![allow(dead_code)]
use super::*;
use std::fmt;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub enum Expr {
Nil,
Bool(bool),
Int(i64),
Flt(f64),
Str(String),
Sym(Symbol),
Func(Arc<Function>),
Macro(Arc<Macro>),
List(List),
Vector(Vector),
Map(Map),
}
impl Expr { | } else {
None
}
}
pub fn int(&self) -> Option<i64> {
if let Expr::Int(x) = *self {
Some(x)
} else {
None
}
}
pub fn flt(&self) -> Option<f64> {
if let Expr::Flt(x) = *self {
Some(x)
} else {
None
}
}
pub fn str(&self) -> Option<&str> {
if let Expr::Str(ref x) = *self {
Some(x)
} else {
None
}
}
pub fn sym(&self) -> Option<&Symbol> {
if let Expr::Sym(ref x) = *self {
Some(x)
} else {
None
}
}
pub fn list(&self) -> Option<&List> {
if let Expr::List(ref x) = *self {
Some(x)
} else {
None
}
}
pub fn vector(&self) -> Option<&Vector> {
if let Expr::Vector(ref x) = *self {
Some(x)
} else {
None
}
}
pub fn func(&self) -> Option<Arc<Function>> {
if let Expr::Func(ref x) = *self {
Some(x.clone())
} else {
None
}
}
pub fn truthiness(&self) -> bool {
match *self {
Expr::Nil => false,
Expr::Bool(b) => b,
_ => true,
}
}
pub fn is_int(&self) -> bool {
self.int().is_some()
}
pub fn is_flt(&self) -> bool {
self.flt().is_some()
}
pub fn is_num(&self) -> bool {
match *self {
Expr::Flt(_) | Expr::Int(_) => true,
_ => false,
}
}
pub fn map_int<E, F>(self, f: F) -> Expr
where
F: FnOnce(i64) -> E,
E: Into<Expr>
{
match self {
Expr::Int(int) => f(int).into(),
_ => self,
}
}
pub fn map_flt<E, F>(self, f: F) -> Expr
where
F: FnOnce(f64) -> E,
E: Into<Expr>
{
match self {
Expr::Flt(flt) => f(flt).into(),
_ => self,
}
}
}
impl fmt::Display for Expr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Expr::Nil => write!(f, "()"),
Expr::Bool(boolean) => write!(f, "#{}", if boolean { "t" } else { "f" }),
Expr::Int(int) => write!(f, "{}", int),
Expr::Flt(flt) => write!(f, "{}", flt),
Expr::Str(ref string) => write!(f, "\"{}\"", string),
Expr::Sym(ref sym) => write!(f, "{}", sym.0),
Expr::Func(ref func) => write!(f, "{}", func),
Expr::Macro(ref mac) => write!(f, "{}", mac),
Expr::List(ref list) => write!(f, "{}", list),
Expr::Vector(ref vec) => write!(f, "{}", vec),
Expr::Map(ref map) => write!(f, "{}", map),
}
}
}
impl PartialEq for Expr {
fn eq(&self, other: &Self) -> bool {
use self::Expr::*;
match (self, other) {
(&Nil, &Nil) => true,
(&Bool(ref a), &Bool(ref b)) => a == b,
(&Int(ref a), &Int(ref b)) => a == b,
(&Flt(ref a), &Flt(ref b)) => a == b,
(&Str(ref a), &Str(ref b)) => a == b,
(&Sym(ref a), &Sym(ref b)) => a == b,
(&Func(_), &Func(_)) => false,
(&Macro(_), &Macro(_)) => false,
(&List(ref a), &List(ref b)) => a == b,
(&Vector(ref a), &Vector(ref b)) => a == b,
(&Map(ref a), &Map(ref b)) => a == b,
_ => false,
}
}
}
#[cfg(test)]
mod test {
use super::*;
use env::Env;
use ops;
#[test]
fn call_fn() {
let env = ops::env();
let add = env.lookup("+").clone().and_then(|f| f.func()).expect(
"Expected #[+] in builtins",
);
let nums: Vec<Expr> = vec![1i64, 2i64].into_iter().map(Expr::from).collect();
let result = add.apply(nums.as_slice(), env.clone());
assert_eq!(Expr::from(3), result.unwrap());
}
#[test]
fn test_env() {
let new_scope = Env::default();
assert!(new_scope.lookup("hello").is_none());
}
} | pub fn boolean(&self) -> Option<bool> {
if let Expr::Bool(x) = *self {
Some(x) | random_line_split |
expr.rs | #![allow(dead_code)]
use super::*;
use std::fmt;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub enum Expr {
Nil,
Bool(bool),
Int(i64),
Flt(f64),
Str(String),
Sym(Symbol),
Func(Arc<Function>),
Macro(Arc<Macro>),
List(List),
Vector(Vector),
Map(Map),
}
impl Expr {
pub fn boolean(&self) -> Option<bool> {
if let Expr::Bool(x) = *self {
Some(x)
} else {
None
}
}
pub fn int(&self) -> Option<i64> {
if let Expr::Int(x) = *self {
Some(x)
} else {
None
}
}
pub fn flt(&self) -> Option<f64> {
if let Expr::Flt(x) = *self {
Some(x)
} else {
None
}
}
pub fn str(&self) -> Option<&str> {
if let Expr::Str(ref x) = *self {
Some(x)
} else {
None
}
}
pub fn sym(&self) -> Option<&Symbol> {
if let Expr::Sym(ref x) = *self {
Some(x)
} else {
None
}
}
pub fn list(&self) -> Option<&List> {
if let Expr::List(ref x) = *self {
Some(x)
} else {
None
}
}
pub fn vector(&self) -> Option<&Vector> {
if let Expr::Vector(ref x) = *self {
Some(x)
} else {
None
}
}
pub fn func(&self) -> Option<Arc<Function>> {
if let Expr::Func(ref x) = *self {
Some(x.clone())
} else {
None
}
}
pub fn truthiness(&self) -> bool {
match *self {
Expr::Nil => false,
Expr::Bool(b) => b,
_ => true,
}
}
pub fn is_int(&self) -> bool |
pub fn is_flt(&self) -> bool {
self.flt().is_some()
}
pub fn is_num(&self) -> bool {
match *self {
Expr::Flt(_) | Expr::Int(_) => true,
_ => false,
}
}
pub fn map_int<E, F>(self, f: F) -> Expr
where
F: FnOnce(i64) -> E,
E: Into<Expr>
{
match self {
Expr::Int(int) => f(int).into(),
_ => self,
}
}
pub fn map_flt<E, F>(self, f: F) -> Expr
where
F: FnOnce(f64) -> E,
E: Into<Expr>
{
match self {
Expr::Flt(flt) => f(flt).into(),
_ => self,
}
}
}
impl fmt::Display for Expr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Expr::Nil => write!(f, "()"),
Expr::Bool(boolean) => write!(f, "#{}", if boolean { "t" } else { "f" }),
Expr::Int(int) => write!(f, "{}", int),
Expr::Flt(flt) => write!(f, "{}", flt),
Expr::Str(ref string) => write!(f, "\"{}\"", string),
Expr::Sym(ref sym) => write!(f, "{}", sym.0),
Expr::Func(ref func) => write!(f, "{}", func),
Expr::Macro(ref mac) => write!(f, "{}", mac),
Expr::List(ref list) => write!(f, "{}", list),
Expr::Vector(ref vec) => write!(f, "{}", vec),
Expr::Map(ref map) => write!(f, "{}", map),
}
}
}
impl PartialEq for Expr {
fn eq(&self, other: &Self) -> bool {
use self::Expr::*;
match (self, other) {
(&Nil, &Nil) => true,
(&Bool(ref a), &Bool(ref b)) => a == b,
(&Int(ref a), &Int(ref b)) => a == b,
(&Flt(ref a), &Flt(ref b)) => a == b,
(&Str(ref a), &Str(ref b)) => a == b,
(&Sym(ref a), &Sym(ref b)) => a == b,
(&Func(_), &Func(_)) => false,
(&Macro(_), &Macro(_)) => false,
(&List(ref a), &List(ref b)) => a == b,
(&Vector(ref a), &Vector(ref b)) => a == b,
(&Map(ref a), &Map(ref b)) => a == b,
_ => false,
}
}
}
#[cfg(test)]
mod test {
use super::*;
use env::Env;
use ops;
#[test]
fn call_fn() {
let env = ops::env();
let add = env.lookup("+").clone().and_then(|f| f.func()).expect(
"Expected #[+] in builtins",
);
let nums: Vec<Expr> = vec![1i64, 2i64].into_iter().map(Expr::from).collect();
let result = add.apply(nums.as_slice(), env.clone());
assert_eq!(Expr::from(3), result.unwrap());
}
#[test]
fn test_env() {
let new_scope = Env::default();
assert!(new_scope.lookup("hello").is_none());
}
}
| {
self.int().is_some()
} | identifier_body |
expr.rs | #![allow(dead_code)]
use super::*;
use std::fmt;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub enum Expr {
Nil,
Bool(bool),
Int(i64),
Flt(f64),
Str(String),
Sym(Symbol),
Func(Arc<Function>),
Macro(Arc<Macro>),
List(List),
Vector(Vector),
Map(Map),
}
impl Expr {
pub fn boolean(&self) -> Option<bool> {
if let Expr::Bool(x) = *self {
Some(x)
} else {
None
}
}
pub fn int(&self) -> Option<i64> {
if let Expr::Int(x) = *self {
Some(x)
} else {
None
}
}
pub fn flt(&self) -> Option<f64> {
if let Expr::Flt(x) = *self {
Some(x)
} else {
None
}
}
pub fn str(&self) -> Option<&str> {
if let Expr::Str(ref x) = *self {
Some(x)
} else {
None
}
}
pub fn sym(&self) -> Option<&Symbol> {
if let Expr::Sym(ref x) = *self {
Some(x)
} else {
None
}
}
pub fn list(&self) -> Option<&List> {
if let Expr::List(ref x) = *self {
Some(x)
} else {
None
}
}
pub fn | (&self) -> Option<&Vector> {
if let Expr::Vector(ref x) = *self {
Some(x)
} else {
None
}
}
pub fn func(&self) -> Option<Arc<Function>> {
if let Expr::Func(ref x) = *self {
Some(x.clone())
} else {
None
}
}
pub fn truthiness(&self) -> bool {
match *self {
Expr::Nil => false,
Expr::Bool(b) => b,
_ => true,
}
}
pub fn is_int(&self) -> bool {
self.int().is_some()
}
pub fn is_flt(&self) -> bool {
self.flt().is_some()
}
pub fn is_num(&self) -> bool {
match *self {
Expr::Flt(_) | Expr::Int(_) => true,
_ => false,
}
}
pub fn map_int<E, F>(self, f: F) -> Expr
where
F: FnOnce(i64) -> E,
E: Into<Expr>
{
match self {
Expr::Int(int) => f(int).into(),
_ => self,
}
}
pub fn map_flt<E, F>(self, f: F) -> Expr
where
F: FnOnce(f64) -> E,
E: Into<Expr>
{
match self {
Expr::Flt(flt) => f(flt).into(),
_ => self,
}
}
}
impl fmt::Display for Expr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Expr::Nil => write!(f, "()"),
Expr::Bool(boolean) => write!(f, "#{}", if boolean { "t" } else { "f" }),
Expr::Int(int) => write!(f, "{}", int),
Expr::Flt(flt) => write!(f, "{}", flt),
Expr::Str(ref string) => write!(f, "\"{}\"", string),
Expr::Sym(ref sym) => write!(f, "{}", sym.0),
Expr::Func(ref func) => write!(f, "{}", func),
Expr::Macro(ref mac) => write!(f, "{}", mac),
Expr::List(ref list) => write!(f, "{}", list),
Expr::Vector(ref vec) => write!(f, "{}", vec),
Expr::Map(ref map) => write!(f, "{}", map),
}
}
}
impl PartialEq for Expr {
fn eq(&self, other: &Self) -> bool {
use self::Expr::*;
match (self, other) {
(&Nil, &Nil) => true,
(&Bool(ref a), &Bool(ref b)) => a == b,
(&Int(ref a), &Int(ref b)) => a == b,
(&Flt(ref a), &Flt(ref b)) => a == b,
(&Str(ref a), &Str(ref b)) => a == b,
(&Sym(ref a), &Sym(ref b)) => a == b,
(&Func(_), &Func(_)) => false,
(&Macro(_), &Macro(_)) => false,
(&List(ref a), &List(ref b)) => a == b,
(&Vector(ref a), &Vector(ref b)) => a == b,
(&Map(ref a), &Map(ref b)) => a == b,
_ => false,
}
}
}
#[cfg(test)]
mod test {
use super::*;
use env::Env;
use ops;
#[test]
fn call_fn() {
let env = ops::env();
let add = env.lookup("+").clone().and_then(|f| f.func()).expect(
"Expected #[+] in builtins",
);
let nums: Vec<Expr> = vec![1i64, 2i64].into_iter().map(Expr::from).collect();
let result = add.apply(nums.as_slice(), env.clone());
assert_eq!(Expr::from(3), result.unwrap());
}
#[test]
fn test_env() {
let new_scope = Env::default();
assert!(new_scope.lookup("hello").is_none());
}
}
| vector | identifier_name |
astconv.rs | Some(a) => fmt!("lifetime %s",
lifetime_to_str(a, tcx.sess.intr()))
};
tcx.sess.span_err(
span,
fmt!("Illegal %s: %s",
descr, e.msg));
e.replacement
}
}
}
pub fn ast_region_to_region<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
default_span: span,
opt_lifetime: Option<@ast::Lifetime>) -> ty::Region
{
let (span, res) = match opt_lifetime {
None => {
(default_span, rscope.anon_region(default_span))
}
Some(ref lifetime) if lifetime.ident == special_idents::static => {
(lifetime.span, Ok(ty::re_static))
}
Some(ref lifetime) if lifetime.ident == special_idents::self_ => {
(lifetime.span, rscope.self_region(lifetime.span))
}
Some(ref lifetime) => {
(lifetime.span, rscope.named_region(lifetime.span,
lifetime.ident))
}
};
get_region_reporting_err(self.tcx(), span, opt_lifetime, res)
}
pub fn ast_path_to_substs_and_ty<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
did: ast::def_id,
path: @ast::path)
-> ty_param_substs_and_ty {
let tcx = self.tcx();
let ty::ty_param_bounds_and_ty {
bounds: decl_bounds,
region_param: decl_rp,
ty: decl_ty
} = self.get_item_ty(did);
debug!("ast_path_to_substs_and_ty: did=%? decl_rp=%?",
did, decl_rp);
// If the type is parameterized by the self region, then replace self
// region with the current anon region binding (in other words,
// whatever & would get replaced with).
let self_r = match (decl_rp, path.rp) {
(None, None) => {
None
}
(None, Some(_)) => {
tcx.sess.span_err(
path.span,
fmt!("no region bound is allowed on `%s`, \
which is not declared as containing region pointers",
ty::item_path_str(tcx, did)));
None
}
(Some(_), None) => {
let res = rscope.anon_region(path.span);
let r = get_region_reporting_err(self.tcx(), path.span, None, res);
Some(r)
}
(Some(_), Some(_)) => {
Some(ast_region_to_region(self, rscope, path.span, path.rp))
}
};
// Convert the type parameters supplied by the user.
if!vec::same_length(*decl_bounds, path.types) {
self.tcx().sess.span_fatal(
path.span,
fmt!("wrong number of type arguments: expected %u but found %u",
(*decl_bounds).len(), path.types.len()));
}
let tps = path.types.map(|a_t| ast_ty_to_ty(self, rscope, *a_t));
let substs = substs {self_r:self_r, self_ty:None, tps:tps};
let ty = ty::subst(tcx, &substs, decl_ty);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub fn ast_path_to_ty<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
did: ast::def_id,
path: @ast::path)
-> ty_param_substs_and_ty
|
pub static NO_REGIONS: uint = 1;
pub static NO_TPS: uint = 2;
// Parses the programmer's textual representation of a type into our
// internal notion of a type. `getter` is a function that returns the type
// corresponding to a definition ID:
pub fn ast_ty_to_ty<AC:AstConv, RS:region_scope + Copy + Durable>(
self: &AC, rscope: &RS, &&ast_ty: @ast::Ty) -> ty::t {
fn ast_mt_to_mt<AC:AstConv, RS:region_scope + Copy + Durable>(
self: &AC, rscope: &RS, mt: &ast::mt) -> ty::mt {
ty::mt {ty: ast_ty_to_ty(self, rscope, mt.ty), mutbl: mt.mutbl}
}
// Handle @, ~, and & being able to mean estrs and evecs.
// If a_seq_ty is a str or a vec, make it an estr/evec.
// Also handle first-class trait types.
fn mk_pointer<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
a_seq_ty: &ast::mt,
vst: ty::vstore,
constr: &fn(ty::mt) -> ty::t) -> ty::t
{
let tcx = self.tcx();
match a_seq_ty.ty.node {
ast::ty_vec(ref mt) => {
let mut mt = ast_mt_to_mt(self, rscope, mt);
if a_seq_ty.mutbl == ast::m_mutbl ||
a_seq_ty.mutbl == ast::m_const {
mt = ty::mt { ty: mt.ty, mutbl: a_seq_ty.mutbl };
}
return ty::mk_evec(tcx, mt, vst);
}
ast::ty_path(path, id) if a_seq_ty.mutbl == ast::m_imm => {
match tcx.def_map.find(&id) {
Some(&ast::def_prim_ty(ast::ty_str)) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
return ty::mk_estr(tcx, vst);
}
Some(&ast::def_ty(type_def_id)) => {
let result = ast_path_to_substs_and_ty(
self, rscope,
type_def_id, path);
match ty::get(result.ty).sty {
ty::ty_trait(trait_def_id, ref substs, _) => {
let trait_store = match vst {
ty::vstore_box => ty::BoxTraitStore,
ty::vstore_uniq => ty::UniqTraitStore,
ty::vstore_slice(r) => {
ty::RegionTraitStore(r)
}
ty::vstore_fixed(*) => {
tcx.sess.span_err(
path.span,
~"@trait, ~trait or &trait \
are the only supported \
forms of casting-to-\
trait");
ty::BoxTraitStore
}
};
return ty::mk_trait(tcx,
trait_def_id,
/*bad*/copy *substs,
trait_store);
}
_ => {}
}
}
_ => {}
}
}
_ => {}
}
let seq_ty = ast_mt_to_mt(self, rscope, a_seq_ty);
return constr(seq_ty);
}
fn check_path_args(tcx: ty::ctxt,
path: @ast::path,
flags: uint) {
if (flags & NO_TPS)!= 0u {
if path.types.len() > 0u {
tcx.sess.span_err(
path.span,
~"type parameters are not allowed on this type");
}
}
if (flags & NO_REGIONS)!= 0u {
if path.rp.is_some() {
tcx.sess.span_err(
path.span,
~"region parameters are not allowed on this type");
}
}
}
let tcx = self.tcx();
match tcx.ast_ty_to_ty_cache.find(&ast_ty.id) {
Some(&ty::atttce_resolved(ty)) => return ty,
Some(&ty::atttce_unresolved) => {
tcx.sess.span_fatal(ast_ty.span, ~"illegal recursive type; \
insert an enum in the cycle, \
if this is desired");
}
None => { /* go on */ }
}
tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_unresolved);
let typ = match ast_ty.node {
ast::ty_nil => ty::mk_nil(tcx),
ast::ty_bot => ty::mk_bot(tcx),
ast::ty_box(ref mt) => {
mk_pointer(self, rscope, mt, ty::vstore_box,
|tmt| ty::mk_box(tcx, tmt))
}
ast::ty_uniq(ref mt) => {
mk_pointer(self, rscope, mt, ty::vstore_uniq,
|tmt| ty::mk_uniq(tcx, tmt))
}
ast::ty_vec(ref mt) => {
tcx.sess.span_err(ast_ty.span,
~"bare `[]` is not a type");
// return /something/ so they can at least get more errors
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, mt),
ty::vstore_uniq)
}
ast::ty_ptr(ref mt) => {
ty::mk_ptr(tcx, ast_mt_to_mt(self, rscope, mt))
}
ast::ty_rptr(region, ref mt) => {
let r = ast_region_to_region(self, rscope, ast_ty.span, region);
mk_pointer(self, rscope, mt, ty::vstore_slice(r),
|tmt| ty::mk_rptr(tcx, r, tmt))
}
ast::ty_tup(ref fields) => {
let flds = fields.map(|t| ast_ty_to_ty(self, rscope, *t));
ty::mk_tup(tcx, flds)
}
ast::ty_bare_fn(ref bf) => {
ty::mk_bare_fn(tcx, ty_of_bare_fn(self, rscope, bf.purity,
bf.abis, &bf.lifetimes, &bf.decl))
}
ast::ty_closure(ref f) => {
let fn_decl = ty_of_closure(self,
rscope,
f.sigil,
f.purity,
f.onceness,
f.region,
&f.decl,
None,
&f.lifetimes,
ast_ty.span);
ty::mk_closure(tcx, fn_decl)
}
ast::ty_path(path, id) => {
let a_def = match tcx.def_map.find(&id) {
None => tcx.sess.span_fatal(
ast_ty.span, fmt!("unbound path %s",
path_to_str(path, tcx.sess.intr()))),
Some(&d) => d
};
match a_def {
ast::def_ty(did) | ast::def_struct(did) => {
ast_path_to_ty(self, rscope, did, path).ty
}
ast::def_prim_ty(nty) => {
match nty {
ast::ty_bool => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_bool(tcx)
}
ast::ty_int(it) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_int(tcx, it)
}
ast::ty_uint(uit) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_uint(tcx, uit)
}
ast::ty_float(ft) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_float(tcx, ft)
}
ast::ty_str => {
tcx.sess.span_err(ast_ty.span,
~"bare `str` is not a type");
// return /something/ so they can at least get more errors
ty::mk_estr(tcx, ty::vstore_uniq)
}
}
}
ast::def_ty_param(id, n) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_param(tcx, n, id)
}
ast::def_self_ty(id) => {
// n.b.: resolve guarantees that the self type only appears in a
// trait, which we rely upon in various places when creating
// substs
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
let did = ast_util::local_def(id);
ty::mk_self(tcx, did)
}
_ => {
tcx.sess.span_fatal(ast_ty.span,
~"found type name used as a variable");
}
}
}
ast::ty_fixed_length_vec(ref a_mt, e) => {
match const_eval::eval_const_expr_partial(tcx, e) {
Ok(ref r) => {
match *r {
const_eval::const_int(i) =>
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt),
ty::vstore_fixed(i as uint)),
const_eval::const_uint(i) =>
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt),
ty::vstore_fixed(i as uint)),
_ => {
tcx.sess.span_fatal(
ast_ty.span, ~"expected constant expr for vector length");
}
}
}
Err(ref r) => {
tcx.sess.span_fatal(
ast_ty.span,
fmt!("expected constant expr for vector length: %s",
*r));
}
}
}
ast::ty_infer => {
// ty_infer should only appear as the type of arguments or return
// values in a fn_expr, or as the type of local variables. Both of
// these cases are handled specially and should not descend into this
// routine.
self.tcx().sess.span_bug(
ast_ty.span,
~"found `ty_infer` in unexpected place");
}
ast::ty_mac(_) => {
tcx.sess.span_bug(ast_ty.span,
~"found `ty_mac` in unexpected place");
}
};
tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_resolved(typ));
return typ;
}
pub fn ty_of_arg<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
a: ast::arg,
expected_ty: Option<ty::arg>)
-> ty::arg {
let ty = match a.ty.node {
ast::ty_infer if expected_ty.is_some() => expected_ty.get().ty,
ast::ty_infer => self.ty_infer(a.ty.span),
_ => ast_ty_to_ty(self, rscope, a.ty)
};
let mode = {
match a.mode {
| {
// Look up the polytype of the item and then substitute the provided types
// for any type/region parameters.
let ty::ty_param_substs_and_ty {
substs: substs,
ty: ty
} = ast_path_to_substs_and_ty(self, rscope, did, path);
ty_param_substs_and_ty { substs: substs, ty: ty }
} | identifier_body |
astconv.rs | (
tcx: ty::ctxt,
span: span,
a_r: Option<@ast::Lifetime>,
res: Result<ty::Region, RegionError>) -> ty::Region
{
match res {
result::Ok(r) => r,
result::Err(ref e) => {
let descr = match a_r {
None => ~"anonymous lifetime",
Some(a) => fmt!("lifetime %s",
lifetime_to_str(a, tcx.sess.intr()))
};
tcx.sess.span_err(
span,
fmt!("Illegal %s: %s",
descr, e.msg));
e.replacement
}
}
}
pub fn ast_region_to_region<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
default_span: span,
opt_lifetime: Option<@ast::Lifetime>) -> ty::Region
{
let (span, res) = match opt_lifetime {
None => {
(default_span, rscope.anon_region(default_span))
}
Some(ref lifetime) if lifetime.ident == special_idents::static => {
(lifetime.span, Ok(ty::re_static))
}
Some(ref lifetime) if lifetime.ident == special_idents::self_ => {
(lifetime.span, rscope.self_region(lifetime.span))
}
Some(ref lifetime) => {
(lifetime.span, rscope.named_region(lifetime.span,
lifetime.ident))
}
};
get_region_reporting_err(self.tcx(), span, opt_lifetime, res)
}
pub fn ast_path_to_substs_and_ty<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
did: ast::def_id,
path: @ast::path)
-> ty_param_substs_and_ty {
let tcx = self.tcx();
let ty::ty_param_bounds_and_ty {
bounds: decl_bounds,
region_param: decl_rp,
ty: decl_ty
} = self.get_item_ty(did);
debug!("ast_path_to_substs_and_ty: did=%? decl_rp=%?",
did, decl_rp);
// If the type is parameterized by the self region, then replace self
// region with the current anon region binding (in other words,
// whatever & would get replaced with).
let self_r = match (decl_rp, path.rp) {
(None, None) => {
None
}
(None, Some(_)) => {
tcx.sess.span_err(
path.span,
fmt!("no region bound is allowed on `%s`, \
which is not declared as containing region pointers",
ty::item_path_str(tcx, did)));
None
}
(Some(_), None) => {
let res = rscope.anon_region(path.span);
let r = get_region_reporting_err(self.tcx(), path.span, None, res);
Some(r)
}
(Some(_), Some(_)) => {
Some(ast_region_to_region(self, rscope, path.span, path.rp))
}
};
// Convert the type parameters supplied by the user.
if!vec::same_length(*decl_bounds, path.types) {
self.tcx().sess.span_fatal(
path.span,
fmt!("wrong number of type arguments: expected %u but found %u",
(*decl_bounds).len(), path.types.len()));
}
let tps = path.types.map(|a_t| ast_ty_to_ty(self, rscope, *a_t));
let substs = substs {self_r:self_r, self_ty:None, tps:tps};
let ty = ty::subst(tcx, &substs, decl_ty);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub fn ast_path_to_ty<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
did: ast::def_id,
path: @ast::path)
-> ty_param_substs_and_ty
{
// Look up the polytype of the item and then substitute the provided types
// for any type/region parameters.
let ty::ty_param_substs_and_ty {
substs: substs,
ty: ty
} = ast_path_to_substs_and_ty(self, rscope, did, path);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub static NO_REGIONS: uint = 1;
pub static NO_TPS: uint = 2;
// Parses the programmer's textual representation of a type into our
// internal notion of a type. `getter` is a function that returns the type
// corresponding to a definition ID:
pub fn ast_ty_to_ty<AC:AstConv, RS:region_scope + Copy + Durable>(
self: &AC, rscope: &RS, &&ast_ty: @ast::Ty) -> ty::t {
fn ast_mt_to_mt<AC:AstConv, RS:region_scope + Copy + Durable>(
self: &AC, rscope: &RS, mt: &ast::mt) -> ty::mt {
ty::mt {ty: ast_ty_to_ty(self, rscope, mt.ty), mutbl: mt.mutbl}
}
// Handle @, ~, and & being able to mean estrs and evecs.
// If a_seq_ty is a str or a vec, make it an estr/evec.
// Also handle first-class trait types.
fn mk_pointer<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
a_seq_ty: &ast::mt,
vst: ty::vstore,
constr: &fn(ty::mt) -> ty::t) -> ty::t
{
let tcx = self.tcx();
match a_seq_ty.ty.node {
ast::ty_vec(ref mt) => {
let mut mt = ast_mt_to_mt(self, rscope, mt);
if a_seq_ty.mutbl == ast::m_mutbl ||
a_seq_ty.mutbl == ast::m_const {
mt = ty::mt { ty: mt.ty, mutbl: a_seq_ty.mutbl };
}
return ty::mk_evec(tcx, mt, vst);
}
ast::ty_path(path, id) if a_seq_ty.mutbl == ast::m_imm => {
match tcx.def_map.find(&id) {
Some(&ast::def_prim_ty(ast::ty_str)) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
return ty::mk_estr(tcx, vst);
}
Some(&ast::def_ty(type_def_id)) => {
let result = ast_path_to_substs_and_ty(
self, rscope,
type_def_id, path);
match ty::get(result.ty).sty {
ty::ty_trait(trait_def_id, ref substs, _) => {
let trait_store = match vst {
ty::vstore_box => ty::BoxTraitStore,
ty::vstore_uniq => ty::UniqTraitStore,
ty::vstore_slice(r) => {
ty::RegionTraitStore(r)
}
ty::vstore_fixed(*) => {
tcx.sess.span_err(
path.span,
~"@trait, ~trait or &trait \
are the only supported \
forms of casting-to-\
trait");
ty::BoxTraitStore
}
};
return ty::mk_trait(tcx,
trait_def_id,
/*bad*/copy *substs,
trait_store);
}
_ => {}
}
}
_ => {}
}
}
_ => {}
}
let seq_ty = ast_mt_to_mt(self, rscope, a_seq_ty);
return constr(seq_ty);
}
fn check_path_args(tcx: ty::ctxt,
path: @ast::path,
flags: uint) {
if (flags & NO_TPS)!= 0u {
if path.types.len() > 0u {
tcx.sess.span_err(
path.span,
~"type parameters are not allowed on this type");
}
}
if (flags & NO_REGIONS)!= 0u {
if path.rp.is_some() {
tcx.sess.span_err(
path.span,
~"region parameters are not allowed on this type");
}
}
}
let tcx = self.tcx();
match tcx.ast_ty_to_ty_cache.find(&ast_ty.id) {
Some(&ty::atttce_resolved(ty)) => return ty,
Some(&ty::atttce_unresolved) => {
tcx.sess.span_fatal(ast_ty.span, ~"illegal recursive type; \
insert an enum in the cycle, \
if this is desired");
}
None => { /* go on */ }
}
tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_unresolved);
let typ = match ast_ty.node {
ast::ty_nil => ty::mk_nil(tcx),
ast::ty_bot => ty::mk_bot(tcx),
ast::ty_box(ref mt) => {
mk_pointer(self, rscope, mt, ty::vstore_box,
|tmt| ty::mk_box(tcx, tmt))
}
ast::ty_uniq(ref mt) => {
mk_pointer(self, rscope, mt, ty::vstore_uniq,
|tmt| ty::mk_uniq(tcx, tmt))
}
ast::ty_vec(ref mt) => {
tcx.sess.span_err(ast_ty.span,
~"bare `[]` is not a type");
// return /something/ so they can at least get more errors
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, mt),
ty::vstore_uniq)
}
ast::ty_ptr(ref mt) => {
ty::mk_ptr(tcx, ast_mt_to_mt(self, rscope, mt))
}
ast::ty_rptr(region, ref mt) => {
let r = ast_region_to_region(self, rscope, ast_ty.span, region);
mk_pointer(self, rscope, mt, ty::vstore_slice(r),
|tmt| ty::mk_rptr(tcx, r, tmt))
}
ast::ty_tup(ref fields) => {
let flds = fields.map(|t| ast_ty_to_ty(self, rscope, *t));
ty::mk_tup(tcx, flds)
}
ast::ty_bare_fn(ref bf) => {
ty::mk_bare_fn(tcx, ty_of_bare_fn(self, rscope, bf.purity,
bf.abis, &bf.lifetimes, &bf.decl))
}
ast::ty_closure(ref f) => {
let fn_decl = ty_of_closure(self,
rscope,
f.sigil,
f.purity,
f.onceness,
f.region,
&f.decl,
None,
&f.lifetimes,
ast_ty.span);
ty::mk_closure(tcx, fn_decl)
}
ast::ty_path(path, id) => {
let a_def = match tcx.def_map.find(&id) {
None => tcx.sess.span_fatal(
ast_ty.span, fmt!("unbound path %s",
path_to_str(path, tcx.sess.intr()))),
Some(&d) => d
};
match a_def {
ast::def_ty(did) | ast::def_struct(did) => {
ast_path_to_ty(self, rscope, did, path).ty
}
ast::def_prim_ty(nty) => {
match nty {
ast::ty_bool => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_bool(tcx)
}
ast::ty_int(it) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_int(tcx, it)
}
ast::ty_uint(uit) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_uint(tcx, uit)
}
ast::ty_float(ft) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_float(tcx, ft)
}
ast::ty_str => {
tcx.sess.span_err(ast_ty.span,
~"bare `str` is not a type");
// return /something/ so they can at least get more errors
ty::mk_estr(tcx, ty::vstore_uniq)
}
}
}
ast::def_ty_param(id, n) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_param(tcx, n, id)
}
ast::def_self_ty(id) => {
// n.b.: resolve guarantees that the self type only appears in a
// trait, which we rely upon in various places when creating
// substs
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
let did = ast_util::local_def(id);
ty::mk_self(tcx, did)
}
_ => {
tcx.sess.span_fatal(ast_ty.span,
~"found type name used as a variable");
}
}
}
ast::ty_fixed_length_vec(ref a_mt, e) => {
match const_eval::eval_const_expr_partial(tcx, e) {
Ok(ref r) => {
match *r {
const_eval::const_int(i) =>
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt),
ty::vstore_fixed(i as uint)),
const_eval::const_uint(i) =>
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt),
ty::vstore_fixed(i as uint)),
_ => {
tcx.sess.span_fatal(
ast_ty.span, ~"expected constant expr for vector length");
}
}
}
Err(ref r) => {
tcx.sess.span_fatal(
ast_ty.span,
fmt!("expected constant expr for vector length: %s",
*r));
}
}
}
ast::ty_infer => {
// ty_infer should only appear as the type of arguments or return
// values in a fn_expr, or as the type of local variables. Both of
// these cases are handled specially and should not descend into this
// routine.
self.tcx().sess.span_bug(
ast_ty.span,
~"found `ty_infer` in unexpected place");
}
ast::ty_mac(_) => {
tcx.sess.span_bug(ast_ty.span,
~"found `ty_mac` in unexpected place");
}
};
tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_resolved(typ));
return typ;
}
pub fn ty_of_arg<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
a | get_region_reporting_err | identifier_name |
|
astconv.rs | Some(a) => fmt!("lifetime %s",
lifetime_to_str(a, tcx.sess.intr()))
};
tcx.sess.span_err(
span,
fmt!("Illegal %s: %s",
descr, e.msg));
e.replacement
}
}
}
pub fn ast_region_to_region<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
default_span: span,
opt_lifetime: Option<@ast::Lifetime>) -> ty::Region
{
let (span, res) = match opt_lifetime {
None => {
(default_span, rscope.anon_region(default_span))
}
Some(ref lifetime) if lifetime.ident == special_idents::static => {
(lifetime.span, Ok(ty::re_static))
}
Some(ref lifetime) if lifetime.ident == special_idents::self_ => {
(lifetime.span, rscope.self_region(lifetime.span))
}
Some(ref lifetime) => |
};
get_region_reporting_err(self.tcx(), span, opt_lifetime, res)
}
pub fn ast_path_to_substs_and_ty<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
did: ast::def_id,
path: @ast::path)
-> ty_param_substs_and_ty {
let tcx = self.tcx();
let ty::ty_param_bounds_and_ty {
bounds: decl_bounds,
region_param: decl_rp,
ty: decl_ty
} = self.get_item_ty(did);
debug!("ast_path_to_substs_and_ty: did=%? decl_rp=%?",
did, decl_rp);
// If the type is parameterized by the self region, then replace self
// region with the current anon region binding (in other words,
// whatever & would get replaced with).
let self_r = match (decl_rp, path.rp) {
(None, None) => {
None
}
(None, Some(_)) => {
tcx.sess.span_err(
path.span,
fmt!("no region bound is allowed on `%s`, \
which is not declared as containing region pointers",
ty::item_path_str(tcx, did)));
None
}
(Some(_), None) => {
let res = rscope.anon_region(path.span);
let r = get_region_reporting_err(self.tcx(), path.span, None, res);
Some(r)
}
(Some(_), Some(_)) => {
Some(ast_region_to_region(self, rscope, path.span, path.rp))
}
};
// Convert the type parameters supplied by the user.
if!vec::same_length(*decl_bounds, path.types) {
self.tcx().sess.span_fatal(
path.span,
fmt!("wrong number of type arguments: expected %u but found %u",
(*decl_bounds).len(), path.types.len()));
}
let tps = path.types.map(|a_t| ast_ty_to_ty(self, rscope, *a_t));
let substs = substs {self_r:self_r, self_ty:None, tps:tps};
let ty = ty::subst(tcx, &substs, decl_ty);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub fn ast_path_to_ty<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
did: ast::def_id,
path: @ast::path)
-> ty_param_substs_and_ty
{
// Look up the polytype of the item and then substitute the provided types
// for any type/region parameters.
let ty::ty_param_substs_and_ty {
substs: substs,
ty: ty
} = ast_path_to_substs_and_ty(self, rscope, did, path);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub static NO_REGIONS: uint = 1;
pub static NO_TPS: uint = 2;
// Parses the programmer's textual representation of a type into our
// internal notion of a type. `getter` is a function that returns the type
// corresponding to a definition ID:
pub fn ast_ty_to_ty<AC:AstConv, RS:region_scope + Copy + Durable>(
self: &AC, rscope: &RS, &&ast_ty: @ast::Ty) -> ty::t {
fn ast_mt_to_mt<AC:AstConv, RS:region_scope + Copy + Durable>(
self: &AC, rscope: &RS, mt: &ast::mt) -> ty::mt {
ty::mt {ty: ast_ty_to_ty(self, rscope, mt.ty), mutbl: mt.mutbl}
}
// Handle @, ~, and & being able to mean estrs and evecs.
// If a_seq_ty is a str or a vec, make it an estr/evec.
// Also handle first-class trait types.
fn mk_pointer<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
a_seq_ty: &ast::mt,
vst: ty::vstore,
constr: &fn(ty::mt) -> ty::t) -> ty::t
{
let tcx = self.tcx();
match a_seq_ty.ty.node {
ast::ty_vec(ref mt) => {
let mut mt = ast_mt_to_mt(self, rscope, mt);
if a_seq_ty.mutbl == ast::m_mutbl ||
a_seq_ty.mutbl == ast::m_const {
mt = ty::mt { ty: mt.ty, mutbl: a_seq_ty.mutbl };
}
return ty::mk_evec(tcx, mt, vst);
}
ast::ty_path(path, id) if a_seq_ty.mutbl == ast::m_imm => {
match tcx.def_map.find(&id) {
Some(&ast::def_prim_ty(ast::ty_str)) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
return ty::mk_estr(tcx, vst);
}
Some(&ast::def_ty(type_def_id)) => {
let result = ast_path_to_substs_and_ty(
self, rscope,
type_def_id, path);
match ty::get(result.ty).sty {
ty::ty_trait(trait_def_id, ref substs, _) => {
let trait_store = match vst {
ty::vstore_box => ty::BoxTraitStore,
ty::vstore_uniq => ty::UniqTraitStore,
ty::vstore_slice(r) => {
ty::RegionTraitStore(r)
}
ty::vstore_fixed(*) => {
tcx.sess.span_err(
path.span,
~"@trait, ~trait or &trait \
are the only supported \
forms of casting-to-\
trait");
ty::BoxTraitStore
}
};
return ty::mk_trait(tcx,
trait_def_id,
/*bad*/copy *substs,
trait_store);
}
_ => {}
}
}
_ => {}
}
}
_ => {}
}
let seq_ty = ast_mt_to_mt(self, rscope, a_seq_ty);
return constr(seq_ty);
}
fn check_path_args(tcx: ty::ctxt,
path: @ast::path,
flags: uint) {
if (flags & NO_TPS)!= 0u {
if path.types.len() > 0u {
tcx.sess.span_err(
path.span,
~"type parameters are not allowed on this type");
}
}
if (flags & NO_REGIONS)!= 0u {
if path.rp.is_some() {
tcx.sess.span_err(
path.span,
~"region parameters are not allowed on this type");
}
}
}
let tcx = self.tcx();
match tcx.ast_ty_to_ty_cache.find(&ast_ty.id) {
Some(&ty::atttce_resolved(ty)) => return ty,
Some(&ty::atttce_unresolved) => {
tcx.sess.span_fatal(ast_ty.span, ~"illegal recursive type; \
insert an enum in the cycle, \
if this is desired");
}
None => { /* go on */ }
}
tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_unresolved);
let typ = match ast_ty.node {
ast::ty_nil => ty::mk_nil(tcx),
ast::ty_bot => ty::mk_bot(tcx),
ast::ty_box(ref mt) => {
mk_pointer(self, rscope, mt, ty::vstore_box,
|tmt| ty::mk_box(tcx, tmt))
}
ast::ty_uniq(ref mt) => {
mk_pointer(self, rscope, mt, ty::vstore_uniq,
|tmt| ty::mk_uniq(tcx, tmt))
}
ast::ty_vec(ref mt) => {
tcx.sess.span_err(ast_ty.span,
~"bare `[]` is not a type");
// return /something/ so they can at least get more errors
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, mt),
ty::vstore_uniq)
}
ast::ty_ptr(ref mt) => {
ty::mk_ptr(tcx, ast_mt_to_mt(self, rscope, mt))
}
ast::ty_rptr(region, ref mt) => {
let r = ast_region_to_region(self, rscope, ast_ty.span, region);
mk_pointer(self, rscope, mt, ty::vstore_slice(r),
|tmt| ty::mk_rptr(tcx, r, tmt))
}
ast::ty_tup(ref fields) => {
let flds = fields.map(|t| ast_ty_to_ty(self, rscope, *t));
ty::mk_tup(tcx, flds)
}
ast::ty_bare_fn(ref bf) => {
ty::mk_bare_fn(tcx, ty_of_bare_fn(self, rscope, bf.purity,
bf.abis, &bf.lifetimes, &bf.decl))
}
ast::ty_closure(ref f) => {
let fn_decl = ty_of_closure(self,
rscope,
f.sigil,
f.purity,
f.onceness,
f.region,
&f.decl,
None,
&f.lifetimes,
ast_ty.span);
ty::mk_closure(tcx, fn_decl)
}
ast::ty_path(path, id) => {
let a_def = match tcx.def_map.find(&id) {
None => tcx.sess.span_fatal(
ast_ty.span, fmt!("unbound path %s",
path_to_str(path, tcx.sess.intr()))),
Some(&d) => d
};
match a_def {
ast::def_ty(did) | ast::def_struct(did) => {
ast_path_to_ty(self, rscope, did, path).ty
}
ast::def_prim_ty(nty) => {
match nty {
ast::ty_bool => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_bool(tcx)
}
ast::ty_int(it) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_int(tcx, it)
}
ast::ty_uint(uit) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_uint(tcx, uit)
}
ast::ty_float(ft) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_float(tcx, ft)
}
ast::ty_str => {
tcx.sess.span_err(ast_ty.span,
~"bare `str` is not a type");
// return /something/ so they can at least get more errors
ty::mk_estr(tcx, ty::vstore_uniq)
}
}
}
ast::def_ty_param(id, n) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_param(tcx, n, id)
}
ast::def_self_ty(id) => {
// n.b.: resolve guarantees that the self type only appears in a
// trait, which we rely upon in various places when creating
// substs
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
let did = ast_util::local_def(id);
ty::mk_self(tcx, did)
}
_ => {
tcx.sess.span_fatal(ast_ty.span,
~"found type name used as a variable");
}
}
}
ast::ty_fixed_length_vec(ref a_mt, e) => {
match const_eval::eval_const_expr_partial(tcx, e) {
Ok(ref r) => {
match *r {
const_eval::const_int(i) =>
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt),
ty::vstore_fixed(i as uint)),
const_eval::const_uint(i) =>
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt),
ty::vstore_fixed(i as uint)),
_ => {
tcx.sess.span_fatal(
ast_ty.span, ~"expected constant expr for vector length");
}
}
}
Err(ref r) => {
tcx.sess.span_fatal(
ast_ty.span,
fmt!("expected constant expr for vector length: %s",
*r));
}
}
}
ast::ty_infer => {
// ty_infer should only appear as the type of arguments or return
// values in a fn_expr, or as the type of local variables. Both of
// these cases are handled specially and should not descend into this
// routine.
self.tcx().sess.span_bug(
ast_ty.span,
~"found `ty_infer` in unexpected place");
}
ast::ty_mac(_) => {
tcx.sess.span_bug(ast_ty.span,
~"found `ty_mac` in unexpected place");
}
};
tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_resolved(typ));
return typ;
}
pub fn ty_of_arg<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
a: ast::arg,
expected_ty: Option<ty::arg>)
-> ty::arg {
let ty = match a.ty.node {
ast::ty_infer if expected_ty.is_some() => expected_ty.get().ty,
ast::ty_infer => self.ty_infer(a.ty.span),
_ => ast_ty_to_ty(self, rscope, a.ty)
};
let mode = {
match a.mode {
| {
(lifetime.span, rscope.named_region(lifetime.span,
lifetime.ident))
} | conditional_block |
astconv.rs | * Note that the self region for the `foo` defaulted to `&` in the first
* case but `&a` in the second. Basically, defaults that appear inside
* an rptr (`&r.T`) use the region `r` that appears in the rptr.
*/
use core::prelude::*;
use middle::const_eval;
use middle::ty::{arg, substs};
use middle::ty::{ty_param_substs_and_ty};
use middle::ty;
use middle::typeck::rscope::in_binding_rscope;
use middle::typeck::rscope::{region_scope, RegionError};
use middle::typeck::rscope::RegionParamNames;
use core::result;
use core::vec;
use syntax::abi::AbiSet;
use syntax::{ast, ast_util};
use syntax::codemap::span;
use syntax::opt_vec::OptVec;
use syntax::opt_vec;
use syntax::print::pprust::{lifetime_to_str, path_to_str};
use syntax::parse::token::special_idents;
use util::common::indenter;
pub trait AstConv {
fn tcx(&self) -> ty::ctxt;
fn get_item_ty(&self, id: ast::def_id) -> ty::ty_param_bounds_and_ty;
// what type should we use when a type is omitted?
fn ty_infer(&self, span: span) -> ty::t;
}
pub fn get_region_reporting_err(
tcx: ty::ctxt,
span: span,
a_r: Option<@ast::Lifetime>,
res: Result<ty::Region, RegionError>) -> ty::Region
{
match res {
result::Ok(r) => r,
result::Err(ref e) => {
let descr = match a_r {
None => ~"anonymous lifetime",
Some(a) => fmt!("lifetime %s",
lifetime_to_str(a, tcx.sess.intr()))
};
tcx.sess.span_err(
span,
fmt!("Illegal %s: %s",
descr, e.msg));
e.replacement
}
}
}
pub fn ast_region_to_region<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
default_span: span,
opt_lifetime: Option<@ast::Lifetime>) -> ty::Region
{
let (span, res) = match opt_lifetime {
None => {
(default_span, rscope.anon_region(default_span))
}
Some(ref lifetime) if lifetime.ident == special_idents::static => {
(lifetime.span, Ok(ty::re_static))
}
Some(ref lifetime) if lifetime.ident == special_idents::self_ => {
(lifetime.span, rscope.self_region(lifetime.span))
}
Some(ref lifetime) => {
(lifetime.span, rscope.named_region(lifetime.span,
lifetime.ident))
}
};
get_region_reporting_err(self.tcx(), span, opt_lifetime, res)
}
pub fn ast_path_to_substs_and_ty<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
did: ast::def_id,
path: @ast::path)
-> ty_param_substs_and_ty {
let tcx = self.tcx();
let ty::ty_param_bounds_and_ty {
bounds: decl_bounds,
region_param: decl_rp,
ty: decl_ty
} = self.get_item_ty(did);
debug!("ast_path_to_substs_and_ty: did=%? decl_rp=%?",
did, decl_rp);
// If the type is parameterized by the self region, then replace self
// region with the current anon region binding (in other words,
// whatever & would get replaced with).
let self_r = match (decl_rp, path.rp) {
(None, None) => {
None
}
(None, Some(_)) => {
tcx.sess.span_err(
path.span,
fmt!("no region bound is allowed on `%s`, \
which is not declared as containing region pointers",
ty::item_path_str(tcx, did)));
None
}
(Some(_), None) => {
let res = rscope.anon_region(path.span);
let r = get_region_reporting_err(self.tcx(), path.span, None, res);
Some(r)
}
(Some(_), Some(_)) => {
Some(ast_region_to_region(self, rscope, path.span, path.rp))
}
};
// Convert the type parameters supplied by the user.
if!vec::same_length(*decl_bounds, path.types) {
self.tcx().sess.span_fatal(
path.span,
fmt!("wrong number of type arguments: expected %u but found %u",
(*decl_bounds).len(), path.types.len()));
}
let tps = path.types.map(|a_t| ast_ty_to_ty(self, rscope, *a_t));
let substs = substs {self_r:self_r, self_ty:None, tps:tps};
let ty = ty::subst(tcx, &substs, decl_ty);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub fn ast_path_to_ty<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
did: ast::def_id,
path: @ast::path)
-> ty_param_substs_and_ty
{
// Look up the polytype of the item and then substitute the provided types
// for any type/region parameters.
let ty::ty_param_substs_and_ty {
substs: substs,
ty: ty
} = ast_path_to_substs_and_ty(self, rscope, did, path);
ty_param_substs_and_ty { substs: substs, ty: ty }
}
pub static NO_REGIONS: uint = 1;
pub static NO_TPS: uint = 2;
// Parses the programmer's textual representation of a type into our
// internal notion of a type. `getter` is a function that returns the type
// corresponding to a definition ID:
pub fn ast_ty_to_ty<AC:AstConv, RS:region_scope + Copy + Durable>(
self: &AC, rscope: &RS, &&ast_ty: @ast::Ty) -> ty::t {
fn ast_mt_to_mt<AC:AstConv, RS:region_scope + Copy + Durable>(
self: &AC, rscope: &RS, mt: &ast::mt) -> ty::mt {
ty::mt {ty: ast_ty_to_ty(self, rscope, mt.ty), mutbl: mt.mutbl}
}
// Handle @, ~, and & being able to mean estrs and evecs.
// If a_seq_ty is a str or a vec, make it an estr/evec.
// Also handle first-class trait types.
fn mk_pointer<AC:AstConv,RS:region_scope + Copy + Durable>(
self: &AC,
rscope: &RS,
a_seq_ty: &ast::mt,
vst: ty::vstore,
constr: &fn(ty::mt) -> ty::t) -> ty::t
{
let tcx = self.tcx();
match a_seq_ty.ty.node {
ast::ty_vec(ref mt) => {
let mut mt = ast_mt_to_mt(self, rscope, mt);
if a_seq_ty.mutbl == ast::m_mutbl ||
a_seq_ty.mutbl == ast::m_const {
mt = ty::mt { ty: mt.ty, mutbl: a_seq_ty.mutbl };
}
return ty::mk_evec(tcx, mt, vst);
}
ast::ty_path(path, id) if a_seq_ty.mutbl == ast::m_imm => {
match tcx.def_map.find(&id) {
Some(&ast::def_prim_ty(ast::ty_str)) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
return ty::mk_estr(tcx, vst);
}
Some(&ast::def_ty(type_def_id)) => {
let result = ast_path_to_substs_and_ty(
self, rscope,
type_def_id, path);
match ty::get(result.ty).sty {
ty::ty_trait(trait_def_id, ref substs, _) => {
let trait_store = match vst {
ty::vstore_box => ty::BoxTraitStore,
ty::vstore_uniq => ty::UniqTraitStore,
ty::vstore_slice(r) => {
ty::RegionTraitStore(r)
}
ty::vstore_fixed(*) => {
tcx.sess.span_err(
path.span,
~"@trait, ~trait or &trait \
are the only supported \
forms of casting-to-\
trait");
ty::BoxTraitStore
}
};
return ty::mk_trait(tcx,
trait_def_id,
/*bad*/copy *substs,
trait_store);
}
_ => {}
}
}
_ => {}
}
}
_ => {}
}
let seq_ty = ast_mt_to_mt(self, rscope, a_seq_ty);
return constr(seq_ty);
}
fn check_path_args(tcx: ty::ctxt,
path: @ast::path,
flags: uint) {
if (flags & NO_TPS)!= 0u {
if path.types.len() > 0u {
tcx.sess.span_err(
path.span,
~"type parameters are not allowed on this type");
}
}
if (flags & NO_REGIONS)!= 0u {
if path.rp.is_some() {
tcx.sess.span_err(
path.span,
~"region parameters are not allowed on this type");
}
}
}
let tcx = self.tcx();
match tcx.ast_ty_to_ty_cache.find(&ast_ty.id) {
Some(&ty::atttce_resolved(ty)) => return ty,
Some(&ty::atttce_unresolved) => {
tcx.sess.span_fatal(ast_ty.span, ~"illegal recursive type; \
insert an enum in the cycle, \
if this is desired");
}
None => { /* go on */ }
}
tcx.ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_unresolved);
let typ = match ast_ty.node {
ast::ty_nil => ty::mk_nil(tcx),
ast::ty_bot => ty::mk_bot(tcx),
ast::ty_box(ref mt) => {
mk_pointer(self, rscope, mt, ty::vstore_box,
|tmt| ty::mk_box(tcx, tmt))
}
ast::ty_uniq(ref mt) => {
mk_pointer(self, rscope, mt, ty::vstore_uniq,
|tmt| ty::mk_uniq(tcx, tmt))
}
ast::ty_vec(ref mt) => {
tcx.sess.span_err(ast_ty.span,
~"bare `[]` is not a type");
// return /something/ so they can at least get more errors
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, mt),
ty::vstore_uniq)
}
ast::ty_ptr(ref mt) => {
ty::mk_ptr(tcx, ast_mt_to_mt(self, rscope, mt))
}
ast::ty_rptr(region, ref mt) => {
let r = ast_region_to_region(self, rscope, ast_ty.span, region);
mk_pointer(self, rscope, mt, ty::vstore_slice(r),
|tmt| ty::mk_rptr(tcx, r, tmt))
}
ast::ty_tup(ref fields) => {
let flds = fields.map(|t| ast_ty_to_ty(self, rscope, *t));
ty::mk_tup(tcx, flds)
}
ast::ty_bare_fn(ref bf) => {
ty::mk_bare_fn(tcx, ty_of_bare_fn(self, rscope, bf.purity,
bf.abis, &bf.lifetimes, &bf.decl))
}
ast::ty_closure(ref f) => {
let fn_decl = ty_of_closure(self,
rscope,
f.sigil,
f.purity,
f.onceness,
f.region,
&f.decl,
None,
&f.lifetimes,
ast_ty.span);
ty::mk_closure(tcx, fn_decl)
}
ast::ty_path(path, id) => {
let a_def = match tcx.def_map.find(&id) {
None => tcx.sess.span_fatal(
ast_ty.span, fmt!("unbound path %s",
path_to_str(path, tcx.sess.intr()))),
Some(&d) => d
};
match a_def {
ast::def_ty(did) | ast::def_struct(did) => {
ast_path_to_ty(self, rscope, did, path).ty
}
ast::def_prim_ty(nty) => {
match nty {
ast::ty_bool => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_bool(tcx)
}
ast::ty_int(it) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_int(tcx, it)
}
ast::ty_uint(uit) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_uint(tcx, uit)
}
ast::ty_float(ft) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_mach_float(tcx, ft)
}
ast::ty_str => {
tcx.sess.span_err(ast_ty.span,
~"bare `str` is not a type");
// return /something/ so they can at least get more errors
ty::mk_estr(tcx, ty::vstore_uniq)
}
}
}
ast::def_ty_param(id, n) => {
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
ty::mk_param(tcx, n, id)
}
ast::def_self_ty(id) => {
// n.b.: resolve guarantees that the self type only appears in a
// trait, which we rely upon in various places when creating
// substs
check_path_args(tcx, path, NO_TPS | NO_REGIONS);
let did = ast_util::local_def(id);
ty::mk_self(tcx, did)
}
_ => {
tcx.sess.span_fatal(ast_ty.span,
~"found type name used as a variable");
}
}
}
ast::ty_fixed_length_vec(ref a_mt, e) => {
match const_eval::eval_const_expr_partial(tcx, e) {
Ok(ref r) => {
match *r {
const_eval::const_int(i) =>
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt),
ty::vstore_fixed(i as uint)),
const_eval::const_uint(i) =>
ty::mk_evec(tcx, ast_mt_to_mt(self, rscope, a_mt),
ty::vstore_fixed(i as uint)),
_ => {
tcx.sess.span_fatal(
ast_ty.span, ~"expected constant expr for vector length");
}
}
}
Err(ref r) => {
tcx.sess.span_fatal(
ast_ty.span | * Case (b) says that if you have a type:
* type foo<'self> = ...;
* type bar = fn(&foo, &a.foo)
* The fully expanded version of type bar is:
* type bar = fn(&'foo &, &a.foo<'a>) | random_line_split |
|
reporter.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use crate::cpu::collector::{register_collector, Collector, CollectorHandle};
use crate::cpu::recorder::CpuRecords;
use crate::Config;
use std::fmt::{self, Display, Formatter};
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::Arc;
use collections::HashMap;
use futures::SinkExt;
use grpcio::{CallOption, ChannelBuilder, Environment, WriteFlags};
use kvproto::resource_usage_agent::{CpuTimeRecord, ResourceUsageAgentClient};
use tikv_util::time::Duration;
use tikv_util::worker::{Runnable, RunnableWithTimer, Scheduler};
pub struct CpuRecordsCollector {
scheduler: Scheduler<Task>,
}
impl CpuRecordsCollector {
pub fn | (scheduler: Scheduler<Task>) -> Self {
Self { scheduler }
}
}
impl Collector for CpuRecordsCollector {
fn collect(&self, records: Arc<CpuRecords>) {
self.scheduler.schedule(Task::CpuRecords(records)).ok();
}
}
pub enum Task {
ConfigChange(Config),
CpuRecords(Arc<CpuRecords>),
}
impl Display for Task {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Task::ConfigChange(_) => {
write!(f, "ConfigChange")?;
}
Task::CpuRecords(_) => {
write!(f, "CpuRecords")?;
}
}
Ok(())
}
}
pub struct ResourceMeteringReporter {
config: Config,
env: Arc<Environment>,
scheduler: Scheduler<Task>,
// TODO: mock client for testing
client: Option<ResourceUsageAgentClient>,
reporting: Arc<AtomicBool>,
cpu_records_collector: Option<CollectorHandle>,
// resource_tag -> ([timestamp_secs], [cpu_time_ms], total_cpu_time_ms)
records: HashMap<Vec<u8>, (Vec<u64>, Vec<u32>, u32)>,
// timestamp_secs -> cpu_time_ms
others: HashMap<u64, u32>,
find_top_k: Vec<u32>,
}
impl ResourceMeteringReporter {
pub fn new(config: Config, scheduler: Scheduler<Task>, env: Arc<Environment>) -> Self {
let mut reporter = Self {
config,
env,
scheduler,
client: None,
reporting: Arc::new(AtomicBool::new(false)),
cpu_records_collector: None,
records: HashMap::default(),
others: HashMap::default(),
find_top_k: Vec::default(),
};
if reporter.config.should_report() {
reporter.init_client();
}
reporter
}
pub fn init_client(&mut self) {
let channel = {
let cb = ChannelBuilder::new(self.env.clone())
.keepalive_time(Duration::from_secs(10))
.keepalive_timeout(Duration::from_secs(3));
cb.connect(&self.config.agent_address)
};
self.client = Some(ResourceUsageAgentClient::new(channel));
if self.cpu_records_collector.is_none() {
self.cpu_records_collector = Some(register_collector(Box::new(
CpuRecordsCollector::new(self.scheduler.clone()),
)));
}
}
}
impl Runnable for ResourceMeteringReporter {
type Task = Task;
fn run(&mut self, task: Self::Task) {
match task {
Task::ConfigChange(new_config) => {
let old_config_enabled = self.config.enabled;
let old_config_agent_address = self.config.agent_address.clone();
self.config = new_config;
if!self.config.should_report() {
self.client.take();
self.cpu_records_collector.take();
} else if self.config.agent_address!= old_config_agent_address
|| self.config.enabled!= old_config_enabled
{
self.init_client();
}
}
Task::CpuRecords(records) => {
let timestamp_secs = records.begin_unix_time_secs;
for (tag, ms) in &records.records {
let tag = &tag.infos.extra_attachment;
if tag.is_empty() {
continue;
}
let ms = *ms as u32;
match self.records.get_mut(tag) {
Some((ts, cpu_time, total)) => {
if *ts.last().unwrap() == timestamp_secs {
*cpu_time.last_mut().unwrap() += ms;
} else {
ts.push(timestamp_secs);
cpu_time.push(ms);
}
*total += ms;
}
None => {
self.records
.insert(tag.clone(), (vec![timestamp_secs], vec![ms], ms));
}
}
}
if self.records.len() > self.config.max_resource_groups {
self.find_top_k.clear();
for (_, _, total) in self.records.values() {
self.find_top_k.push(*total);
}
pdqselect::select_by(
&mut self.find_top_k,
self.config.max_resource_groups,
|a, b| b.cmp(a),
);
let kth = self.find_top_k[self.config.max_resource_groups];
let others = &mut self.others;
self.records
.drain_filter(|_, (_, _, total)| *total <= kth)
.for_each(|(_, (secs_list, cpu_time_list, _))| {
secs_list
.into_iter()
.zip(cpu_time_list.into_iter())
.for_each(|(secs, cpu_time)| {
*others.entry(secs).or_insert(0) += cpu_time
})
});
}
}
}
}
fn shutdown(&mut self) {
self.cpu_records_collector.take();
self.client.take();
}
}
impl RunnableWithTimer for ResourceMeteringReporter {
fn on_timeout(&mut self) {
if self.records.is_empty() {
assert!(self.others.is_empty());
return;
}
let records = std::mem::take(&mut self.records);
let others = std::mem::take(&mut self.others);
if self.reporting.load(SeqCst) {
return;
}
if let Some(client) = self.client.as_ref() {
match client.report_cpu_time_opt(CallOption::default().timeout(Duration::from_secs(2)))
{
Ok((mut tx, rx)) => {
self.reporting.store(true, SeqCst);
let reporting = self.reporting.clone();
client.spawn(async move {
defer!(reporting.store(false, SeqCst));
for (tag, (timestamp_list, cpu_time_ms_list, _)) in records {
let mut req = CpuTimeRecord::default();
req.set_resource_group_tag(tag);
req.set_record_list_timestamp_sec(timestamp_list);
req.set_record_list_cpu_time_ms(cpu_time_ms_list);
if tx.send((req, WriteFlags::default())).await.is_err() {
return;
}
}
// others
if!others.is_empty() {
let timestamp_list = others.keys().cloned().collect::<Vec<_>>();
let cpu_time_ms_list = others.values().cloned().collect::<Vec<_>>();
let mut req = CpuTimeRecord::default();
req.set_record_list_timestamp_sec(timestamp_list);
req.set_record_list_cpu_time_ms(cpu_time_ms_list);
if tx.send((req, WriteFlags::default())).await.is_err() {
return;
}
}
if tx.close().await.is_err() {
return;
}
rx.await.ok();
});
}
Err(err) => {
warn!("failed to connect resource usage agent"; "error" =>?err);
}
}
}
}
fn get_interval(&self) -> Duration {
self.config.report_agent_interval.0
}
}
| new | identifier_name |
reporter.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use crate::cpu::collector::{register_collector, Collector, CollectorHandle};
use crate::cpu::recorder::CpuRecords;
use crate::Config;
use std::fmt::{self, Display, Formatter};
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::Arc;
use collections::HashMap;
use futures::SinkExt;
use grpcio::{CallOption, ChannelBuilder, Environment, WriteFlags};
use kvproto::resource_usage_agent::{CpuTimeRecord, ResourceUsageAgentClient};
use tikv_util::time::Duration;
use tikv_util::worker::{Runnable, RunnableWithTimer, Scheduler};
pub struct CpuRecordsCollector {
scheduler: Scheduler<Task>,
}
impl CpuRecordsCollector {
pub fn new(scheduler: Scheduler<Task>) -> Self {
Self { scheduler }
}
}
impl Collector for CpuRecordsCollector {
fn collect(&self, records: Arc<CpuRecords>) {
self.scheduler.schedule(Task::CpuRecords(records)).ok();
}
}
pub enum Task {
ConfigChange(Config),
CpuRecords(Arc<CpuRecords>),
}
impl Display for Task {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Task::ConfigChange(_) => {
write!(f, "ConfigChange")?;
}
Task::CpuRecords(_) => {
write!(f, "CpuRecords")?;
}
}
Ok(())
}
}
pub struct ResourceMeteringReporter {
config: Config,
env: Arc<Environment>,
scheduler: Scheduler<Task>,
// TODO: mock client for testing
client: Option<ResourceUsageAgentClient>,
reporting: Arc<AtomicBool>,
cpu_records_collector: Option<CollectorHandle>,
// resource_tag -> ([timestamp_secs], [cpu_time_ms], total_cpu_time_ms)
records: HashMap<Vec<u8>, (Vec<u64>, Vec<u32>, u32)>,
// timestamp_secs -> cpu_time_ms
others: HashMap<u64, u32>,
find_top_k: Vec<u32>,
}
impl ResourceMeteringReporter {
pub fn new(config: Config, scheduler: Scheduler<Task>, env: Arc<Environment>) -> Self {
let mut reporter = Self {
config,
env,
scheduler,
client: None,
reporting: Arc::new(AtomicBool::new(false)),
cpu_records_collector: None,
records: HashMap::default(),
others: HashMap::default(),
find_top_k: Vec::default(),
};
if reporter.config.should_report() {
reporter.init_client();
}
reporter
}
pub fn init_client(&mut self) |
}
impl Runnable for ResourceMeteringReporter {
type Task = Task;
fn run(&mut self, task: Self::Task) {
match task {
Task::ConfigChange(new_config) => {
let old_config_enabled = self.config.enabled;
let old_config_agent_address = self.config.agent_address.clone();
self.config = new_config;
if!self.config.should_report() {
self.client.take();
self.cpu_records_collector.take();
} else if self.config.agent_address!= old_config_agent_address
|| self.config.enabled!= old_config_enabled
{
self.init_client();
}
}
Task::CpuRecords(records) => {
let timestamp_secs = records.begin_unix_time_secs;
for (tag, ms) in &records.records {
let tag = &tag.infos.extra_attachment;
if tag.is_empty() {
continue;
}
let ms = *ms as u32;
match self.records.get_mut(tag) {
Some((ts, cpu_time, total)) => {
if *ts.last().unwrap() == timestamp_secs {
*cpu_time.last_mut().unwrap() += ms;
} else {
ts.push(timestamp_secs);
cpu_time.push(ms);
}
*total += ms;
}
None => {
self.records
.insert(tag.clone(), (vec![timestamp_secs], vec![ms], ms));
}
}
}
if self.records.len() > self.config.max_resource_groups {
self.find_top_k.clear();
for (_, _, total) in self.records.values() {
self.find_top_k.push(*total);
}
pdqselect::select_by(
&mut self.find_top_k,
self.config.max_resource_groups,
|a, b| b.cmp(a),
);
let kth = self.find_top_k[self.config.max_resource_groups];
let others = &mut self.others;
self.records
.drain_filter(|_, (_, _, total)| *total <= kth)
.for_each(|(_, (secs_list, cpu_time_list, _))| {
secs_list
.into_iter()
.zip(cpu_time_list.into_iter())
.for_each(|(secs, cpu_time)| {
*others.entry(secs).or_insert(0) += cpu_time
})
});
}
}
}
}
fn shutdown(&mut self) {
self.cpu_records_collector.take();
self.client.take();
}
}
impl RunnableWithTimer for ResourceMeteringReporter {
fn on_timeout(&mut self) {
if self.records.is_empty() {
assert!(self.others.is_empty());
return;
}
let records = std::mem::take(&mut self.records);
let others = std::mem::take(&mut self.others);
if self.reporting.load(SeqCst) {
return;
}
if let Some(client) = self.client.as_ref() {
match client.report_cpu_time_opt(CallOption::default().timeout(Duration::from_secs(2)))
{
Ok((mut tx, rx)) => {
self.reporting.store(true, SeqCst);
let reporting = self.reporting.clone();
client.spawn(async move {
defer!(reporting.store(false, SeqCst));
for (tag, (timestamp_list, cpu_time_ms_list, _)) in records {
let mut req = CpuTimeRecord::default();
req.set_resource_group_tag(tag);
req.set_record_list_timestamp_sec(timestamp_list);
req.set_record_list_cpu_time_ms(cpu_time_ms_list);
if tx.send((req, WriteFlags::default())).await.is_err() {
return;
}
}
// others
if!others.is_empty() {
let timestamp_list = others.keys().cloned().collect::<Vec<_>>();
let cpu_time_ms_list = others.values().cloned().collect::<Vec<_>>();
let mut req = CpuTimeRecord::default();
req.set_record_list_timestamp_sec(timestamp_list);
req.set_record_list_cpu_time_ms(cpu_time_ms_list);
if tx.send((req, WriteFlags::default())).await.is_err() {
return;
}
}
if tx.close().await.is_err() {
return;
}
rx.await.ok();
});
}
Err(err) => {
warn!("failed to connect resource usage agent"; "error" =>?err);
}
}
}
}
fn get_interval(&self) -> Duration {
self.config.report_agent_interval.0
}
}
| {
let channel = {
let cb = ChannelBuilder::new(self.env.clone())
.keepalive_time(Duration::from_secs(10))
.keepalive_timeout(Duration::from_secs(3));
cb.connect(&self.config.agent_address)
};
self.client = Some(ResourceUsageAgentClient::new(channel));
if self.cpu_records_collector.is_none() {
self.cpu_records_collector = Some(register_collector(Box::new(
CpuRecordsCollector::new(self.scheduler.clone()),
)));
}
} | identifier_body |
reporter.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use crate::cpu::collector::{register_collector, Collector, CollectorHandle};
use crate::cpu::recorder::CpuRecords;
use crate::Config;
use std::fmt::{self, Display, Formatter};
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::Arc;
use collections::HashMap;
use futures::SinkExt;
use grpcio::{CallOption, ChannelBuilder, Environment, WriteFlags};
use kvproto::resource_usage_agent::{CpuTimeRecord, ResourceUsageAgentClient};
use tikv_util::time::Duration;
use tikv_util::worker::{Runnable, RunnableWithTimer, Scheduler};
pub struct CpuRecordsCollector {
scheduler: Scheduler<Task>,
}
impl CpuRecordsCollector {
pub fn new(scheduler: Scheduler<Task>) -> Self {
Self { scheduler }
}
}
impl Collector for CpuRecordsCollector {
fn collect(&self, records: Arc<CpuRecords>) {
self.scheduler.schedule(Task::CpuRecords(records)).ok();
}
}
pub enum Task {
ConfigChange(Config),
CpuRecords(Arc<CpuRecords>),
}
impl Display for Task {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Task::ConfigChange(_) => {
write!(f, "ConfigChange")?;
}
Task::CpuRecords(_) => {
write!(f, "CpuRecords")?;
}
}
Ok(())
}
}
pub struct ResourceMeteringReporter {
config: Config,
env: Arc<Environment>,
scheduler: Scheduler<Task>,
// TODO: mock client for testing
client: Option<ResourceUsageAgentClient>,
reporting: Arc<AtomicBool>,
cpu_records_collector: Option<CollectorHandle>,
// resource_tag -> ([timestamp_secs], [cpu_time_ms], total_cpu_time_ms)
records: HashMap<Vec<u8>, (Vec<u64>, Vec<u32>, u32)>,
// timestamp_secs -> cpu_time_ms
others: HashMap<u64, u32>,
find_top_k: Vec<u32>,
}
impl ResourceMeteringReporter {
pub fn new(config: Config, scheduler: Scheduler<Task>, env: Arc<Environment>) -> Self {
let mut reporter = Self {
config,
env,
scheduler,
client: None,
reporting: Arc::new(AtomicBool::new(false)),
cpu_records_collector: None,
records: HashMap::default(),
others: HashMap::default(),
find_top_k: Vec::default(),
};
if reporter.config.should_report() {
reporter.init_client();
}
reporter
}
pub fn init_client(&mut self) {
let channel = {
let cb = ChannelBuilder::new(self.env.clone())
.keepalive_time(Duration::from_secs(10))
.keepalive_timeout(Duration::from_secs(3));
cb.connect(&self.config.agent_address)
};
self.client = Some(ResourceUsageAgentClient::new(channel));
if self.cpu_records_collector.is_none() {
self.cpu_records_collector = Some(register_collector(Box::new(
CpuRecordsCollector::new(self.scheduler.clone()),
)));
}
}
}
impl Runnable for ResourceMeteringReporter {
type Task = Task;
fn run(&mut self, task: Self::Task) {
match task {
Task::ConfigChange(new_config) => {
let old_config_enabled = self.config.enabled;
let old_config_agent_address = self.config.agent_address.clone();
self.config = new_config;
if!self.config.should_report() {
self.client.take();
self.cpu_records_collector.take();
} else if self.config.agent_address!= old_config_agent_address
|| self.config.enabled!= old_config_enabled
{
self.init_client();
}
}
Task::CpuRecords(records) => {
let timestamp_secs = records.begin_unix_time_secs;
for (tag, ms) in &records.records {
let tag = &tag.infos.extra_attachment;
if tag.is_empty() {
continue;
}
let ms = *ms as u32;
match self.records.get_mut(tag) {
Some((ts, cpu_time, total)) => {
if *ts.last().unwrap() == timestamp_secs {
*cpu_time.last_mut().unwrap() += ms;
} else {
ts.push(timestamp_secs);
cpu_time.push(ms);
}
*total += ms;
}
None => {
self.records
.insert(tag.clone(), (vec![timestamp_secs], vec![ms], ms));
}
}
}
if self.records.len() > self.config.max_resource_groups {
self.find_top_k.clear();
for (_, _, total) in self.records.values() {
self.find_top_k.push(*total);
}
pdqselect::select_by(
&mut self.find_top_k,
self.config.max_resource_groups,
|a, b| b.cmp(a),
);
let kth = self.find_top_k[self.config.max_resource_groups];
let others = &mut self.others;
self.records
.drain_filter(|_, (_, _, total)| *total <= kth)
.for_each(|(_, (secs_list, cpu_time_list, _))| {
secs_list
.into_iter()
.zip(cpu_time_list.into_iter())
.for_each(|(secs, cpu_time)| {
*others.entry(secs).or_insert(0) += cpu_time
})
});
}
}
}
}
fn shutdown(&mut self) {
self.cpu_records_collector.take();
self.client.take();
}
}
impl RunnableWithTimer for ResourceMeteringReporter {
fn on_timeout(&mut self) {
if self.records.is_empty() {
assert!(self.others.is_empty());
return;
}
let records = std::mem::take(&mut self.records);
let others = std::mem::take(&mut self.others);
if self.reporting.load(SeqCst) {
return;
}
if let Some(client) = self.client.as_ref() {
match client.report_cpu_time_opt(CallOption::default().timeout(Duration::from_secs(2)))
{
Ok((mut tx, rx)) => {
self.reporting.store(true, SeqCst);
let reporting = self.reporting.clone();
client.spawn(async move {
defer!(reporting.store(false, SeqCst)); | req.set_record_list_timestamp_sec(timestamp_list);
req.set_record_list_cpu_time_ms(cpu_time_ms_list);
if tx.send((req, WriteFlags::default())).await.is_err() {
return;
}
}
// others
if!others.is_empty() {
let timestamp_list = others.keys().cloned().collect::<Vec<_>>();
let cpu_time_ms_list = others.values().cloned().collect::<Vec<_>>();
let mut req = CpuTimeRecord::default();
req.set_record_list_timestamp_sec(timestamp_list);
req.set_record_list_cpu_time_ms(cpu_time_ms_list);
if tx.send((req, WriteFlags::default())).await.is_err() {
return;
}
}
if tx.close().await.is_err() {
return;
}
rx.await.ok();
});
}
Err(err) => {
warn!("failed to connect resource usage agent"; "error" =>?err);
}
}
}
}
fn get_interval(&self) -> Duration {
self.config.report_agent_interval.0
}
} |
for (tag, (timestamp_list, cpu_time_ms_list, _)) in records {
let mut req = CpuTimeRecord::default();
req.set_resource_group_tag(tag); | random_line_split |
mod.rs | // This file is released under the same terms as Rust itself.
pub mod github_status;
pub mod jenkins;
use config::PipelinesConfig;
use hyper::Url;
use pipeline::{GetPipelineId, PipelineId};
use vcs::Commit;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct CiId(pub i32);
#[derive(Clone, Debug)]
pub enum Message {
StartBuild(CiId, Commit),
}
#[derive(Clone, Debug)]
pub enum | {
BuildStarted(CiId, Commit, Option<Url>),
BuildSucceeded(CiId, Commit, Option<Url>),
BuildFailed(CiId, Commit, Option<Url>),
}
impl GetPipelineId for Event {
fn pipeline_id<C: PipelinesConfig +?Sized>(&self, config: &C) -> PipelineId {
let ci_id = match *self {
Event::BuildStarted(i, _, _) => i,
Event::BuildSucceeded(i, _, _) => i,
Event::BuildFailed(i, _, _) => i,
};
config.by_ci_id(ci_id).pipeline_id
}
} | Event | identifier_name |
mod.rs | // This file is released under the same terms as Rust itself.
pub mod github_status;
pub mod jenkins;
use config::PipelinesConfig;
use hyper::Url;
use pipeline::{GetPipelineId, PipelineId};
use vcs::Commit;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct CiId(pub i32);
#[derive(Clone, Debug)]
pub enum Message {
StartBuild(CiId, Commit),
}
#[derive(Clone, Debug)]
pub enum Event {
BuildStarted(CiId, Commit, Option<Url>), |
impl GetPipelineId for Event {
fn pipeline_id<C: PipelinesConfig +?Sized>(&self, config: &C) -> PipelineId {
let ci_id = match *self {
Event::BuildStarted(i, _, _) => i,
Event::BuildSucceeded(i, _, _) => i,
Event::BuildFailed(i, _, _) => i,
};
config.by_ci_id(ci_id).pipeline_id
}
} | BuildSucceeded(CiId, Commit, Option<Url>),
BuildFailed(CiId, Commit, Option<Url>),
} | random_line_split |
arm.rs | //! Contains arm-specific types
use core::convert::From;
use core::{cmp, fmt, slice};
use capstone_sys::{
arm_op_mem, arm_op_type, cs_arm, cs_arm_op, arm_shifter,
cs_arm_op__bindgen_ty_2};
use libc::c_uint;
pub use crate::arch::arch_builder::arm::*;
use crate::arch::DetailsArchInsn;
use crate::instruction::{RegId, RegIdInt};
pub use capstone_sys::arm_insn_group as ArmInsnGroup;
pub use capstone_sys::arm_insn as ArmInsn;
pub use capstone_sys::arm_reg as ArmReg;
pub use capstone_sys::arm_vectordata_type as ArmVectorData;
pub use capstone_sys::arm_cpsmode_type as ArmCPSMode;
pub use capstone_sys::arm_cpsflag_type as ArmCPSFlag;
pub use capstone_sys::arm_cc as ArmCC;
pub use capstone_sys::arm_mem_barrier as ArmMemBarrier;
pub use capstone_sys::arm_setend_type as ArmSetendType;
/// Contains ARM-specific details for an instruction
pub struct ArmInsnDetail<'a>(pub(crate) &'a cs_arm);
/// ARM shift amount
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum ArmShift {
Invalid,
/// Arithmetic shift right (immediate)
Asr(u32),
/// Logical shift lift (immediate)
Lsl(u32),
/// Logical shift right (immediate)
Lsr(u32),
/// Rotate right (immediate)
Ror(u32),
/// Rotate right with extend (immediate)
Rrx(u32),
/// Arithmetic shift right (register)
AsrReg(RegId),
/// Logical shift lift (register)
LslReg(RegId),
/// Logical shift right (register)
LsrReg(RegId),
/// Rotate right (register)
RorReg(RegId),
/// Rotate right with extend (register)
RrxReg(RegId),
}
impl ArmShift {
fn new(type_: arm_shifter, value: c_uint) -> ArmShift {
use self::arm_shifter::*;
use self::ArmShift::*;
macro_rules! arm_shift_match {
(
imm = [ $( $imm_r_enum:ident = $imm_c_enum:ident, )* ]
reg = [ $( $reg_r_enum:ident = $reg_c_enum:ident, )* ]
) => {
match type_ {
ARM_SFT_INVALID => Invalid,
$(
$imm_c_enum => $imm_r_enum(value as u32),
)*
$(
$reg_c_enum => $reg_r_enum(RegId(value as RegIdInt)),
)*
}
}
}
arm_shift_match!(
imm = [
Asr = ARM_SFT_ASR, Lsl = ARM_SFT_LSL, Lsr = ARM_SFT_LSR,
Ror = ARM_SFT_ROR, Rrx = ARM_SFT_RRX,
]
reg = [
AsrReg = ARM_SFT_ASR_REG, LslReg = ARM_SFT_LSL_REG, LsrReg = ARM_SFT_LSR_REG,
RorReg = ARM_SFT_ROR_REG, RrxReg = ARM_SFT_RRX_REG,
]
)
}
}
impl ArmOperandType {
fn new(op_type: arm_op_type, value: cs_arm_op__bindgen_ty_2) -> ArmOperandType {
use self::arm_op_type::*;
use self::ArmOperandType::*;
match op_type {
ARM_OP_INVALID => Invalid,
ARM_OP_REG => Reg(RegId(unsafe { value.reg } as RegIdInt)),
ARM_OP_IMM => Imm(unsafe { value.imm }),
ARM_OP_MEM => Mem(ArmOpMem(unsafe { value.mem })),
ARM_OP_FP => Fp(unsafe { value.fp }),
ARM_OP_CIMM => Cimm(unsafe { value.imm }),
ARM_OP_PIMM => Pimm(unsafe { value.imm }),
ARM_OP_SETEND => Setend(unsafe { value.setend }),
ARM_OP_SYSREG => SysReg(RegId(unsafe { value.reg } as RegIdInt)),
}
}
}
/// ARM operand
#[derive(Clone, Debug, PartialEq)]
pub struct ArmOperand {
/// Vector Index for some vector operands
pub vector_index: Option<u32>,
/// Whether operand is subtracted
pub subtracted: bool,
pub shift: ArmShift,
/// Operand type
pub op_type: ArmOperandType,
}
/// ARM operand
#[derive(Clone, Debug, PartialEq)]
pub enum ArmOperandType {
/// Register
Reg(RegId),
/// Immediate
Imm(i32),
/// Memory
Mem(ArmOpMem),
/// Floating point
Fp(f64),
/// C-IMM
Cimm(i32),
/// P-IMM
Pimm(i32),
/// SETEND instruction endianness
Setend(ArmSetendType),
/// Sysreg
SysReg(RegId),
/// Invalid
Invalid,
}
/// ARM memory operand
#[derive(Debug, Copy, Clone)]
pub struct ArmOpMem(pub(crate) arm_op_mem);
impl<'a> ArmInsnDetail<'a> {
/// Whether the instruction is a user mode
pub fn usermode(&self) -> bool |
/// Vector size
pub fn vector_size(&self) -> i32 {
self.0.vector_size as i32
}
/// Type of vector data
pub fn vector_data(&self) -> ArmVectorData {
self.0.vector_data
}
/// CPS mode for CPS instruction
pub fn cps_mode(&self) -> ArmCPSMode {
self.0.cps_mode
}
/// CPS flag for CPS instruction
pub fn cps_flag(&self) -> ArmCPSFlag {
self.0.cps_flag
}
/// Condition codes
pub fn cc(&self) -> ArmCC {
self.0.cc
}
/// Whether this insn updates flags
pub fn update_flags(&self) -> bool {
self.0.update_flags
}
/// Whether writeback is required
pub fn writeback(&self) -> bool {
self.0.writeback
}
/// Memory barrier
pub fn mem_barrier(&self) -> ArmMemBarrier {
self.0.mem_barrier
}
}
impl_PartialEq_repr_fields!(ArmInsnDetail<'a> [ 'a ];
usermode, vector_size, vector_data, cps_mode, cps_flag, cc, update_flags, writeback,
mem_barrier, operands
);
impl ArmOpMem {
/// Base register
pub fn base(&self) -> RegId {
RegId(self.0.base as RegIdInt)
}
/// Index value
pub fn index(&self) -> RegId {
RegId(self.0.index as RegIdInt)
}
/// Scale for index register (can be 1, or -1)
pub fn scale(&self) -> i32 {
self.0.scale as i32
}
/// Disp value
pub fn disp(&self) -> i32 {
self.0.disp as i32
}
}
impl_PartialEq_repr_fields!(ArmOpMem;
base, index, scale, disp
);
impl cmp::Eq for ArmOpMem {}
impl Default for ArmOperand {
fn default() -> Self {
ArmOperand {
vector_index: None,
subtracted: false,
shift: ArmShift::Invalid,
op_type: ArmOperandType::Invalid
}
}
}
impl<'a> From<&'a cs_arm_op> for ArmOperand {
fn from(op: &cs_arm_op) -> ArmOperand {
let shift = ArmShift::new(op.shift.type_, op.shift.value);
let op_type = ArmOperandType::new(op.type_, op.__bindgen_anon_1);
let vector_index = if op.vector_index >= 0 {
Some(op.vector_index as u32)
} else {
None
};
ArmOperand {
vector_index,
shift,
op_type,
subtracted: op.subtracted,
}
}
}
def_arch_details_struct!(
InsnDetail = ArmInsnDetail;
Operand = ArmOperand;
OperandIterator = ArmOperandIterator;
OperandIteratorLife = ArmOperandIterator<'a>;
[ pub struct ArmOperandIterator<'a>(slice::Iter<'a, cs_arm_op>); ]
cs_arch_op = cs_arm_op;
cs_arch = cs_arm;
);
#[cfg(test)]
mod test {
use super::*;
use capstone_sys::*;
#[test]
fn test_armshift() {
use super::arm_shifter::*;
use super::ArmShift::*;
use libc::c_uint;
fn t(shift_type_value: (arm_shifter, c_uint), arm_shift: ArmShift) {
let (shift_type, value) = shift_type_value;
assert_eq!(arm_shift, ArmShift::new(shift_type, value));
}
t((ARM_SFT_INVALID, 0), Invalid);
t((ARM_SFT_ASR, 0), Asr(0));
t((ARM_SFT_ASR_REG, 42), AsrReg(RegId(42)));
t((ARM_SFT_RRX_REG, 42), RrxReg(RegId(42)));
}
#[test]
fn test_arm_op_type() {
use super::arm_op_type::*;
use super::ArmOperandType::*;
fn t(
op_type_value: (arm_op_type, cs_arm_op__bindgen_ty_2),
expected_op_type: ArmOperandType,
) {
let (op_type, op_value) = op_type_value;
let op_type = ArmOperandType::new(op_type, op_value);
assert_eq!(expected_op_type, op_type);
}
t(
(ARM_OP_INVALID, cs_arm_op__bindgen_ty_2 { reg: 0 }),
Invalid,
);
t(
(ARM_OP_REG, cs_arm_op__bindgen_ty_2 { reg: 0 }),
Reg(RegId(0)),
);
}
#[test]
fn test_arm_insn_detail_eq() {
let a1 = cs_arm {
usermode: false,
vector_size: 0,
vector_data: arm_vectordata_type::ARM_VECTORDATA_INVALID,
cps_mode: arm_cpsmode_type::ARM_CPSMODE_INVALID,
cps_flag: arm_cpsflag_type::ARM_CPSFLAG_INVALID,
cc: arm_cc::ARM_CC_INVALID,
update_flags: false,
writeback: false,
mem_barrier: arm_mem_barrier::ARM_MB_INVALID,
op_count: 0,
operands: [
cs_arm_op {
vector_index: 0,
shift: cs_arm_op__bindgen_ty_1 {
type_: arm_shifter::ARM_SFT_INVALID,
value: 0
},
type_: arm_op_type::ARM_OP_INVALID,
__bindgen_anon_1: cs_arm_op__bindgen_ty_2 { imm: 0 },
subtracted: false,
access: 0,
neon_lane: 0,
}
; 36]
};
let a2 = cs_arm {
usermode: true,
..a1
};
let a3 = cs_arm {
op_count: 20,
..a1
};
let a4 = cs_arm {
op_count: 19,
..a1
};
let a4_clone = a4.clone();
assert_eq!(ArmInsnDetail(&a1), ArmInsnDetail(&a1));
assert_ne!(ArmInsnDetail(&a1), ArmInsnDetail(&a2));
assert_ne!(ArmInsnDetail(&a1), ArmInsnDetail(&a3));
assert_ne!(ArmInsnDetail(&a3), ArmInsnDetail(&a4));
assert_eq!(ArmInsnDetail(&a4), ArmInsnDetail(&a4_clone));
}
}
| {
self.0.usermode
} | identifier_body |
arm.rs | //! Contains arm-specific types
use core::convert::From;
use core::{cmp, fmt, slice};
use capstone_sys::{
arm_op_mem, arm_op_type, cs_arm, cs_arm_op, arm_shifter,
cs_arm_op__bindgen_ty_2}; | use libc::c_uint;
pub use crate::arch::arch_builder::arm::*;
use crate::arch::DetailsArchInsn;
use crate::instruction::{RegId, RegIdInt};
pub use capstone_sys::arm_insn_group as ArmInsnGroup;
pub use capstone_sys::arm_insn as ArmInsn;
pub use capstone_sys::arm_reg as ArmReg;
pub use capstone_sys::arm_vectordata_type as ArmVectorData;
pub use capstone_sys::arm_cpsmode_type as ArmCPSMode;
pub use capstone_sys::arm_cpsflag_type as ArmCPSFlag;
pub use capstone_sys::arm_cc as ArmCC;
pub use capstone_sys::arm_mem_barrier as ArmMemBarrier;
pub use capstone_sys::arm_setend_type as ArmSetendType;
/// Contains ARM-specific details for an instruction
pub struct ArmInsnDetail<'a>(pub(crate) &'a cs_arm);
/// ARM shift amount
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum ArmShift {
Invalid,
/// Arithmetic shift right (immediate)
Asr(u32),
/// Logical shift lift (immediate)
Lsl(u32),
/// Logical shift right (immediate)
Lsr(u32),
/// Rotate right (immediate)
Ror(u32),
/// Rotate right with extend (immediate)
Rrx(u32),
/// Arithmetic shift right (register)
AsrReg(RegId),
/// Logical shift lift (register)
LslReg(RegId),
/// Logical shift right (register)
LsrReg(RegId),
/// Rotate right (register)
RorReg(RegId),
/// Rotate right with extend (register)
RrxReg(RegId),
}
impl ArmShift {
fn new(type_: arm_shifter, value: c_uint) -> ArmShift {
use self::arm_shifter::*;
use self::ArmShift::*;
macro_rules! arm_shift_match {
(
imm = [ $( $imm_r_enum:ident = $imm_c_enum:ident, )* ]
reg = [ $( $reg_r_enum:ident = $reg_c_enum:ident, )* ]
) => {
match type_ {
ARM_SFT_INVALID => Invalid,
$(
$imm_c_enum => $imm_r_enum(value as u32),
)*
$(
$reg_c_enum => $reg_r_enum(RegId(value as RegIdInt)),
)*
}
}
}
arm_shift_match!(
imm = [
Asr = ARM_SFT_ASR, Lsl = ARM_SFT_LSL, Lsr = ARM_SFT_LSR,
Ror = ARM_SFT_ROR, Rrx = ARM_SFT_RRX,
]
reg = [
AsrReg = ARM_SFT_ASR_REG, LslReg = ARM_SFT_LSL_REG, LsrReg = ARM_SFT_LSR_REG,
RorReg = ARM_SFT_ROR_REG, RrxReg = ARM_SFT_RRX_REG,
]
)
}
}
impl ArmOperandType {
fn new(op_type: arm_op_type, value: cs_arm_op__bindgen_ty_2) -> ArmOperandType {
use self::arm_op_type::*;
use self::ArmOperandType::*;
match op_type {
ARM_OP_INVALID => Invalid,
ARM_OP_REG => Reg(RegId(unsafe { value.reg } as RegIdInt)),
ARM_OP_IMM => Imm(unsafe { value.imm }),
ARM_OP_MEM => Mem(ArmOpMem(unsafe { value.mem })),
ARM_OP_FP => Fp(unsafe { value.fp }),
ARM_OP_CIMM => Cimm(unsafe { value.imm }),
ARM_OP_PIMM => Pimm(unsafe { value.imm }),
ARM_OP_SETEND => Setend(unsafe { value.setend }),
ARM_OP_SYSREG => SysReg(RegId(unsafe { value.reg } as RegIdInt)),
}
}
}
/// ARM operand
#[derive(Clone, Debug, PartialEq)]
pub struct ArmOperand {
/// Vector Index for some vector operands
pub vector_index: Option<u32>,
/// Whether operand is subtracted
pub subtracted: bool,
pub shift: ArmShift,
/// Operand type
pub op_type: ArmOperandType,
}
/// ARM operand
#[derive(Clone, Debug, PartialEq)]
pub enum ArmOperandType {
/// Register
Reg(RegId),
/// Immediate
Imm(i32),
/// Memory
Mem(ArmOpMem),
/// Floating point
Fp(f64),
/// C-IMM
Cimm(i32),
/// P-IMM
Pimm(i32),
/// SETEND instruction endianness
Setend(ArmSetendType),
/// Sysreg
SysReg(RegId),
/// Invalid
Invalid,
}
/// ARM memory operand
#[derive(Debug, Copy, Clone)]
pub struct ArmOpMem(pub(crate) arm_op_mem);
impl<'a> ArmInsnDetail<'a> {
/// Whether the instruction is a user mode
pub fn usermode(&self) -> bool {
self.0.usermode
}
/// Vector size
pub fn vector_size(&self) -> i32 {
self.0.vector_size as i32
}
/// Type of vector data
pub fn vector_data(&self) -> ArmVectorData {
self.0.vector_data
}
/// CPS mode for CPS instruction
pub fn cps_mode(&self) -> ArmCPSMode {
self.0.cps_mode
}
/// CPS flag for CPS instruction
pub fn cps_flag(&self) -> ArmCPSFlag {
self.0.cps_flag
}
/// Condition codes
pub fn cc(&self) -> ArmCC {
self.0.cc
}
/// Whether this insn updates flags
pub fn update_flags(&self) -> bool {
self.0.update_flags
}
/// Whether writeback is required
pub fn writeback(&self) -> bool {
self.0.writeback
}
/// Memory barrier
pub fn mem_barrier(&self) -> ArmMemBarrier {
self.0.mem_barrier
}
}
impl_PartialEq_repr_fields!(ArmInsnDetail<'a> [ 'a ];
usermode, vector_size, vector_data, cps_mode, cps_flag, cc, update_flags, writeback,
mem_barrier, operands
);
impl ArmOpMem {
/// Base register
pub fn base(&self) -> RegId {
RegId(self.0.base as RegIdInt)
}
/// Index value
pub fn index(&self) -> RegId {
RegId(self.0.index as RegIdInt)
}
/// Scale for index register (can be 1, or -1)
pub fn scale(&self) -> i32 {
self.0.scale as i32
}
/// Disp value
pub fn disp(&self) -> i32 {
self.0.disp as i32
}
}
impl_PartialEq_repr_fields!(ArmOpMem;
base, index, scale, disp
);
impl cmp::Eq for ArmOpMem {}
impl Default for ArmOperand {
fn default() -> Self {
ArmOperand {
vector_index: None,
subtracted: false,
shift: ArmShift::Invalid,
op_type: ArmOperandType::Invalid
}
}
}
impl<'a> From<&'a cs_arm_op> for ArmOperand {
fn from(op: &cs_arm_op) -> ArmOperand {
let shift = ArmShift::new(op.shift.type_, op.shift.value);
let op_type = ArmOperandType::new(op.type_, op.__bindgen_anon_1);
let vector_index = if op.vector_index >= 0 {
Some(op.vector_index as u32)
} else {
None
};
ArmOperand {
vector_index,
shift,
op_type,
subtracted: op.subtracted,
}
}
}
def_arch_details_struct!(
InsnDetail = ArmInsnDetail;
Operand = ArmOperand;
OperandIterator = ArmOperandIterator;
OperandIteratorLife = ArmOperandIterator<'a>;
[ pub struct ArmOperandIterator<'a>(slice::Iter<'a, cs_arm_op>); ]
cs_arch_op = cs_arm_op;
cs_arch = cs_arm;
);
#[cfg(test)]
mod test {
use super::*;
use capstone_sys::*;
#[test]
fn test_armshift() {
use super::arm_shifter::*;
use super::ArmShift::*;
use libc::c_uint;
fn t(shift_type_value: (arm_shifter, c_uint), arm_shift: ArmShift) {
let (shift_type, value) = shift_type_value;
assert_eq!(arm_shift, ArmShift::new(shift_type, value));
}
t((ARM_SFT_INVALID, 0), Invalid);
t((ARM_SFT_ASR, 0), Asr(0));
t((ARM_SFT_ASR_REG, 42), AsrReg(RegId(42)));
t((ARM_SFT_RRX_REG, 42), RrxReg(RegId(42)));
}
#[test]
fn test_arm_op_type() {
use super::arm_op_type::*;
use super::ArmOperandType::*;
fn t(
op_type_value: (arm_op_type, cs_arm_op__bindgen_ty_2),
expected_op_type: ArmOperandType,
) {
let (op_type, op_value) = op_type_value;
let op_type = ArmOperandType::new(op_type, op_value);
assert_eq!(expected_op_type, op_type);
}
t(
(ARM_OP_INVALID, cs_arm_op__bindgen_ty_2 { reg: 0 }),
Invalid,
);
t(
(ARM_OP_REG, cs_arm_op__bindgen_ty_2 { reg: 0 }),
Reg(RegId(0)),
);
}
#[test]
fn test_arm_insn_detail_eq() {
let a1 = cs_arm {
usermode: false,
vector_size: 0,
vector_data: arm_vectordata_type::ARM_VECTORDATA_INVALID,
cps_mode: arm_cpsmode_type::ARM_CPSMODE_INVALID,
cps_flag: arm_cpsflag_type::ARM_CPSFLAG_INVALID,
cc: arm_cc::ARM_CC_INVALID,
update_flags: false,
writeback: false,
mem_barrier: arm_mem_barrier::ARM_MB_INVALID,
op_count: 0,
operands: [
cs_arm_op {
vector_index: 0,
shift: cs_arm_op__bindgen_ty_1 {
type_: arm_shifter::ARM_SFT_INVALID,
value: 0
},
type_: arm_op_type::ARM_OP_INVALID,
__bindgen_anon_1: cs_arm_op__bindgen_ty_2 { imm: 0 },
subtracted: false,
access: 0,
neon_lane: 0,
}
; 36]
};
let a2 = cs_arm {
usermode: true,
..a1
};
let a3 = cs_arm {
op_count: 20,
..a1
};
let a4 = cs_arm {
op_count: 19,
..a1
};
let a4_clone = a4.clone();
assert_eq!(ArmInsnDetail(&a1), ArmInsnDetail(&a1));
assert_ne!(ArmInsnDetail(&a1), ArmInsnDetail(&a2));
assert_ne!(ArmInsnDetail(&a1), ArmInsnDetail(&a3));
assert_ne!(ArmInsnDetail(&a3), ArmInsnDetail(&a4));
assert_eq!(ArmInsnDetail(&a4), ArmInsnDetail(&a4_clone));
}
} | random_line_split |
|
arm.rs | //! Contains arm-specific types
use core::convert::From;
use core::{cmp, fmt, slice};
use capstone_sys::{
arm_op_mem, arm_op_type, cs_arm, cs_arm_op, arm_shifter,
cs_arm_op__bindgen_ty_2};
use libc::c_uint;
pub use crate::arch::arch_builder::arm::*;
use crate::arch::DetailsArchInsn;
use crate::instruction::{RegId, RegIdInt};
pub use capstone_sys::arm_insn_group as ArmInsnGroup;
pub use capstone_sys::arm_insn as ArmInsn;
pub use capstone_sys::arm_reg as ArmReg;
pub use capstone_sys::arm_vectordata_type as ArmVectorData;
pub use capstone_sys::arm_cpsmode_type as ArmCPSMode;
pub use capstone_sys::arm_cpsflag_type as ArmCPSFlag;
pub use capstone_sys::arm_cc as ArmCC;
pub use capstone_sys::arm_mem_barrier as ArmMemBarrier;
pub use capstone_sys::arm_setend_type as ArmSetendType;
/// Contains ARM-specific details for an instruction
pub struct ArmInsnDetail<'a>(pub(crate) &'a cs_arm);
/// ARM shift amount
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum ArmShift {
Invalid,
/// Arithmetic shift right (immediate)
Asr(u32),
/// Logical shift lift (immediate)
Lsl(u32),
/// Logical shift right (immediate)
Lsr(u32),
/// Rotate right (immediate)
Ror(u32),
/// Rotate right with extend (immediate)
Rrx(u32),
/// Arithmetic shift right (register)
AsrReg(RegId),
/// Logical shift lift (register)
LslReg(RegId),
/// Logical shift right (register)
LsrReg(RegId),
/// Rotate right (register)
RorReg(RegId),
/// Rotate right with extend (register)
RrxReg(RegId),
}
impl ArmShift {
fn new(type_: arm_shifter, value: c_uint) -> ArmShift {
use self::arm_shifter::*;
use self::ArmShift::*;
macro_rules! arm_shift_match {
(
imm = [ $( $imm_r_enum:ident = $imm_c_enum:ident, )* ]
reg = [ $( $reg_r_enum:ident = $reg_c_enum:ident, )* ]
) => {
match type_ {
ARM_SFT_INVALID => Invalid,
$(
$imm_c_enum => $imm_r_enum(value as u32),
)*
$(
$reg_c_enum => $reg_r_enum(RegId(value as RegIdInt)),
)*
}
}
}
arm_shift_match!(
imm = [
Asr = ARM_SFT_ASR, Lsl = ARM_SFT_LSL, Lsr = ARM_SFT_LSR,
Ror = ARM_SFT_ROR, Rrx = ARM_SFT_RRX,
]
reg = [
AsrReg = ARM_SFT_ASR_REG, LslReg = ARM_SFT_LSL_REG, LsrReg = ARM_SFT_LSR_REG,
RorReg = ARM_SFT_ROR_REG, RrxReg = ARM_SFT_RRX_REG,
]
)
}
}
impl ArmOperandType {
fn new(op_type: arm_op_type, value: cs_arm_op__bindgen_ty_2) -> ArmOperandType {
use self::arm_op_type::*;
use self::ArmOperandType::*;
match op_type {
ARM_OP_INVALID => Invalid,
ARM_OP_REG => Reg(RegId(unsafe { value.reg } as RegIdInt)),
ARM_OP_IMM => Imm(unsafe { value.imm }),
ARM_OP_MEM => Mem(ArmOpMem(unsafe { value.mem })),
ARM_OP_FP => Fp(unsafe { value.fp }),
ARM_OP_CIMM => Cimm(unsafe { value.imm }),
ARM_OP_PIMM => Pimm(unsafe { value.imm }),
ARM_OP_SETEND => Setend(unsafe { value.setend }),
ARM_OP_SYSREG => SysReg(RegId(unsafe { value.reg } as RegIdInt)),
}
}
}
/// ARM operand
#[derive(Clone, Debug, PartialEq)]
pub struct ArmOperand {
/// Vector Index for some vector operands
pub vector_index: Option<u32>,
/// Whether operand is subtracted
pub subtracted: bool,
pub shift: ArmShift,
/// Operand type
pub op_type: ArmOperandType,
}
/// ARM operand
#[derive(Clone, Debug, PartialEq)]
pub enum ArmOperandType {
/// Register
Reg(RegId),
/// Immediate
Imm(i32),
/// Memory
Mem(ArmOpMem),
/// Floating point
Fp(f64),
/// C-IMM
Cimm(i32),
/// P-IMM
Pimm(i32),
/// SETEND instruction endianness
Setend(ArmSetendType),
/// Sysreg
SysReg(RegId),
/// Invalid
Invalid,
}
/// ARM memory operand
#[derive(Debug, Copy, Clone)]
pub struct ArmOpMem(pub(crate) arm_op_mem);
impl<'a> ArmInsnDetail<'a> {
/// Whether the instruction is a user mode
pub fn usermode(&self) -> bool {
self.0.usermode
}
/// Vector size
pub fn vector_size(&self) -> i32 {
self.0.vector_size as i32
}
/// Type of vector data
pub fn vector_data(&self) -> ArmVectorData {
self.0.vector_data
}
/// CPS mode for CPS instruction
pub fn cps_mode(&self) -> ArmCPSMode {
self.0.cps_mode
}
/// CPS flag for CPS instruction
pub fn cps_flag(&self) -> ArmCPSFlag {
self.0.cps_flag
}
/// Condition codes
pub fn cc(&self) -> ArmCC {
self.0.cc
}
/// Whether this insn updates flags
pub fn update_flags(&self) -> bool {
self.0.update_flags
}
/// Whether writeback is required
pub fn writeback(&self) -> bool {
self.0.writeback
}
/// Memory barrier
pub fn mem_barrier(&self) -> ArmMemBarrier {
self.0.mem_barrier
}
}
impl_PartialEq_repr_fields!(ArmInsnDetail<'a> [ 'a ];
usermode, vector_size, vector_data, cps_mode, cps_flag, cc, update_flags, writeback,
mem_barrier, operands
);
impl ArmOpMem {
/// Base register
pub fn base(&self) -> RegId {
RegId(self.0.base as RegIdInt)
}
/// Index value
pub fn | (&self) -> RegId {
RegId(self.0.index as RegIdInt)
}
/// Scale for index register (can be 1, or -1)
pub fn scale(&self) -> i32 {
self.0.scale as i32
}
/// Disp value
pub fn disp(&self) -> i32 {
self.0.disp as i32
}
}
impl_PartialEq_repr_fields!(ArmOpMem;
base, index, scale, disp
);
impl cmp::Eq for ArmOpMem {}
impl Default for ArmOperand {
fn default() -> Self {
ArmOperand {
vector_index: None,
subtracted: false,
shift: ArmShift::Invalid,
op_type: ArmOperandType::Invalid
}
}
}
impl<'a> From<&'a cs_arm_op> for ArmOperand {
fn from(op: &cs_arm_op) -> ArmOperand {
let shift = ArmShift::new(op.shift.type_, op.shift.value);
let op_type = ArmOperandType::new(op.type_, op.__bindgen_anon_1);
let vector_index = if op.vector_index >= 0 {
Some(op.vector_index as u32)
} else {
None
};
ArmOperand {
vector_index,
shift,
op_type,
subtracted: op.subtracted,
}
}
}
def_arch_details_struct!(
InsnDetail = ArmInsnDetail;
Operand = ArmOperand;
OperandIterator = ArmOperandIterator;
OperandIteratorLife = ArmOperandIterator<'a>;
[ pub struct ArmOperandIterator<'a>(slice::Iter<'a, cs_arm_op>); ]
cs_arch_op = cs_arm_op;
cs_arch = cs_arm;
);
#[cfg(test)]
mod test {
use super::*;
use capstone_sys::*;
#[test]
fn test_armshift() {
use super::arm_shifter::*;
use super::ArmShift::*;
use libc::c_uint;
fn t(shift_type_value: (arm_shifter, c_uint), arm_shift: ArmShift) {
let (shift_type, value) = shift_type_value;
assert_eq!(arm_shift, ArmShift::new(shift_type, value));
}
t((ARM_SFT_INVALID, 0), Invalid);
t((ARM_SFT_ASR, 0), Asr(0));
t((ARM_SFT_ASR_REG, 42), AsrReg(RegId(42)));
t((ARM_SFT_RRX_REG, 42), RrxReg(RegId(42)));
}
#[test]
fn test_arm_op_type() {
use super::arm_op_type::*;
use super::ArmOperandType::*;
fn t(
op_type_value: (arm_op_type, cs_arm_op__bindgen_ty_2),
expected_op_type: ArmOperandType,
) {
let (op_type, op_value) = op_type_value;
let op_type = ArmOperandType::new(op_type, op_value);
assert_eq!(expected_op_type, op_type);
}
t(
(ARM_OP_INVALID, cs_arm_op__bindgen_ty_2 { reg: 0 }),
Invalid,
);
t(
(ARM_OP_REG, cs_arm_op__bindgen_ty_2 { reg: 0 }),
Reg(RegId(0)),
);
}
#[test]
fn test_arm_insn_detail_eq() {
let a1 = cs_arm {
usermode: false,
vector_size: 0,
vector_data: arm_vectordata_type::ARM_VECTORDATA_INVALID,
cps_mode: arm_cpsmode_type::ARM_CPSMODE_INVALID,
cps_flag: arm_cpsflag_type::ARM_CPSFLAG_INVALID,
cc: arm_cc::ARM_CC_INVALID,
update_flags: false,
writeback: false,
mem_barrier: arm_mem_barrier::ARM_MB_INVALID,
op_count: 0,
operands: [
cs_arm_op {
vector_index: 0,
shift: cs_arm_op__bindgen_ty_1 {
type_: arm_shifter::ARM_SFT_INVALID,
value: 0
},
type_: arm_op_type::ARM_OP_INVALID,
__bindgen_anon_1: cs_arm_op__bindgen_ty_2 { imm: 0 },
subtracted: false,
access: 0,
neon_lane: 0,
}
; 36]
};
let a2 = cs_arm {
usermode: true,
..a1
};
let a3 = cs_arm {
op_count: 20,
..a1
};
let a4 = cs_arm {
op_count: 19,
..a1
};
let a4_clone = a4.clone();
assert_eq!(ArmInsnDetail(&a1), ArmInsnDetail(&a1));
assert_ne!(ArmInsnDetail(&a1), ArmInsnDetail(&a2));
assert_ne!(ArmInsnDetail(&a1), ArmInsnDetail(&a3));
assert_ne!(ArmInsnDetail(&a3), ArmInsnDetail(&a4));
assert_eq!(ArmInsnDetail(&a4), ArmInsnDetail(&a4_clone));
}
}
| index | identifier_name |
absurd_extreme_comparisons.rs | use rustc_hir::{BinOpKind, Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use clippy_utils::comparisons::{normalize_comparison, Rel};
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::source::snippet;
use clippy_utils::ty::is_isize_or_usize;
use clippy_utils::{clip, int_bits, unsext};
declare_clippy_lint! {
/// ### What it does
/// Checks for comparisons where one side of the relation is
/// either the minimum or maximum value for its type and warns if it involves a
/// case that is always true or always false. Only integer and boolean types are
/// checked.
///
/// ### Why is this bad?
/// An expression like `min <= x` may misleadingly imply
/// that it is possible for `x` to be less than the minimum. Expressions like
/// `max < x` are probably mistakes.
///
/// ### Known problems
/// For `usize` the size of the current compile target will
/// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
/// a comparison to detect target pointer width will trigger this lint. One can
/// use `mem::sizeof` and compare its value or conditional compilation
/// attributes
/// like `#[cfg(target_pointer_width = "64")]..` instead.
///
/// ### Example
/// ```rust
/// let vec: Vec<isize> = Vec::new();
/// if vec.len() <= 0 {}
/// if 100 > i32::MAX {}
/// ```
pub ABSURD_EXTREME_COMPARISONS,
correctness,
"a comparison with a maximum or minimum value that is always true or false"
}
declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if let ExprKind::Binary(ref cmp, lhs, rhs) = expr.kind {
if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
if!expr.span.from_expansion() {
let msg = "this comparison involving the minimum or maximum element for this \
type contains a case that is always true or always false";
let conclusion = match result {
AbsurdComparisonResult::AlwaysFalse => "this comparison is always false".to_owned(),
AbsurdComparisonResult::AlwaysTrue => "this comparison is always true".to_owned(),
AbsurdComparisonResult::InequalityImpossible => format!(
"the case where the two sides are not equal never occurs, consider using `{} == {}` \
instead",
snippet(cx, lhs.span, "lhs"),
snippet(cx, rhs.span, "rhs")
),
};
let help = format!(
"because `{}` is the {} value for this type, {}",
snippet(cx, culprit.expr.span, "x"),
match culprit.which {
ExtremeType::Minimum => "minimum",
ExtremeType::Maximum => "maximum",
},
conclusion
);
span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
}
}
}
}
}
enum ExtremeType {
Minimum,
Maximum,
}
struct ExtremeExpr<'a> {
which: ExtremeType,
expr: &'a Expr<'a>,
}
enum AbsurdComparisonResult {
AlwaysFalse,
AlwaysTrue,
InequalityImpossible,
}
fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
if let ExprKind::Cast(cast_exp, _) = expr.kind {
let precast_ty = cx.typeck_results().expr_ty(cast_exp);
let cast_ty = cx.typeck_results().expr_ty(expr);
return is_isize_or_usize(precast_ty)!= is_isize_or_usize(cast_ty);
}
false
}
fn detect_absurd_comparison<'tcx>(
cx: &LateContext<'tcx>,
op: BinOpKind,
lhs: &'tcx Expr<'_>,
rhs: &'tcx Expr<'_>,
) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
use AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
use ExtremeType::{Maximum, Minimum};
// absurd comparison only makes sense on primitive types
// primitive types don't implement comparison operators with each other
if cx.typeck_results().expr_ty(lhs)!= cx.typeck_results().expr_ty(rhs) {
return None;
}
// comparisons between fix sized types and target sized types are considered unanalyzable
if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
return None;
}
let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
let lx = detect_extreme_expr(cx, normalized_lhs);
let rx = detect_extreme_expr(cx, normalized_rhs);
Some(match rel {
Rel::Lt => {
match (lx, rx) {
(Some(l @ ExtremeExpr { which: Maximum,.. }), _) => (l, AlwaysFalse), // max < x
(_, Some(r @ ExtremeExpr { which: Minimum,.. })) => (r, AlwaysFalse), // x < min
_ => return None,
}
},
Rel::Le => {
match (lx, rx) {
(Some(l @ ExtremeExpr { which: Minimum,.. }), _) => (l, AlwaysTrue), // min <= x
(Some(l @ ExtremeExpr { which: Maximum,.. }), _) => (l, InequalityImpossible), // max <= x
(_, Some(r @ ExtremeExpr { which: Minimum,.. })) => (r, InequalityImpossible), // x <= min
(_, Some(r @ ExtremeExpr { which: Maximum,.. })) => (r, AlwaysTrue), // x <= max
_ => return None,
}
},
Rel::Ne | Rel::Eq => return None,
})
}
fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
let ty = cx.typeck_results().expr_ty(expr);
let cv = constant(cx, cx.typeck_results(), expr)?.0;
let which = match (ty.kind(), cv) {
(&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => ExtremeType::Minimum,
(&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => {
ExtremeType::Minimum
},
(&ty::Bool, Constant::Bool(true)) => ExtremeType::Maximum,
(&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => {
ExtremeType::Maximum
},
(&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => ExtremeType::Maximum,
_ => return None,
};
Some(ExtremeExpr { which, expr }) | } | random_line_split |
|
absurd_extreme_comparisons.rs | use rustc_hir::{BinOpKind, Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use clippy_utils::comparisons::{normalize_comparison, Rel};
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::source::snippet;
use clippy_utils::ty::is_isize_or_usize;
use clippy_utils::{clip, int_bits, unsext};
declare_clippy_lint! {
/// ### What it does
/// Checks for comparisons where one side of the relation is
/// either the minimum or maximum value for its type and warns if it involves a
/// case that is always true or always false. Only integer and boolean types are
/// checked.
///
/// ### Why is this bad?
/// An expression like `min <= x` may misleadingly imply
/// that it is possible for `x` to be less than the minimum. Expressions like
/// `max < x` are probably mistakes.
///
/// ### Known problems
/// For `usize` the size of the current compile target will
/// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
/// a comparison to detect target pointer width will trigger this lint. One can
/// use `mem::sizeof` and compare its value or conditional compilation
/// attributes
/// like `#[cfg(target_pointer_width = "64")]..` instead.
///
/// ### Example
/// ```rust
/// let vec: Vec<isize> = Vec::new();
/// if vec.len() <= 0 {}
/// if 100 > i32::MAX {}
/// ```
pub ABSURD_EXTREME_COMPARISONS,
correctness,
"a comparison with a maximum or minimum value that is always true or false"
}
declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if let ExprKind::Binary(ref cmp, lhs, rhs) = expr.kind {
if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
if!expr.span.from_expansion() {
let msg = "this comparison involving the minimum or maximum element for this \
type contains a case that is always true or always false";
let conclusion = match result {
AbsurdComparisonResult::AlwaysFalse => "this comparison is always false".to_owned(),
AbsurdComparisonResult::AlwaysTrue => "this comparison is always true".to_owned(),
AbsurdComparisonResult::InequalityImpossible => format!(
"the case where the two sides are not equal never occurs, consider using `{} == {}` \
instead",
snippet(cx, lhs.span, "lhs"),
snippet(cx, rhs.span, "rhs")
),
};
let help = format!(
"because `{}` is the {} value for this type, {}",
snippet(cx, culprit.expr.span, "x"),
match culprit.which {
ExtremeType::Minimum => "minimum",
ExtremeType::Maximum => "maximum",
},
conclusion
);
span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
}
}
}
}
}
enum | {
Minimum,
Maximum,
}
struct ExtremeExpr<'a> {
which: ExtremeType,
expr: &'a Expr<'a>,
}
enum AbsurdComparisonResult {
AlwaysFalse,
AlwaysTrue,
InequalityImpossible,
}
fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
if let ExprKind::Cast(cast_exp, _) = expr.kind {
let precast_ty = cx.typeck_results().expr_ty(cast_exp);
let cast_ty = cx.typeck_results().expr_ty(expr);
return is_isize_or_usize(precast_ty)!= is_isize_or_usize(cast_ty);
}
false
}
fn detect_absurd_comparison<'tcx>(
cx: &LateContext<'tcx>,
op: BinOpKind,
lhs: &'tcx Expr<'_>,
rhs: &'tcx Expr<'_>,
) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
use AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
use ExtremeType::{Maximum, Minimum};
// absurd comparison only makes sense on primitive types
// primitive types don't implement comparison operators with each other
if cx.typeck_results().expr_ty(lhs)!= cx.typeck_results().expr_ty(rhs) {
return None;
}
// comparisons between fix sized types and target sized types are considered unanalyzable
if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
return None;
}
let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
let lx = detect_extreme_expr(cx, normalized_lhs);
let rx = detect_extreme_expr(cx, normalized_rhs);
Some(match rel {
Rel::Lt => {
match (lx, rx) {
(Some(l @ ExtremeExpr { which: Maximum,.. }), _) => (l, AlwaysFalse), // max < x
(_, Some(r @ ExtremeExpr { which: Minimum,.. })) => (r, AlwaysFalse), // x < min
_ => return None,
}
},
Rel::Le => {
match (lx, rx) {
(Some(l @ ExtremeExpr { which: Minimum,.. }), _) => (l, AlwaysTrue), // min <= x
(Some(l @ ExtremeExpr { which: Maximum,.. }), _) => (l, InequalityImpossible), // max <= x
(_, Some(r @ ExtremeExpr { which: Minimum,.. })) => (r, InequalityImpossible), // x <= min
(_, Some(r @ ExtremeExpr { which: Maximum,.. })) => (r, AlwaysTrue), // x <= max
_ => return None,
}
},
Rel::Ne | Rel::Eq => return None,
})
}
fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
let ty = cx.typeck_results().expr_ty(expr);
let cv = constant(cx, cx.typeck_results(), expr)?.0;
let which = match (ty.kind(), cv) {
(&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => ExtremeType::Minimum,
(&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => {
ExtremeType::Minimum
},
(&ty::Bool, Constant::Bool(true)) => ExtremeType::Maximum,
(&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => {
ExtremeType::Maximum
},
(&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => ExtremeType::Maximum,
_ => return None,
};
Some(ExtremeExpr { which, expr })
}
| ExtremeType | identifier_name |
absurd_extreme_comparisons.rs | use rustc_hir::{BinOpKind, Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use clippy_utils::comparisons::{normalize_comparison, Rel};
use clippy_utils::consts::{constant, Constant};
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::source::snippet;
use clippy_utils::ty::is_isize_or_usize;
use clippy_utils::{clip, int_bits, unsext};
declare_clippy_lint! {
/// ### What it does
/// Checks for comparisons where one side of the relation is
/// either the minimum or maximum value for its type and warns if it involves a
/// case that is always true or always false. Only integer and boolean types are
/// checked.
///
/// ### Why is this bad?
/// An expression like `min <= x` may misleadingly imply
/// that it is possible for `x` to be less than the minimum. Expressions like
/// `max < x` are probably mistakes.
///
/// ### Known problems
/// For `usize` the size of the current compile target will
/// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
/// a comparison to detect target pointer width will trigger this lint. One can
/// use `mem::sizeof` and compare its value or conditional compilation
/// attributes
/// like `#[cfg(target_pointer_width = "64")]..` instead.
///
/// ### Example
/// ```rust
/// let vec: Vec<isize> = Vec::new();
/// if vec.len() <= 0 {}
/// if 100 > i32::MAX {}
/// ```
pub ABSURD_EXTREME_COMPARISONS,
correctness,
"a comparison with a maximum or minimum value that is always true or false"
}
declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
impl<'tcx> LateLintPass<'tcx> for AbsurdExtremeComparisons {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if let ExprKind::Binary(ref cmp, lhs, rhs) = expr.kind {
if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
if!expr.span.from_expansion() {
let msg = "this comparison involving the minimum or maximum element for this \
type contains a case that is always true or always false";
let conclusion = match result {
AbsurdComparisonResult::AlwaysFalse => "this comparison is always false".to_owned(),
AbsurdComparisonResult::AlwaysTrue => "this comparison is always true".to_owned(),
AbsurdComparisonResult::InequalityImpossible => format!(
"the case where the two sides are not equal never occurs, consider using `{} == {}` \
instead",
snippet(cx, lhs.span, "lhs"),
snippet(cx, rhs.span, "rhs")
),
};
let help = format!(
"because `{}` is the {} value for this type, {}",
snippet(cx, culprit.expr.span, "x"),
match culprit.which {
ExtremeType::Minimum => "minimum",
ExtremeType::Maximum => "maximum",
},
conclusion
);
span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, None, &help);
}
}
}
}
}
enum ExtremeType {
Minimum,
Maximum,
}
struct ExtremeExpr<'a> {
which: ExtremeType,
expr: &'a Expr<'a>,
}
enum AbsurdComparisonResult {
AlwaysFalse,
AlwaysTrue,
InequalityImpossible,
}
fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool |
fn detect_absurd_comparison<'tcx>(
cx: &LateContext<'tcx>,
op: BinOpKind,
lhs: &'tcx Expr<'_>,
rhs: &'tcx Expr<'_>,
) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
use AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
use ExtremeType::{Maximum, Minimum};
// absurd comparison only makes sense on primitive types
// primitive types don't implement comparison operators with each other
if cx.typeck_results().expr_ty(lhs)!= cx.typeck_results().expr_ty(rhs) {
return None;
}
// comparisons between fix sized types and target sized types are considered unanalyzable
if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
return None;
}
let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
let lx = detect_extreme_expr(cx, normalized_lhs);
let rx = detect_extreme_expr(cx, normalized_rhs);
Some(match rel {
Rel::Lt => {
match (lx, rx) {
(Some(l @ ExtremeExpr { which: Maximum,.. }), _) => (l, AlwaysFalse), // max < x
(_, Some(r @ ExtremeExpr { which: Minimum,.. })) => (r, AlwaysFalse), // x < min
_ => return None,
}
},
Rel::Le => {
match (lx, rx) {
(Some(l @ ExtremeExpr { which: Minimum,.. }), _) => (l, AlwaysTrue), // min <= x
(Some(l @ ExtremeExpr { which: Maximum,.. }), _) => (l, InequalityImpossible), // max <= x
(_, Some(r @ ExtremeExpr { which: Minimum,.. })) => (r, InequalityImpossible), // x <= min
(_, Some(r @ ExtremeExpr { which: Maximum,.. })) => (r, AlwaysTrue), // x <= max
_ => return None,
}
},
Rel::Ne | Rel::Eq => return None,
})
}
fn detect_extreme_expr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
let ty = cx.typeck_results().expr_ty(expr);
let cv = constant(cx, cx.typeck_results(), expr)?.0;
let which = match (ty.kind(), cv) {
(&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => ExtremeType::Minimum,
(&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => {
ExtremeType::Minimum
},
(&ty::Bool, Constant::Bool(true)) => ExtremeType::Maximum,
(&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => {
ExtremeType::Maximum
},
(&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => ExtremeType::Maximum,
_ => return None,
};
Some(ExtremeExpr { which, expr })
}
| {
if let ExprKind::Cast(cast_exp, _) = expr.kind {
let precast_ty = cx.typeck_results().expr_ty(cast_exp);
let cast_ty = cx.typeck_results().expr_ty(expr);
return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
}
false
} | identifier_body |
compress.rs | use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use ::image;
use ::image::GenericImage;
use dct;
use quantize;
use color_space;
use compressed_image;
use protobuf::Message; |
use flate2::Compression;
use flate2::write::ZlibEncoder;
pub fn compress_file(input_filename: &Path) {
let file_stem = match input_filename.file_stem() {
Some(stem) => stem,
None => panic!("Invalid input filename: Could not automatically determine output file"),
};
let file_container = match input_filename.parent() {
Some(result) => result,
None => {
panic!("Invalid input filename: Could not automatically determine the output file \
directory")
}
};
let mut output_filename = PathBuf::from(&file_container);
output_filename.push(file_stem);
output_filename.set_extension("msca");
compress_file_to_output(input_filename, output_filename.as_path());
}
pub fn compress_file_to_output(input_filename: &Path, output_filename: &Path) {
if let Some(extension) = output_filename.extension() {
assert!(extension == "msca",
"Output file for compression must be'msca'")
} else {
panic!("Output file for compression must be msca")
}
let input_image = image::open(input_filename).unwrap();
let mut output_file = File::create(&Path::new(&output_filename)).unwrap();
compress(&input_image, &mut output_file);
}
fn compress(input_image: &image::DynamicImage, output: &mut File) {
let (width, height) = input_image.dimensions();
let mut red_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize);
let mut green_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize);
let mut blue_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize);
// split the color data into channels
for y in 0..height {
for x in 0..width {
let pixel = input_image.get_pixel(x, y);
let (y, cb, cr) = color_space::rgb_to_ycbcr(pixel[0], pixel[1], pixel[2]);
red_channel.push(y);
green_channel.push(cb);
blue_channel.push(cr);
}
}
let mut serializer = compressed_image::compressed_image::new();
serializer.set_width(width);
serializer.set_height(height);
// compress the data and put it directly into the serializer
serializer.set_red(compress_color_channel(width as usize, height as usize, red_channel));
serializer.set_green(compress_color_channel(width as usize, height as usize, green_channel));
serializer.set_blue(compress_color_channel(width as usize, height as usize, blue_channel));
let serialized_bytes = serializer.write_to_bytes().unwrap();
// losslessly compress the serialized data
let mut enc = ZlibEncoder::new(output, Compression::Default);
let mut written = 0;
while written < serialized_bytes.len() {
written += enc.write(&serialized_bytes[written..serialized_bytes.len()]).unwrap();
}
let _ = enc.finish();
}
fn compress_color_channel(width: usize,
height: usize,
mut uncompressed_channel_data: Vec<f32>)
-> Vec<i32> {
dct::dct2_2d(width, height, &mut uncompressed_channel_data);
quantize::encode(width, height, &uncompressed_channel_data)
} | random_line_split |
|
compress.rs | use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use ::image;
use ::image::GenericImage;
use dct;
use quantize;
use color_space;
use compressed_image;
use protobuf::Message;
use flate2::Compression;
use flate2::write::ZlibEncoder;
pub fn compress_file(input_filename: &Path) {
let file_stem = match input_filename.file_stem() {
Some(stem) => stem,
None => panic!("Invalid input filename: Could not automatically determine output file"),
};
let file_container = match input_filename.parent() {
Some(result) => result,
None => {
panic!("Invalid input filename: Could not automatically determine the output file \
directory")
}
};
let mut output_filename = PathBuf::from(&file_container);
output_filename.push(file_stem);
output_filename.set_extension("msca");
compress_file_to_output(input_filename, output_filename.as_path());
}
pub fn compress_file_to_output(input_filename: &Path, output_filename: &Path) {
if let Some(extension) = output_filename.extension() {
assert!(extension == "msca",
"Output file for compression must be'msca'")
} else {
panic!("Output file for compression must be msca")
}
let input_image = image::open(input_filename).unwrap();
let mut output_file = File::create(&Path::new(&output_filename)).unwrap();
compress(&input_image, &mut output_file);
}
fn compress(input_image: &image::DynamicImage, output: &mut File) {
let (width, height) = input_image.dimensions();
let mut red_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize);
let mut green_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize);
let mut blue_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize);
// split the color data into channels
for y in 0..height {
for x in 0..width {
let pixel = input_image.get_pixel(x, y);
let (y, cb, cr) = color_space::rgb_to_ycbcr(pixel[0], pixel[1], pixel[2]);
red_channel.push(y);
green_channel.push(cb);
blue_channel.push(cr);
}
}
let mut serializer = compressed_image::compressed_image::new();
serializer.set_width(width);
serializer.set_height(height);
// compress the data and put it directly into the serializer
serializer.set_red(compress_color_channel(width as usize, height as usize, red_channel));
serializer.set_green(compress_color_channel(width as usize, height as usize, green_channel));
serializer.set_blue(compress_color_channel(width as usize, height as usize, blue_channel));
let serialized_bytes = serializer.write_to_bytes().unwrap();
// losslessly compress the serialized data
let mut enc = ZlibEncoder::new(output, Compression::Default);
let mut written = 0;
while written < serialized_bytes.len() {
written += enc.write(&serialized_bytes[written..serialized_bytes.len()]).unwrap();
}
let _ = enc.finish();
}
fn compress_color_channel(width: usize,
height: usize,
mut uncompressed_channel_data: Vec<f32>)
-> Vec<i32> | {
dct::dct2_2d(width, height, &mut uncompressed_channel_data);
quantize::encode(width, height, &uncompressed_channel_data)
} | identifier_body |
|
compress.rs | use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use ::image;
use ::image::GenericImage;
use dct;
use quantize;
use color_space;
use compressed_image;
use protobuf::Message;
use flate2::Compression;
use flate2::write::ZlibEncoder;
pub fn compress_file(input_filename: &Path) {
let file_stem = match input_filename.file_stem() {
Some(stem) => stem,
None => panic!("Invalid input filename: Could not automatically determine output file"),
};
let file_container = match input_filename.parent() {
Some(result) => result,
None => {
panic!("Invalid input filename: Could not automatically determine the output file \
directory")
}
};
let mut output_filename = PathBuf::from(&file_container);
output_filename.push(file_stem);
output_filename.set_extension("msca");
compress_file_to_output(input_filename, output_filename.as_path());
}
pub fn | (input_filename: &Path, output_filename: &Path) {
if let Some(extension) = output_filename.extension() {
assert!(extension == "msca",
"Output file for compression must be'msca'")
} else {
panic!("Output file for compression must be msca")
}
let input_image = image::open(input_filename).unwrap();
let mut output_file = File::create(&Path::new(&output_filename)).unwrap();
compress(&input_image, &mut output_file);
}
fn compress(input_image: &image::DynamicImage, output: &mut File) {
let (width, height) = input_image.dimensions();
let mut red_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize);
let mut green_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize);
let mut blue_channel: Vec<f32> = Vec::with_capacity(width as usize * height as usize);
// split the color data into channels
for y in 0..height {
for x in 0..width {
let pixel = input_image.get_pixel(x, y);
let (y, cb, cr) = color_space::rgb_to_ycbcr(pixel[0], pixel[1], pixel[2]);
red_channel.push(y);
green_channel.push(cb);
blue_channel.push(cr);
}
}
let mut serializer = compressed_image::compressed_image::new();
serializer.set_width(width);
serializer.set_height(height);
// compress the data and put it directly into the serializer
serializer.set_red(compress_color_channel(width as usize, height as usize, red_channel));
serializer.set_green(compress_color_channel(width as usize, height as usize, green_channel));
serializer.set_blue(compress_color_channel(width as usize, height as usize, blue_channel));
let serialized_bytes = serializer.write_to_bytes().unwrap();
// losslessly compress the serialized data
let mut enc = ZlibEncoder::new(output, Compression::Default);
let mut written = 0;
while written < serialized_bytes.len() {
written += enc.write(&serialized_bytes[written..serialized_bytes.len()]).unwrap();
}
let _ = enc.finish();
}
fn compress_color_channel(width: usize,
height: usize,
mut uncompressed_channel_data: Vec<f32>)
-> Vec<i32> {
dct::dct2_2d(width, height, &mut uncompressed_channel_data);
quantize::encode(width, height, &uncompressed_channel_data)
}
| compress_file_to_output | identifier_name |
config.rs | use crate::files;
use crate::package;
use std::path::PathBuf;
use serde_json;
use treeflection::{Node, NodeRunner, NodeToken};
#[derive(Clone, Serialize, Deserialize, Node)]
pub struct Config {
pub current_package: Option<String>,
pub netplay_region: Option<String>,
pub auto_save_replay: bool,
pub verify_package_hashes: bool,
pub fullscreen: bool, | }
impl Config {
fn get_path() -> PathBuf {
let mut path = files::get_path();
path.push("config.json");
path
}
pub fn load() -> Config {
if let Ok (json) = files::load_json(Config::get_path()) {
if let Ok (mut config) = serde_json::from_value::<Config>(json) {
// current_package may have been deleted since config was last saved
if let Some (ref current_package) = config.current_package.clone() {
if!package::exists(current_package.as_str()) {
config.current_package = None;
}
}
return config;
}
}
warn!("{:?} is invalid or does not exist, loading default values", Config::get_path());
Config::default()
}
pub fn save(&self) {
files::save_struct(Config::get_path(), self);
}
}
impl Default for Config {
fn default() -> Config {
Config {
current_package: None,
netplay_region: None,
auto_save_replay: false,
verify_package_hashes: true,
fullscreen: false,
physical_device_name: None,
}
}
} | pub physical_device_name: Option<String>, | random_line_split |
config.rs | use crate::files;
use crate::package;
use std::path::PathBuf;
use serde_json;
use treeflection::{Node, NodeRunner, NodeToken};
#[derive(Clone, Serialize, Deserialize, Node)]
pub struct Config {
pub current_package: Option<String>,
pub netplay_region: Option<String>,
pub auto_save_replay: bool,
pub verify_package_hashes: bool,
pub fullscreen: bool,
pub physical_device_name: Option<String>,
}
impl Config {
fn get_path() -> PathBuf {
let mut path = files::get_path();
path.push("config.json");
path
}
pub fn | () -> Config {
if let Ok (json) = files::load_json(Config::get_path()) {
if let Ok (mut config) = serde_json::from_value::<Config>(json) {
// current_package may have been deleted since config was last saved
if let Some (ref current_package) = config.current_package.clone() {
if!package::exists(current_package.as_str()) {
config.current_package = None;
}
}
return config;
}
}
warn!("{:?} is invalid or does not exist, loading default values", Config::get_path());
Config::default()
}
pub fn save(&self) {
files::save_struct(Config::get_path(), self);
}
}
impl Default for Config {
fn default() -> Config {
Config {
current_package: None,
netplay_region: None,
auto_save_replay: false,
verify_package_hashes: true,
fullscreen: false,
physical_device_name: None,
}
}
}
| load | identifier_name |
config.rs | use crate::files;
use crate::package;
use std::path::PathBuf;
use serde_json;
use treeflection::{Node, NodeRunner, NodeToken};
#[derive(Clone, Serialize, Deserialize, Node)]
pub struct Config {
pub current_package: Option<String>,
pub netplay_region: Option<String>,
pub auto_save_replay: bool,
pub verify_package_hashes: bool,
pub fullscreen: bool,
pub physical_device_name: Option<String>,
}
impl Config {
fn get_path() -> PathBuf {
let mut path = files::get_path();
path.push("config.json");
path
}
pub fn load() -> Config {
if let Ok (json) = files::load_json(Config::get_path()) |
warn!("{:?} is invalid or does not exist, loading default values", Config::get_path());
Config::default()
}
pub fn save(&self) {
files::save_struct(Config::get_path(), self);
}
}
impl Default for Config {
fn default() -> Config {
Config {
current_package: None,
netplay_region: None,
auto_save_replay: false,
verify_package_hashes: true,
fullscreen: false,
physical_device_name: None,
}
}
}
| {
if let Ok (mut config) = serde_json::from_value::<Config>(json) {
// current_package may have been deleted since config was last saved
if let Some (ref current_package) = config.current_package.clone() {
if !package::exists(current_package.as_str()) {
config.current_package = None;
}
}
return config;
}
} | conditional_block |
main.rs | extern crate llvm_sys as llvm;
extern crate libc;
extern crate itertools;
#[macro_use]
extern crate clap;
extern crate uuid;
extern crate toml;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate bincode;
extern crate time;
extern crate either;
macro_rules! try_opt {
($e:expr) =>(
match $e {
Some(v) => v,
None => return None,
}
)
}
mod ast;
mod compileerror;
mod bytecode;
mod exportlibrary;
mod parser;
mod typechecker;
mod span;
mod llvmbackend;
mod target;
mod timer;
mod package;
mod packagebuild;
use std::fs::File;
use std::process::exit;
use std::path::PathBuf;
use clap::ArgMatches;
use compileerror::{CompileResult};
use llvmbackend::{OutputType, llvm_init, llvm_shutdown};
use packagebuild::{PackageData, BuildOptions};
use exportlibrary::ExportLibrary;
fn build_command(matches: &ArgMatches, dump_flags: &str) -> CompileResult<i32>
{
let input_file = matches.value_of("INPUT_FILE").expect("No input file given");
let build_options = BuildOptions{
optimize: matches.is_present("OPTIMIZE"),
dump_flags: dump_flags.into(),
target_machine: llvm_init()?,
sources_directory: String::new(),
import_directories: matches.value_of("IMPORTS")
.map(|dirs| dirs.split(',').map(PathBuf::from).collect())
.unwrap_or_else(Vec::new),
};
let output_type = match matches.value_of("LIB") {
Some("static") => OutputType::StaticLib,
Some("shared") => OutputType::SharedLib,
_ => OutputType::Binary,
};
let pkg = PackageData::single_file(&input_file, output_type)?;
pkg.build(&build_options)?;
Ok(0)
}
fn build_package_command(matches: &ArgMatches, dump_flags: &str) -> CompileResult<i32>
{
let package_toml = if let Some(toml) = matches.value_of("PACKAGE_TOML") {
toml
} else {
"./package.toml"
};
let pkg = PackageData::load(package_toml)?;
let build_options = BuildOptions{
optimize: matches.is_present("OPTIMIZE"),
dump_flags: dump_flags.into(),
target_machine: llvm_init()?,
sources_directory: "src".into(),
import_directories: matches.value_of("IMPORTS")
.map(|dirs| dirs.split(',').map(PathBuf::from).collect())
.unwrap_or_else(Vec::new),
};
pkg.build(&build_options)?;
Ok(0)
}
fn exports_command(matches: &ArgMatches) -> CompileResult<i32>
{
let exports_file_path = matches.value_of("EXPORTS_FILE").ok_or_else(|| "No exports file given".to_owned())?;
let mut exports_file = File::open(&exports_file_path)?;
let lib = ExportLibrary::load(&mut exports_file)?;
println!("{}", lib);
Ok(0)
}
fn | () -> CompileResult<i32>
{
let app = clap_app!(cobrac =>
(version: "0.1")
(author: "Joris Guisson <[email protected]>")
(about: "Nomad language compiler")
(@arg DUMP: -d --dump +takes_value "Dump internal compiler state for debug purposes. Argument can be all, ast, bytecode or ir. A comma separated list of these values is also supported.")
(@arg TARGET_TRIPLET: -t --triplet "Print the default target triplet of the current system, and exit")
(@subcommand build =>
(about: "Build a menhir file")
(@arg INPUT_FILE: +required "File to build")
(@arg OUTPUT_FILE: -o --output +takes_value "Name of binary to create (by default input file without the extensions)")
(@arg OPTIMIZE: -O --optimize "Optimize the code")
(@arg IMPORTS: -I --imports +takes_value "Directory to look for imports, use a comma separated list for more then one.")
(@arg LIB: -l --lib +takes_value possible_value[static shared] "Create a library, type of library must be pass")
)
(@subcommand buildpkg =>
(about: "Build a menhir package.")
(@arg PACKAGE_TOML: -p --package +takes_value "Specify the package.toml file. If not specified, menhir will look in the current directory for one.")
(@arg OPTIMIZE: -O --optimize "Optimize the code")
(@arg IMPORTS: -I --imports +takes_value "Directory to look for imports, use a comma separated list for more then one.")
)
(@subcommand exports =>
(about: "List the exported symbols in an exports file")
(@arg EXPORTS_FILE: +required "Exports file")
)
);
let matches = app.get_matches();
let dump_flags = matches.value_of("DUMP").unwrap_or("");
if matches.is_present("TARGET_TRIPLET") {
let target_machine = llvm_init()?;
print!("{}", target_machine.target.triplet);
Ok(0)
} else if let Some(matches) = matches.subcommand_matches("build") {
build_command(matches, dump_flags)
} else if let Some(matches) = matches.subcommand_matches("buildpkg") {
build_package_command(matches, dump_flags)
} else if let Some(matches) = matches.subcommand_matches("exports") {
exports_command(matches)
} else {
println!("{}", matches.usage());
Ok(1)
}
}
fn main()
{
match run()
{
Ok(ret) => {
llvm_shutdown();
exit(ret)
},
Err(e) => {
e.print();
llvm_shutdown();
exit(-1);
},
}
}
| run | identifier_name |
main.rs | extern crate llvm_sys as llvm;
extern crate libc;
extern crate itertools;
#[macro_use]
extern crate clap;
extern crate uuid;
extern crate toml;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate bincode;
extern crate time;
extern crate either;
macro_rules! try_opt {
($e:expr) =>(
match $e {
Some(v) => v,
None => return None,
}
)
}
mod ast;
mod compileerror;
mod bytecode;
mod exportlibrary;
mod parser;
mod typechecker;
mod span;
mod llvmbackend;
mod target;
mod timer;
mod package;
mod packagebuild;
use std::fs::File;
use std::process::exit;
use std::path::PathBuf;
use clap::ArgMatches;
use compileerror::{CompileResult};
use llvmbackend::{OutputType, llvm_init, llvm_shutdown};
use packagebuild::{PackageData, BuildOptions};
use exportlibrary::ExportLibrary;
fn build_command(matches: &ArgMatches, dump_flags: &str) -> CompileResult<i32>
{
let input_file = matches.value_of("INPUT_FILE").expect("No input file given");
let build_options = BuildOptions{
optimize: matches.is_present("OPTIMIZE"),
dump_flags: dump_flags.into(),
target_machine: llvm_init()?,
sources_directory: String::new(),
import_directories: matches.value_of("IMPORTS")
.map(|dirs| dirs.split(',').map(PathBuf::from).collect())
.unwrap_or_else(Vec::new),
};
let output_type = match matches.value_of("LIB") {
Some("static") => OutputType::StaticLib,
Some("shared") => OutputType::SharedLib,
_ => OutputType::Binary,
};
let pkg = PackageData::single_file(&input_file, output_type)?;
pkg.build(&build_options)?;
Ok(0)
}
fn build_package_command(matches: &ArgMatches, dump_flags: &str) -> CompileResult<i32>
{
let package_toml = if let Some(toml) = matches.value_of("PACKAGE_TOML") {
toml
} else {
"./package.toml"
};
let pkg = PackageData::load(package_toml)?;
let build_options = BuildOptions{
optimize: matches.is_present("OPTIMIZE"),
dump_flags: dump_flags.into(),
target_machine: llvm_init()?,
sources_directory: "src".into(),
import_directories: matches.value_of("IMPORTS")
.map(|dirs| dirs.split(',').map(PathBuf::from).collect())
.unwrap_or_else(Vec::new),
};
pkg.build(&build_options)?;
Ok(0)
}
fn exports_command(matches: &ArgMatches) -> CompileResult<i32>
{
let exports_file_path = matches.value_of("EXPORTS_FILE").ok_or_else(|| "No exports file given".to_owned())?;
let mut exports_file = File::open(&exports_file_path)?;
let lib = ExportLibrary::load(&mut exports_file)?;
println!("{}", lib);
Ok(0)
}
fn run() -> CompileResult<i32>
{
let app = clap_app!(cobrac =>
(version: "0.1")
(author: "Joris Guisson <[email protected]>")
(about: "Nomad language compiler")
(@arg DUMP: -d --dump +takes_value "Dump internal compiler state for debug purposes. Argument can be all, ast, bytecode or ir. A comma separated list of these values is also supported.")
(@arg TARGET_TRIPLET: -t --triplet "Print the default target triplet of the current system, and exit")
(@subcommand build =>
(about: "Build a menhir file")
(@arg INPUT_FILE: +required "File to build")
(@arg OUTPUT_FILE: -o --output +takes_value "Name of binary to create (by default input file without the extensions)")
(@arg OPTIMIZE: -O --optimize "Optimize the code")
(@arg IMPORTS: -I --imports +takes_value "Directory to look for imports, use a comma separated list for more then one.")
(@arg LIB: -l --lib +takes_value possible_value[static shared] "Create a library, type of library must be pass")
)
(@subcommand buildpkg =>
(about: "Build a menhir package.")
(@arg PACKAGE_TOML: -p --package +takes_value "Specify the package.toml file. If not specified, menhir will look in the current directory for one.")
(@arg OPTIMIZE: -O --optimize "Optimize the code")
(@arg IMPORTS: -I --imports +takes_value "Directory to look for imports, use a comma separated list for more then one.")
)
(@subcommand exports =>
(about: "List the exported symbols in an exports file")
(@arg EXPORTS_FILE: +required "Exports file")
)
);
let matches = app.get_matches();
let dump_flags = matches.value_of("DUMP").unwrap_or("");
if matches.is_present("TARGET_TRIPLET") {
let target_machine = llvm_init()?;
print!("{}", target_machine.target.triplet);
Ok(0)
} else if let Some(matches) = matches.subcommand_matches("build") {
build_command(matches, dump_flags)
} else if let Some(matches) = matches.subcommand_matches("buildpkg") {
build_package_command(matches, dump_flags)
} else if let Some(matches) = matches.subcommand_matches("exports") {
exports_command(matches)
} else {
println!("{}", matches.usage());
Ok(1)
}
}
fn main()
| {
match run()
{
Ok(ret) => {
llvm_shutdown();
exit(ret)
},
Err(e) => {
e.print();
llvm_shutdown();
exit(-1);
},
}
} | identifier_body |
|
main.rs | extern crate llvm_sys as llvm;
extern crate libc;
extern crate itertools;
#[macro_use]
extern crate clap;
extern crate uuid;
extern crate toml;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate bincode;
extern crate time;
extern crate either;
macro_rules! try_opt {
($e:expr) =>(
match $e {
Some(v) => v,
None => return None,
}
)
}
mod ast;
mod compileerror;
mod bytecode;
mod exportlibrary;
mod parser;
mod typechecker;
mod span;
mod llvmbackend;
mod target;
mod timer;
mod package;
mod packagebuild;
use std::fs::File;
use std::process::exit;
use std::path::PathBuf;
use clap::ArgMatches;
use compileerror::{CompileResult};
use llvmbackend::{OutputType, llvm_init, llvm_shutdown};
use packagebuild::{PackageData, BuildOptions};
use exportlibrary::ExportLibrary;
fn build_command(matches: &ArgMatches, dump_flags: &str) -> CompileResult<i32>
{
let input_file = matches.value_of("INPUT_FILE").expect("No input file given");
let build_options = BuildOptions{
optimize: matches.is_present("OPTIMIZE"),
dump_flags: dump_flags.into(),
target_machine: llvm_init()?,
sources_directory: String::new(),
import_directories: matches.value_of("IMPORTS")
.map(|dirs| dirs.split(',').map(PathBuf::from).collect())
.unwrap_or_else(Vec::new),
};
let output_type = match matches.value_of("LIB") {
Some("static") => OutputType::StaticLib,
Some("shared") => OutputType::SharedLib,
_ => OutputType::Binary,
};
let pkg = PackageData::single_file(&input_file, output_type)?;
pkg.build(&build_options)?;
Ok(0)
}
fn build_package_command(matches: &ArgMatches, dump_flags: &str) -> CompileResult<i32>
{
let package_toml = if let Some(toml) = matches.value_of("PACKAGE_TOML") {
toml
} else {
"./package.toml"
};
let pkg = PackageData::load(package_toml)?;
let build_options = BuildOptions{
optimize: matches.is_present("OPTIMIZE"),
dump_flags: dump_flags.into(),
target_machine: llvm_init()?,
sources_directory: "src".into(),
import_directories: matches.value_of("IMPORTS")
.map(|dirs| dirs.split(',').map(PathBuf::from).collect())
.unwrap_or_else(Vec::new),
};
pkg.build(&build_options)?;
Ok(0)
}
fn exports_command(matches: &ArgMatches) -> CompileResult<i32>
{
let exports_file_path = matches.value_of("EXPORTS_FILE").ok_or_else(|| "No exports file given".to_owned())?;
let mut exports_file = File::open(&exports_file_path)?;
let lib = ExportLibrary::load(&mut exports_file)?;
println!("{}", lib);
Ok(0)
}
fn run() -> CompileResult<i32>
{
let app = clap_app!(cobrac =>
(version: "0.1")
(author: "Joris Guisson <[email protected]>")
(about: "Nomad language compiler")
(@arg DUMP: -d --dump +takes_value "Dump internal compiler state for debug purposes. Argument can be all, ast, bytecode or ir. A comma separated list of these values is also supported.")
(@arg TARGET_TRIPLET: -t --triplet "Print the default target triplet of the current system, and exit")
(@subcommand build =>
(about: "Build a menhir file")
(@arg INPUT_FILE: +required "File to build")
(@arg OUTPUT_FILE: -o --output +takes_value "Name of binary to create (by default input file without the extensions)")
(@arg OPTIMIZE: -O --optimize "Optimize the code")
(@arg IMPORTS: -I --imports +takes_value "Directory to look for imports, use a comma separated list for more then one.")
(@arg LIB: -l --lib +takes_value possible_value[static shared] "Create a library, type of library must be pass")
)
(@subcommand buildpkg =>
(about: "Build a menhir package.")
(@arg PACKAGE_TOML: -p --package +takes_value "Specify the package.toml file. If not specified, menhir will look in the current directory for one.")
(@arg OPTIMIZE: -O --optimize "Optimize the code")
(@arg IMPORTS: -I --imports +takes_value "Directory to look for imports, use a comma separated list for more then one.")
)
(@subcommand exports =>
(about: "List the exported symbols in an exports file")
(@arg EXPORTS_FILE: +required "Exports file")
)
);
let matches = app.get_matches();
let dump_flags = matches.value_of("DUMP").unwrap_or("");
if matches.is_present("TARGET_TRIPLET") {
let target_machine = llvm_init()?;
print!("{}", target_machine.target.triplet);
Ok(0) | build_command(matches, dump_flags)
} else if let Some(matches) = matches.subcommand_matches("buildpkg") {
build_package_command(matches, dump_flags)
} else if let Some(matches) = matches.subcommand_matches("exports") {
exports_command(matches)
} else {
println!("{}", matches.usage());
Ok(1)
}
}
fn main()
{
match run()
{
Ok(ret) => {
llvm_shutdown();
exit(ret)
},
Err(e) => {
e.print();
llvm_shutdown();
exit(-1);
},
}
} | } else if let Some(matches) = matches.subcommand_matches("build") { | random_line_split |
compound2d.rs | extern crate nalgebra as na;
use na::{Isometry2, Vector2};
use ncollide2d::shape::{Compound, Cuboid, ShapeHandle};
fn main() {
// Delta transformation matrices.
let delta1 = Isometry2::new(Vector2::new(0.0f32, -1.5), na::zero());
let delta2 = Isometry2::new(Vector2::new(-1.5f32, 0.0), na::zero());
let delta3 = Isometry2::new(Vector2::new(1.5f32, 0.0), na::zero());
// 1) Initialize the shape list.
let mut shapes = Vec::new();
let horizontal_box = ShapeHandle::new(Cuboid::new(Vector2::new(1.5f32, 0.25)));
let vertical_box = ShapeHandle::new(Cuboid::new(Vector2::new(0.25f32, 1.5)));
shapes.push((delta1, horizontal_box));
shapes.push((delta2, vertical_box.clone()));
shapes.push((delta3, vertical_box));
| // 2) Create the compound shape.
let compound = Compound::new(shapes);
assert!(compound.shapes().len() == 3)
} | random_line_split |
|
compound2d.rs | extern crate nalgebra as na;
use na::{Isometry2, Vector2};
use ncollide2d::shape::{Compound, Cuboid, ShapeHandle};
fn main() | {
// Delta transformation matrices.
let delta1 = Isometry2::new(Vector2::new(0.0f32, -1.5), na::zero());
let delta2 = Isometry2::new(Vector2::new(-1.5f32, 0.0), na::zero());
let delta3 = Isometry2::new(Vector2::new(1.5f32, 0.0), na::zero());
// 1) Initialize the shape list.
let mut shapes = Vec::new();
let horizontal_box = ShapeHandle::new(Cuboid::new(Vector2::new(1.5f32, 0.25)));
let vertical_box = ShapeHandle::new(Cuboid::new(Vector2::new(0.25f32, 1.5)));
shapes.push((delta1, horizontal_box));
shapes.push((delta2, vertical_box.clone()));
shapes.push((delta3, vertical_box));
// 2) Create the compound shape.
let compound = Compound::new(shapes);
assert!(compound.shapes().len() == 3)
} | identifier_body |
|
compound2d.rs | extern crate nalgebra as na;
use na::{Isometry2, Vector2};
use ncollide2d::shape::{Compound, Cuboid, ShapeHandle};
fn | () {
// Delta transformation matrices.
let delta1 = Isometry2::new(Vector2::new(0.0f32, -1.5), na::zero());
let delta2 = Isometry2::new(Vector2::new(-1.5f32, 0.0), na::zero());
let delta3 = Isometry2::new(Vector2::new(1.5f32, 0.0), na::zero());
// 1) Initialize the shape list.
let mut shapes = Vec::new();
let horizontal_box = ShapeHandle::new(Cuboid::new(Vector2::new(1.5f32, 0.25)));
let vertical_box = ShapeHandle::new(Cuboid::new(Vector2::new(0.25f32, 1.5)));
shapes.push((delta1, horizontal_box));
shapes.push((delta2, vertical_box.clone()));
shapes.push((delta3, vertical_box));
// 2) Create the compound shape.
let compound = Compound::new(shapes);
assert!(compound.shapes().len() == 3)
}
| main | identifier_name |
lib.rs | // Copyright TUNTAP, 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
use base::{ioctl_ior_nr, ioctl_iow_nr};
// generated with bindgen /usr/include/linux/if.h --no-unstable-rust
// --constified-enum '*' --with-derive-default -- -D __UAPI_DEF_IF_IFNAMSIZ -D
// __UAPI_DEF_IF_NET_DEVICE_FLAGS -D __UAPI_DEF_IF_IFREQ -D __UAPI_DEF_IF_IFMAP
// Name is "iff" to avoid conflicting with "if" keyword.
// Generated against Linux 4.11 to include fix "uapi: fix linux/if.h userspace
// compilation errors".
// Manual fixup of ifrn_name to be of type c_uchar instead of c_char.
#[allow(clippy::all)]
pub mod iff;
// generated with bindgen /usr/include/linux/if_tun.h --no-unstable-rust
// --constified-enum '*' --with-derive-default
pub mod if_tun;
// generated with bindgen /usr/include/linux/in.h --no-unstable-rust
// --constified-enum '*' --with-derive-default
// Name is "inn" to avoid conflicting with "in" keyword.
pub mod inn;
// generated with bindgen /usr/include/linux/sockios.h --no-unstable-rust
// --constified-enum '*' --with-derive-default
pub mod sockios;
pub use crate::if_tun::*;
pub use crate::iff::*;
pub use crate::inn::*;
pub use crate::sockios::*;
pub const TUNTAP: ::std::os::raw::c_uint = 84;
pub const ARPHRD_ETHER: sa_family_t = 1;
ioctl_iow_nr!(TUNSETNOCSUM, TUNTAP, 200, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETDEBUG, TUNTAP, 201, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETIFF, TUNTAP, 202, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETPERSIST, TUNTAP, 203, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETOWNER, TUNTAP, 204, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETLINK, TUNTAP, 205, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETGROUP, TUNTAP, 206, ::std::os::raw::c_int);
ioctl_ior_nr!(TUNGETFEATURES, TUNTAP, 207, ::std::os::raw::c_uint);
ioctl_iow_nr!(TUNSETOFFLOAD, TUNTAP, 208, ::std::os::raw::c_uint);
ioctl_iow_nr!(TUNSETTXFILTER, TUNTAP, 209, ::std::os::raw::c_uint);
ioctl_ior_nr!(TUNGETIFF, TUNTAP, 210, ::std::os::raw::c_uint);
ioctl_ior_nr!(TUNGETSNDBUF, TUNTAP, 211, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETSNDBUF, TUNTAP, 212, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNATTACHFILTER, TUNTAP, 213, sock_fprog);
ioctl_iow_nr!(TUNDETACHFILTER, TUNTAP, 214, sock_fprog);
ioctl_ior_nr!(TUNGETVNETHDRSZ, TUNTAP, 215, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETVNETHDRSZ, TUNTAP, 216, ::std::os::raw::c_int); | ioctl_iow_nr!(TUNSETIFINDEX, TUNTAP, 218, ::std::os::raw::c_uint);
ioctl_ior_nr!(TUNGETFILTER, TUNTAP, 219, sock_fprog);
ioctl_iow_nr!(TUNSETVNETLE, TUNTAP, 220, ::std::os::raw::c_int);
ioctl_ior_nr!(TUNGETVNETLE, TUNTAP, 221, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETVNETBE, TUNTAP, 222, ::std::os::raw::c_int);
ioctl_ior_nr!(TUNGETVNETBE, TUNTAP, 223, ::std::os::raw::c_int); | ioctl_iow_nr!(TUNSETQUEUE, TUNTAP, 217, ::std::os::raw::c_int); | random_line_split |
mod.rs | // Copyright (C) 2020 Sebastian Dröge <[email protected]>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use glib::prelude::*;
mod imp;
// The public Rust wrapper type for our element
glib::glib_wrapper! {
pub struct Rgb2Gray(ObjectSubclass<imp::Rgb2Gray>) @extends gst_base::BaseTransform, gst::Element, gst::Object;
}
// GStreamer elements need to be thread-safe. For the private implementation this is automatically
// enforced but for the public wrapper type we need to specify this manually.
unsafe impl Send for Rgb2Gray {}
unsafe impl Sync for Rgb2Gray {}
| // the name "rsrgb2gray" for being able to instantiate it via e.g.
// gst::ElementFactory::make().
pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
gst::Element::register(
Some(plugin),
"rsrgb2gray",
gst::Rank::None,
Rgb2Gray::static_type(),
)
} | // Registers the type for our element, and then registers in GStreamer under | random_line_split |
mod.rs | // Copyright (C) 2020 Sebastian Dröge <[email protected]>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use glib::prelude::*;
mod imp;
// The public Rust wrapper type for our element
glib::glib_wrapper! {
pub struct Rgb2Gray(ObjectSubclass<imp::Rgb2Gray>) @extends gst_base::BaseTransform, gst::Element, gst::Object;
}
// GStreamer elements need to be thread-safe. For the private implementation this is automatically
// enforced but for the public wrapper type we need to specify this manually.
unsafe impl Send for Rgb2Gray {}
unsafe impl Sync for Rgb2Gray {}
// Registers the type for our element, and then registers in GStreamer under
// the name "rsrgb2gray" for being able to instantiate it via e.g.
// gst::ElementFactory::make().
pub fn r | plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
gst::Element::register(
Some(plugin),
"rsrgb2gray",
gst::Rank::None,
Rgb2Gray::static_type(),
)
}
| egister( | identifier_name |
mod.rs | // Copyright (C) 2020 Sebastian Dröge <[email protected]>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use glib::prelude::*;
mod imp;
// The public Rust wrapper type for our element
glib::glib_wrapper! {
pub struct Rgb2Gray(ObjectSubclass<imp::Rgb2Gray>) @extends gst_base::BaseTransform, gst::Element, gst::Object;
}
// GStreamer elements need to be thread-safe. For the private implementation this is automatically
// enforced but for the public wrapper type we need to specify this manually.
unsafe impl Send for Rgb2Gray {}
unsafe impl Sync for Rgb2Gray {}
// Registers the type for our element, and then registers in GStreamer under
// the name "rsrgb2gray" for being able to instantiate it via e.g.
// gst::ElementFactory::make().
pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { |
gst::Element::register(
Some(plugin),
"rsrgb2gray",
gst::Rank::None,
Rgb2Gray::static_type(),
)
}
| identifier_body |
|
build.rs | use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;
fn rustc_version()->String {
let cmd = Command::new(env::var("RUSTC").unwrap())
.args(&["--version"])
.output()
.expect("failed to execute process");
let mut x = String::from_utf8(cmd.stdout).unwrap();
x = x.trim().to_string();
if x.starts_with("rustc") |
x
}
fn pybuildinfo()->Vec<u8> {
let pyscript = "
import os
import sys
if __name__ == '__main__':
path = os.path.abspath(os.path.join(os.getcwd(), '..'))
sys.path.append(path)
import pybuildinfo.cmd
pybuildinfo.cmd.cmd(sys.argv[2:])
";
let dict = format!("-dict={}", format!("{{
\"build_toolchain\": \"rustc\",
\"build_toolchain_version\": \"{}\",
\"build_target\": \"{}\"
}}", rustc_version(), env::var("TARGET").unwrap()));
let cmd = Command::new("python")
.args(&["-c", pyscript, "-vcs=\"..\"", "-template=buildinfo_template.rs", &dict])
.output()
.expect("failed to execute process");
assert_eq!(cmd.status.code().unwrap(), 0);
cmd.stdout
}
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("pybuildinfo.rs");
let mut f = File::create(&dest_path).unwrap();
let buildinfo = pybuildinfo();
f.write_all(&buildinfo).unwrap();
}
| {
x = x[5..].trim().to_string();
} | conditional_block |
build.rs | use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;
fn rustc_version()->String |
fn pybuildinfo()->Vec<u8> {
let pyscript = "
import os
import sys
if __name__ == '__main__':
path = os.path.abspath(os.path.join(os.getcwd(), '..'))
sys.path.append(path)
import pybuildinfo.cmd
pybuildinfo.cmd.cmd(sys.argv[2:])
";
let dict = format!("-dict={}", format!("{{
\"build_toolchain\": \"rustc\",
\"build_toolchain_version\": \"{}\",
\"build_target\": \"{}\"
}}", rustc_version(), env::var("TARGET").unwrap()));
let cmd = Command::new("python")
.args(&["-c", pyscript, "-vcs=\"..\"", "-template=buildinfo_template.rs", &dict])
.output()
.expect("failed to execute process");
assert_eq!(cmd.status.code().unwrap(), 0);
cmd.stdout
}
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("pybuildinfo.rs");
let mut f = File::create(&dest_path).unwrap();
let buildinfo = pybuildinfo();
f.write_all(&buildinfo).unwrap();
}
| {
let cmd = Command::new(env::var("RUSTC").unwrap())
.args(&["--version"])
.output()
.expect("failed to execute process");
let mut x = String::from_utf8(cmd.stdout).unwrap();
x = x.trim().to_string();
if x.starts_with("rustc") {
x = x[5..].trim().to_string();
}
x
} | identifier_body |
build.rs | use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;
fn rustc_version()->String {
let cmd = Command::new(env::var("RUSTC").unwrap())
.args(&["--version"])
.output()
.expect("failed to execute process");
let mut x = String::from_utf8(cmd.stdout).unwrap();
x = x.trim().to_string();
if x.starts_with("rustc") {
x = x[5..].trim().to_string();
}
x
}
fn pybuildinfo()->Vec<u8> {
let pyscript = "
import os
import sys
if __name__ == '__main__':
path = os.path.abspath(os.path.join(os.getcwd(), '..'))
sys.path.append(path)
import pybuildinfo.cmd | \"build_toolchain_version\": \"{}\",
\"build_target\": \"{}\"
}}", rustc_version(), env::var("TARGET").unwrap()));
let cmd = Command::new("python")
.args(&["-c", pyscript, "-vcs=\"..\"", "-template=buildinfo_template.rs", &dict])
.output()
.expect("failed to execute process");
assert_eq!(cmd.status.code().unwrap(), 0);
cmd.stdout
}
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("pybuildinfo.rs");
let mut f = File::create(&dest_path).unwrap();
let buildinfo = pybuildinfo();
f.write_all(&buildinfo).unwrap();
} | pybuildinfo.cmd.cmd(sys.argv[2:])
";
let dict = format!("-dict={}", format!("{{
\"build_toolchain\": \"rustc\", | random_line_split |
build.rs | use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;
fn | ()->String {
let cmd = Command::new(env::var("RUSTC").unwrap())
.args(&["--version"])
.output()
.expect("failed to execute process");
let mut x = String::from_utf8(cmd.stdout).unwrap();
x = x.trim().to_string();
if x.starts_with("rustc") {
x = x[5..].trim().to_string();
}
x
}
fn pybuildinfo()->Vec<u8> {
let pyscript = "
import os
import sys
if __name__ == '__main__':
path = os.path.abspath(os.path.join(os.getcwd(), '..'))
sys.path.append(path)
import pybuildinfo.cmd
pybuildinfo.cmd.cmd(sys.argv[2:])
";
let dict = format!("-dict={}", format!("{{
\"build_toolchain\": \"rustc\",
\"build_toolchain_version\": \"{}\",
\"build_target\": \"{}\"
}}", rustc_version(), env::var("TARGET").unwrap()));
let cmd = Command::new("python")
.args(&["-c", pyscript, "-vcs=\"..\"", "-template=buildinfo_template.rs", &dict])
.output()
.expect("failed to execute process");
assert_eq!(cmd.status.code().unwrap(), 0);
cmd.stdout
}
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("pybuildinfo.rs");
let mut f = File::create(&dest_path).unwrap();
let buildinfo = pybuildinfo();
f.write_all(&buildinfo).unwrap();
}
| rustc_version | identifier_name |
mod.rs | use syntax::ptr::P;
use syntax::{ast, codemap};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use html::HtmlState;
mod template;
/// Trait meaning something can be turned into an ast::Item with configuration.
pub trait Generate<Cfg> {
/// Turn Self into an ast::Item with a configuration object.
fn generate(
self,
codemap::Span,
&mut base::ExtCtxt,
Cfg
) -> P<ast::Item>;
} | ///
///
///
impl Generate<()> for HtmlState {
fn generate(
self,
sp: codemap::Span,
cx: &mut base::ExtCtxt,
_: ()
) -> P<ast::Item> {
let skin = self.skin.clone().unwrap();
let template_items = self.templates.into_iter().map(
|template| template.generate(sp, cx, ())
).collect();
// we create the module made of the created function
cx.item_mod(sp, sp, skin, vec![], vec![], template_items)
}
} | random_line_split |
|
mod.rs |
use syntax::ptr::P;
use syntax::{ast, codemap};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use html::HtmlState;
mod template;
/// Trait meaning something can be turned into an ast::Item with configuration.
pub trait Generate<Cfg> {
/// Turn Self into an ast::Item with a configuration object.
fn generate(
self,
codemap::Span,
&mut base::ExtCtxt,
Cfg
) -> P<ast::Item>;
}
///
///
///
impl Generate<()> for HtmlState {
fn | (
self,
sp: codemap::Span,
cx: &mut base::ExtCtxt,
_: ()
) -> P<ast::Item> {
let skin = self.skin.clone().unwrap();
let template_items = self.templates.into_iter().map(
|template| template.generate(sp, cx, ())
).collect();
// we create the module made of the created function
cx.item_mod(sp, sp, skin, vec![], vec![], template_items)
}
}
| generate | identifier_name |
mod.rs |
use syntax::ptr::P;
use syntax::{ast, codemap};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use html::HtmlState;
mod template;
/// Trait meaning something can be turned into an ast::Item with configuration.
pub trait Generate<Cfg> {
/// Turn Self into an ast::Item with a configuration object.
fn generate(
self,
codemap::Span,
&mut base::ExtCtxt,
Cfg
) -> P<ast::Item>;
}
///
///
///
impl Generate<()> for HtmlState {
fn generate(
self,
sp: codemap::Span,
cx: &mut base::ExtCtxt,
_: ()
) -> P<ast::Item> |
}
| {
let skin = self.skin.clone().unwrap();
let template_items = self.templates.into_iter().map(
|template| template.generate(sp, cx, ())
).collect();
// we create the module made of the created function
cx.item_mod(sp, sp, skin, vec![], vec![], template_items)
} | identifier_body |
billow.rs | // example.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::billow::Billow;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn | () {
let mut ngen = Billow::new_rand(24, 0.5, 2.5, 100.0);
println!("Noise seed is {}", ngen.get_seed());
let img_size = 512 as u32;
let mut imbuf = image::ImageBuf::new(img_size, img_size);
let start = precise_time_s();
for x in range(0, img_size) {
for y in range(0, img_size) {
let n = ngen.get_value2d((x as f64), (y as f64));
let col = (n * 255.0) as u8;
let pixel = image::Luma(col);
imbuf.put_pixel(x, y, pixel);
}
}
let end = precise_time_s();
let fout = File::create(&Path::new("billow.png")).unwrap();
let _ = image::ImageLuma8(imbuf).save(fout, image::PNG);
println!("billow.png saved");
println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0);
}
| main | identifier_name |
billow.rs | // example.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::billow::Billow;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn main() | let _ = image::ImageLuma8(imbuf).save(fout, image::PNG);
println!("billow.png saved");
println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0);
}
| {
let mut ngen = Billow::new_rand(24, 0.5, 2.5, 100.0);
println!("Noise seed is {}", ngen.get_seed());
let img_size = 512 as u32;
let mut imbuf = image::ImageBuf::new(img_size, img_size);
let start = precise_time_s();
for x in range(0, img_size) {
for y in range(0, img_size) {
let n = ngen.get_value2d((x as f64), (y as f64));
let col = (n * 255.0) as u8;
let pixel = image::Luma(col);
imbuf.put_pixel(x, y, pixel);
}
}
let end = precise_time_s();
let fout = File::create(&Path::new("billow.png")).unwrap();
| identifier_body |
billow.rs | // example.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::billow::Billow;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn main() {
let mut ngen = Billow::new_rand(24, 0.5, 2.5, 100.0);
println!("Noise seed is {}", ngen.get_seed());
let img_size = 512 as u32;
let mut imbuf = image::ImageBuf::new(img_size, img_size);
| let n = ngen.get_value2d((x as f64), (y as f64));
let col = (n * 255.0) as u8;
let pixel = image::Luma(col);
imbuf.put_pixel(x, y, pixel);
}
}
let end = precise_time_s();
let fout = File::create(&Path::new("billow.png")).unwrap();
let _ = image::ImageLuma8(imbuf).save(fout, image::PNG);
println!("billow.png saved");
println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0);
} | let start = precise_time_s();
for x in range(0, img_size) {
for y in range(0, img_size) {
| random_line_split |
live_timers.rs | use std::collections::HashMap;
use platform::time::time_now;
use super::StartTime;
use super::Timing;
#[derive(Debug, Clone, PartialEq)]
pub struct LiveTimers {
timers: HashMap<String, StartTime>,
} |
impl LiveTimers {
pub fn new() -> LiveTimers {
LiveTimers { timers: HashMap::new() }
}
pub fn get_timers(&self) -> &HashMap<String, StartTime> {
&self.timers
}
pub fn start(&mut self, name: &str) -> StartTime {
let start_time = time_now();
self.timers.insert(name.to_string(), start_time.clone());
start_time
}
pub fn stop(&mut self, name: &str) -> Timing {
let stop_time = time_now();
let opt = self.timers.remove(name);
if opt.is_none() {
panic!("Tried to stop non-live timer: {:?}", name);
}
let start_time = opt.unwrap();
let duration = stop_time - start_time;
Timing::new(name, start_time, duration)
}
} | random_line_split |
|
live_timers.rs | use std::collections::HashMap;
use platform::time::time_now;
use super::StartTime;
use super::Timing;
#[derive(Debug, Clone, PartialEq)]
pub struct LiveTimers {
timers: HashMap<String, StartTime>,
}
impl LiveTimers {
pub fn | () -> LiveTimers {
LiveTimers { timers: HashMap::new() }
}
pub fn get_timers(&self) -> &HashMap<String, StartTime> {
&self.timers
}
pub fn start(&mut self, name: &str) -> StartTime {
let start_time = time_now();
self.timers.insert(name.to_string(), start_time.clone());
start_time
}
pub fn stop(&mut self, name: &str) -> Timing {
let stop_time = time_now();
let opt = self.timers.remove(name);
if opt.is_none() {
panic!("Tried to stop non-live timer: {:?}", name);
}
let start_time = opt.unwrap();
let duration = stop_time - start_time;
Timing::new(name, start_time, duration)
}
}
| new | identifier_name |
live_timers.rs | use std::collections::HashMap;
use platform::time::time_now;
use super::StartTime;
use super::Timing;
#[derive(Debug, Clone, PartialEq)]
pub struct LiveTimers {
timers: HashMap<String, StartTime>,
}
impl LiveTimers {
pub fn new() -> LiveTimers {
LiveTimers { timers: HashMap::new() }
}
pub fn get_timers(&self) -> &HashMap<String, StartTime> {
&self.timers
}
pub fn start(&mut self, name: &str) -> StartTime {
let start_time = time_now();
self.timers.insert(name.to_string(), start_time.clone());
start_time
}
pub fn stop(&mut self, name: &str) -> Timing {
let stop_time = time_now();
let opt = self.timers.remove(name);
if opt.is_none() |
let start_time = opt.unwrap();
let duration = stop_time - start_time;
Timing::new(name, start_time, duration)
}
}
| {
panic!("Tried to stop non-live timer: {:?}", name);
} | conditional_block |
live_timers.rs | use std::collections::HashMap;
use platform::time::time_now;
use super::StartTime;
use super::Timing;
#[derive(Debug, Clone, PartialEq)]
pub struct LiveTimers {
timers: HashMap<String, StartTime>,
}
impl LiveTimers {
pub fn new() -> LiveTimers {
LiveTimers { timers: HashMap::new() }
}
pub fn get_timers(&self) -> &HashMap<String, StartTime> |
pub fn start(&mut self, name: &str) -> StartTime {
let start_time = time_now();
self.timers.insert(name.to_string(), start_time.clone());
start_time
}
pub fn stop(&mut self, name: &str) -> Timing {
let stop_time = time_now();
let opt = self.timers.remove(name);
if opt.is_none() {
panic!("Tried to stop non-live timer: {:?}", name);
}
let start_time = opt.unwrap();
let duration = stop_time - start_time;
Timing::new(name, start_time, duration)
}
}
| {
&self.timers
} | identifier_body |
try_chan.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// 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.
//! A simple test program for evaluating the speed of cross-thread communications.
extern crate xi_rpc;
use std::thread;
use std::sync::mpsc;
/*
use xi_rpc::chan::Chan;
pub fn test_chan() {
let n_iter = 1000000;
let chan1 = Chan::new();
let chan1s = chan1.clone();
let chan2 = Chan::new();
let chan2s = chan2.clone();
let thread1 = thread::spawn(move|| {
for _ in 0..n_iter {
chan2s.try_send(chan1.recv());
}
});
let thread2 = thread::spawn(move|| {
for _ in 0..n_iter {
chan1s.try_send(42);
let _ = chan2.recv();
}
});
let _ = thread1.join();
let _ = thread2.join();
}
*/
pub fn test_mpsc() {
let n_iter = 1000000;
let (chan1s, chan1) = mpsc::channel();
let (chan2s, chan2) = mpsc::channel();
let thread1 = thread::spawn(move|| {
for _ in 0..n_iter {
chan2s.send(chan1.recv()).unwrap();
}
});
let thread2 = thread::spawn(move|| {
for _ in 0..n_iter {
chan1s.send(42).unwrap();
let _ = chan2.recv();
}
});
let _ = thread1.join();
let _ = thread2.join();
}
pub fn main() | {
test_mpsc()
} | identifier_body |
|
try_chan.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// 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.
//! A simple test program for evaluating the speed of cross-thread communications.
extern crate xi_rpc; | /*
use xi_rpc::chan::Chan;
pub fn test_chan() {
let n_iter = 1000000;
let chan1 = Chan::new();
let chan1s = chan1.clone();
let chan2 = Chan::new();
let chan2s = chan2.clone();
let thread1 = thread::spawn(move|| {
for _ in 0..n_iter {
chan2s.try_send(chan1.recv());
}
});
let thread2 = thread::spawn(move|| {
for _ in 0..n_iter {
chan1s.try_send(42);
let _ = chan2.recv();
}
});
let _ = thread1.join();
let _ = thread2.join();
}
*/
pub fn test_mpsc() {
let n_iter = 1000000;
let (chan1s, chan1) = mpsc::channel();
let (chan2s, chan2) = mpsc::channel();
let thread1 = thread::spawn(move|| {
for _ in 0..n_iter {
chan2s.send(chan1.recv()).unwrap();
}
});
let thread2 = thread::spawn(move|| {
for _ in 0..n_iter {
chan1s.send(42).unwrap();
let _ = chan2.recv();
}
});
let _ = thread1.join();
let _ = thread2.join();
}
pub fn main() {
test_mpsc()
} |
use std::thread;
use std::sync::mpsc;
| random_line_split |
try_chan.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// 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.
//! A simple test program for evaluating the speed of cross-thread communications.
extern crate xi_rpc;
use std::thread;
use std::sync::mpsc;
/*
use xi_rpc::chan::Chan;
pub fn test_chan() {
let n_iter = 1000000;
let chan1 = Chan::new();
let chan1s = chan1.clone();
let chan2 = Chan::new();
let chan2s = chan2.clone();
let thread1 = thread::spawn(move|| {
for _ in 0..n_iter {
chan2s.try_send(chan1.recv());
}
});
let thread2 = thread::spawn(move|| {
for _ in 0..n_iter {
chan1s.try_send(42);
let _ = chan2.recv();
}
});
let _ = thread1.join();
let _ = thread2.join();
}
*/
pub fn | () {
let n_iter = 1000000;
let (chan1s, chan1) = mpsc::channel();
let (chan2s, chan2) = mpsc::channel();
let thread1 = thread::spawn(move|| {
for _ in 0..n_iter {
chan2s.send(chan1.recv()).unwrap();
}
});
let thread2 = thread::spawn(move|| {
for _ in 0..n_iter {
chan1s.send(42).unwrap();
let _ = chan2.recv();
}
});
let _ = thread1.join();
let _ = thread2.join();
}
pub fn main() {
test_mpsc()
}
| test_mpsc | identifier_name |
get_type_id.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::any::Any;
use core::any::TypeId;
// #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub struct TypeId {
// t: u64,
// }
// impl<T: Reflect +'static> Any for T {
// fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
// }
type T = i32;
#[test]
fn get_type_id_test1() {
let x: T = 68;
let y: T = 500;
let x_typeid: TypeId = x.get_type_id();
let y_typeid: TypeId = y.get_type_id();
assert_eq!(x_typeid, y_typeid);
}
#[test]
fn get_type_id_test2() |
}
| {
struct A;
let x: A = A;
let _: TypeId = x.get_type_id();
} | identifier_body |
get_type_id.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::any::Any;
use core::any::TypeId;
// #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub struct TypeId {
// t: u64,
// }
// impl<T: Reflect +'static> Any for T {
// fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
// }
type T = i32;
#[test]
fn get_type_id_test1() {
let x: T = 68;
let y: T = 500;
let x_typeid: TypeId = x.get_type_id();
let y_typeid: TypeId = y.get_type_id();
assert_eq!(x_typeid, y_typeid);
}
#[test]
fn get_type_id_test2() {
struct A;
let x: A = A;
let _: TypeId = x.get_type_id(); | }
} | random_line_split |
|
get_type_id.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::any::Any;
use core::any::TypeId;
// #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub struct TypeId {
// t: u64,
// }
// impl<T: Reflect +'static> Any for T {
// fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
// }
type T = i32;
#[test]
fn get_type_id_test1() {
let x: T = 68;
let y: T = 500;
let x_typeid: TypeId = x.get_type_id();
let y_typeid: TypeId = y.get_type_id();
assert_eq!(x_typeid, y_typeid);
}
#[test]
fn get_type_id_test2() {
struct | ;
let x: A = A;
let _: TypeId = x.get_type_id();
}
}
| A | identifier_name |
sampler_renderer.rs | use core::{Camera, Integrator, Sampler, Scene};
use film::Spectrum;
use linalg::ray_differential::RayDifferential;
use integrator::{SurfaceIntegrator, VolumeIntegrator};
use renderer::Renderer;
pub struct SamplerRenderer<'a, S: Sampler, C: Camera> {
pub sampler: S,
pub camera: C,
pub surface_integrator: &'a SurfaceIntegrator,
pub volume_integrator: &'a VolumeIntegrator,
}
impl<'a, S: Sampler, C: Camera> SamplerRenderer<'a, S, C> {
fn new(sampler: S,
camera: C,
surface_integrator: &'a SurfaceIntegrator,
volume_integrator: &'a VolumeIntegrator)
-> SamplerRenderer<'a, S, C> {
SamplerRenderer {
sampler: sampler,
camera: camera,
surface_integrator: surface_integrator,
volume_integrator: volume_integrator,
}
}
}
impl<'a, S: Sampler, C: Camera> Renderer for SamplerRenderer<'a, S, C> {
fn render(&self, scene: &Scene) |
#[allow(unused_variables)]
fn li(&self, scene: &Scene, ray: &RayDifferential, sample: &Sampler) -> Box<Spectrum> {
unimplemented!()
}
#[allow(unused_variables)]
fn transmittance(&self,
scene: &Scene,
ray: &RayDifferential,
sample: &Sampler)
-> Box<Spectrum> {
unimplemented!()
}
}
| {
self.surface_integrator.preprocess(scene, &self.camera);
self.volume_integrator.preprocess(scene, &self.camera);
} | identifier_body |
sampler_renderer.rs | use core::{Camera, Integrator, Sampler, Scene};
use film::Spectrum;
use linalg::ray_differential::RayDifferential;
use integrator::{SurfaceIntegrator, VolumeIntegrator};
use renderer::Renderer;
pub struct SamplerRenderer<'a, S: Sampler, C: Camera> {
pub sampler: S,
pub camera: C,
pub surface_integrator: &'a SurfaceIntegrator,
pub volume_integrator: &'a VolumeIntegrator, | fn new(sampler: S,
camera: C,
surface_integrator: &'a SurfaceIntegrator,
volume_integrator: &'a VolumeIntegrator)
-> SamplerRenderer<'a, S, C> {
SamplerRenderer {
sampler: sampler,
camera: camera,
surface_integrator: surface_integrator,
volume_integrator: volume_integrator,
}
}
}
impl<'a, S: Sampler, C: Camera> Renderer for SamplerRenderer<'a, S, C> {
fn render(&self, scene: &Scene) {
self.surface_integrator.preprocess(scene, &self.camera);
self.volume_integrator.preprocess(scene, &self.camera);
}
#[allow(unused_variables)]
fn li(&self, scene: &Scene, ray: &RayDifferential, sample: &Sampler) -> Box<Spectrum> {
unimplemented!()
}
#[allow(unused_variables)]
fn transmittance(&self,
scene: &Scene,
ray: &RayDifferential,
sample: &Sampler)
-> Box<Spectrum> {
unimplemented!()
}
} | }
impl<'a, S: Sampler, C: Camera> SamplerRenderer<'a, S, C> { | random_line_split |
sampler_renderer.rs | use core::{Camera, Integrator, Sampler, Scene};
use film::Spectrum;
use linalg::ray_differential::RayDifferential;
use integrator::{SurfaceIntegrator, VolumeIntegrator};
use renderer::Renderer;
pub struct | <'a, S: Sampler, C: Camera> {
pub sampler: S,
pub camera: C,
pub surface_integrator: &'a SurfaceIntegrator,
pub volume_integrator: &'a VolumeIntegrator,
}
impl<'a, S: Sampler, C: Camera> SamplerRenderer<'a, S, C> {
fn new(sampler: S,
camera: C,
surface_integrator: &'a SurfaceIntegrator,
volume_integrator: &'a VolumeIntegrator)
-> SamplerRenderer<'a, S, C> {
SamplerRenderer {
sampler: sampler,
camera: camera,
surface_integrator: surface_integrator,
volume_integrator: volume_integrator,
}
}
}
impl<'a, S: Sampler, C: Camera> Renderer for SamplerRenderer<'a, S, C> {
fn render(&self, scene: &Scene) {
self.surface_integrator.preprocess(scene, &self.camera);
self.volume_integrator.preprocess(scene, &self.camera);
}
#[allow(unused_variables)]
fn li(&self, scene: &Scene, ray: &RayDifferential, sample: &Sampler) -> Box<Spectrum> {
unimplemented!()
}
#[allow(unused_variables)]
fn transmittance(&self,
scene: &Scene,
ray: &RayDifferential,
sample: &Sampler)
-> Box<Spectrum> {
unimplemented!()
}
}
| SamplerRenderer | identifier_name |
rmeta.rs | // Copyright 2016 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. | // aux-build:rmeta_rlib.rs
extern crate rmeta_aux;
use rmeta_aux::Foo;
pub fn main() {
let _ = Foo { field: 42 };
} |
// Test that using rlibs and rmeta dep crates work together. Specifically, that
// there can be both an rmeta and an rlib file and rustc will prefer the rlib.
// aux-build:rmeta_rmeta.rs | random_line_split |
rmeta.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that using rlibs and rmeta dep crates work together. Specifically, that
// there can be both an rmeta and an rlib file and rustc will prefer the rlib.
// aux-build:rmeta_rmeta.rs
// aux-build:rmeta_rlib.rs
extern crate rmeta_aux;
use rmeta_aux::Foo;
pub fn main() | {
let _ = Foo { field: 42 };
} | identifier_body |
|
rmeta.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test that using rlibs and rmeta dep crates work together. Specifically, that
// there can be both an rmeta and an rlib file and rustc will prefer the rlib.
// aux-build:rmeta_rmeta.rs
// aux-build:rmeta_rlib.rs
extern crate rmeta_aux;
use rmeta_aux::Foo;
pub fn | () {
let _ = Foo { field: 42 };
}
| main | identifier_name |
metadata.rs | use ape;
use id3;
use lewton::inside_ogg::OggStreamReader;
use metaflac;
use mp3_duration;
use regex::Regex;
use std::fs;
use std::path::Path;
use errors::*;
use utils;
use utils::AudioFormat;
#[derive(Debug, Clone, PartialEq)]
pub struct SongTags {
pub disc_number: Option<u32>,
pub track_number: Option<u32>,
pub title: Option<String>,
pub duration: Option<u32>,
pub artist: Option<String>,
pub album_artist: Option<String>,
pub album: Option<String>,
pub year: Option<i32>,
}
pub fn read(path: &Path) -> Result<SongTags> {
match utils::get_audio_format(path) {
Some(AudioFormat::FLAC) => read_flac(path),
Some(AudioFormat::MP3) => read_id3(path),
Some(AudioFormat::MPC) => read_ape(path),
Some(AudioFormat::OGG) => read_vorbis(path),
_ => bail!("Unsupported file format for reading metadata"),
}
}
fn read_id3(path: &Path) -> Result<SongTags> {
let tag = id3::Tag::read_from_path(&path)?;
let duration = mp3_duration::from_path(&path).map(|d| d.as_secs() as u32).ok();
let artist = tag.artist().map(|s| s.to_string());
let album_artist = tag.album_artist().map(|s| s.to_string());
let album = tag.album().map(|s| s.to_string());
let title = tag.title().map(|s| s.to_string());
let disc_number = tag.disc();
let track_number = tag.track();
let year = tag.year()
.map(|y| y as i32)
.or(tag.date_released().and_then(|d| Some(d.year)))
.or(tag.date_recorded().and_then(|d| Some(d.year)));
Ok(SongTags {
artist: artist,
album_artist: album_artist,
album: album,
title: title,
duration: duration,
disc_number: disc_number,
track_number: track_number,
year: year,
})
}
fn read_ape_string(item: &ape::Item) -> Option<String> {
match item.value {
ape::ItemValue::Text(ref s) => Some(s.clone()),
_ => None,
}
}
fn read_ape_i32(item: &ape::Item) -> Option<i32> {
match item.value {
ape::ItemValue::Text(ref s) => s.parse::<i32>().ok(),
_ => None,
}
}
fn read_ape_x_of_y(item: &ape::Item) -> Option<u32> {
match item.value {
ape::ItemValue::Text(ref s) => {
let format = Regex::new(r#"^\d+"#).unwrap();
if let Some(m) = format.find(s) {
s[m.start()..m.end()].parse().ok()
} else {
None
}
}
_ => None,
}
}
fn read_ape(path: &Path) -> Result<SongTags> {
let tag = ape::read(path)?;
let artist = tag.item("Artist").and_then(read_ape_string);
let album = tag.item("Album").and_then(read_ape_string);
let album_artist = tag.item("Album artist").and_then(read_ape_string);
let title = tag.item("Title").and_then(read_ape_string);
let year = tag.item("Year").and_then(read_ape_i32);
let disc_number = tag.item("Disc").and_then(read_ape_x_of_y);
let track_number = tag.item("Track").and_then(read_ape_x_of_y);
Ok(SongTags {
artist: artist,
album_artist: album_artist,
album: album,
title: title,
duration: None,
disc_number: disc_number,
track_number: track_number,
year: year,
})
}
fn read_vorbis(path: &Path) -> Result<SongTags> {
let file = fs::File::open(path)?;
let source = OggStreamReader::new(file)?;
let mut tags = SongTags {
artist: None,
album_artist: None,
album: None,
title: None,
duration:None,
disc_number: None,
track_number: None,
year: None,
};
for (key, value) in source.comment_hdr.comment_list {
match key.as_str() {
"TITLE" => tags.title = Some(value),
"ALBUM" => tags.album = Some(value),
"ARTIST" => tags.artist = Some(value),
"ALBUMARTIST" => tags.album_artist = Some(value),
"TRACKNUMBER" => tags.track_number = value.parse::<u32>().ok(),
"DISCNUMBER" => tags.disc_number = value.parse::<u32>().ok(),
"DATE" => tags.year = value.parse::<i32>().ok(),
_ => (),
}
}
Ok(tags)
}
fn read_flac(path: &Path) -> Result<SongTags> {
let tag = metaflac::Tag::read_from_path(path)?;
let vorbis = tag.vorbis_comments().ok_or("Missing Vorbis comments")?;
let disc_number = vorbis
.get("DISCNUMBER")
.and_then(|d| d[0].parse::<u32>().ok());
let year = vorbis.get("DATE").and_then(|d| d[0].parse::<i32>().ok());
let streaminfo = tag.get_blocks(metaflac::BlockType::StreamInfo);
let duration = match streaminfo.first() {
Some(&&metaflac::Block::StreamInfo(ref s)) => Some((s.total_samples as u32 / s.sample_rate) as u32),
_ => None
};
Ok(SongTags {
artist: vorbis.artist().map(|v| v[0].clone()),
album_artist: vorbis.album_artist().map(|v| v[0].clone()),
album: vorbis.album().map(|v| v[0].clone()),
title: vorbis.title().map(|v| v[0].clone()),
duration: duration,
disc_number: disc_number,
track_number: vorbis.track(),
year: year,
})
}
#[test]
fn test_read_metadata() {
let sample_tags = SongTags {
disc_number: Some(3),
track_number: Some(1),
title: Some("TEST TITLE".into()),
artist: Some("TEST ARTIST".into()),
album_artist: Some("TEST ALBUM ARTIST".into()),
album: Some("TEST ALBUM".into()),
duration: None, | let mp3_sample_tag = SongTags {duration: Some(0),..sample_tags.clone()};
assert_eq!(read(Path::new("test/sample.mp3")).unwrap(), mp3_sample_tag);
assert_eq!(read(Path::new("test/sample.ogg")).unwrap(), sample_tags);
assert_eq!(read(Path::new("test/sample.flac")).unwrap(), flac_sample_tag);
} | year: Some(2016),
};
let flac_sample_tag = SongTags {duration: Some(0), ..sample_tags.clone()}; | random_line_split |
metadata.rs | use ape;
use id3;
use lewton::inside_ogg::OggStreamReader;
use metaflac;
use mp3_duration;
use regex::Regex;
use std::fs;
use std::path::Path;
use errors::*;
use utils;
use utils::AudioFormat;
#[derive(Debug, Clone, PartialEq)]
pub struct SongTags {
pub disc_number: Option<u32>,
pub track_number: Option<u32>,
pub title: Option<String>,
pub duration: Option<u32>,
pub artist: Option<String>,
pub album_artist: Option<String>,
pub album: Option<String>,
pub year: Option<i32>,
}
pub fn read(path: &Path) -> Result<SongTags> {
match utils::get_audio_format(path) {
Some(AudioFormat::FLAC) => read_flac(path),
Some(AudioFormat::MP3) => read_id3(path),
Some(AudioFormat::MPC) => read_ape(path),
Some(AudioFormat::OGG) => read_vorbis(path),
_ => bail!("Unsupported file format for reading metadata"),
}
}
fn read_id3(path: &Path) -> Result<SongTags> {
let tag = id3::Tag::read_from_path(&path)?;
let duration = mp3_duration::from_path(&path).map(|d| d.as_secs() as u32).ok();
let artist = tag.artist().map(|s| s.to_string());
let album_artist = tag.album_artist().map(|s| s.to_string());
let album = tag.album().map(|s| s.to_string());
let title = tag.title().map(|s| s.to_string());
let disc_number = tag.disc();
let track_number = tag.track();
let year = tag.year()
.map(|y| y as i32)
.or(tag.date_released().and_then(|d| Some(d.year)))
.or(tag.date_recorded().and_then(|d| Some(d.year)));
Ok(SongTags {
artist: artist,
album_artist: album_artist,
album: album,
title: title,
duration: duration,
disc_number: disc_number,
track_number: track_number,
year: year,
})
}
fn read_ape_string(item: &ape::Item) -> Option<String> {
match item.value {
ape::ItemValue::Text(ref s) => Some(s.clone()),
_ => None,
}
}
fn read_ape_i32(item: &ape::Item) -> Option<i32> {
match item.value {
ape::ItemValue::Text(ref s) => s.parse::<i32>().ok(),
_ => None,
}
}
fn read_ape_x_of_y(item: &ape::Item) -> Option<u32> {
match item.value {
ape::ItemValue::Text(ref s) => {
let format = Regex::new(r#"^\d+"#).unwrap();
if let Some(m) = format.find(s) {
s[m.start()..m.end()].parse().ok()
} else {
None
}
}
_ => None,
}
}
fn read_ape(path: &Path) -> Result<SongTags> {
let tag = ape::read(path)?;
let artist = tag.item("Artist").and_then(read_ape_string);
let album = tag.item("Album").and_then(read_ape_string);
let album_artist = tag.item("Album artist").and_then(read_ape_string);
let title = tag.item("Title").and_then(read_ape_string);
let year = tag.item("Year").and_then(read_ape_i32);
let disc_number = tag.item("Disc").and_then(read_ape_x_of_y);
let track_number = tag.item("Track").and_then(read_ape_x_of_y);
Ok(SongTags {
artist: artist,
album_artist: album_artist,
album: album,
title: title,
duration: None,
disc_number: disc_number,
track_number: track_number,
year: year,
})
}
fn read_vorbis(path: &Path) -> Result<SongTags> {
let file = fs::File::open(path)?;
let source = OggStreamReader::new(file)?;
let mut tags = SongTags {
artist: None,
album_artist: None,
album: None,
title: None,
duration:None,
disc_number: None,
track_number: None,
year: None,
};
for (key, value) in source.comment_hdr.comment_list {
match key.as_str() {
"TITLE" => tags.title = Some(value),
"ALBUM" => tags.album = Some(value),
"ARTIST" => tags.artist = Some(value),
"ALBUMARTIST" => tags.album_artist = Some(value),
"TRACKNUMBER" => tags.track_number = value.parse::<u32>().ok(),
"DISCNUMBER" => tags.disc_number = value.parse::<u32>().ok(),
"DATE" => tags.year = value.parse::<i32>().ok(),
_ => (),
}
}
Ok(tags)
}
fn | (path: &Path) -> Result<SongTags> {
let tag = metaflac::Tag::read_from_path(path)?;
let vorbis = tag.vorbis_comments().ok_or("Missing Vorbis comments")?;
let disc_number = vorbis
.get("DISCNUMBER")
.and_then(|d| d[0].parse::<u32>().ok());
let year = vorbis.get("DATE").and_then(|d| d[0].parse::<i32>().ok());
let streaminfo = tag.get_blocks(metaflac::BlockType::StreamInfo);
let duration = match streaminfo.first() {
Some(&&metaflac::Block::StreamInfo(ref s)) => Some((s.total_samples as u32 / s.sample_rate) as u32),
_ => None
};
Ok(SongTags {
artist: vorbis.artist().map(|v| v[0].clone()),
album_artist: vorbis.album_artist().map(|v| v[0].clone()),
album: vorbis.album().map(|v| v[0].clone()),
title: vorbis.title().map(|v| v[0].clone()),
duration: duration,
disc_number: disc_number,
track_number: vorbis.track(),
year: year,
})
}
#[test]
fn test_read_metadata() {
let sample_tags = SongTags {
disc_number: Some(3),
track_number: Some(1),
title: Some("TEST TITLE".into()),
artist: Some("TEST ARTIST".into()),
album_artist: Some("TEST ALBUM ARTIST".into()),
album: Some("TEST ALBUM".into()),
duration: None,
year: Some(2016),
};
let flac_sample_tag = SongTags {duration: Some(0),..sample_tags.clone()};
let mp3_sample_tag = SongTags {duration: Some(0),..sample_tags.clone()};
assert_eq!(read(Path::new("test/sample.mp3")).unwrap(), mp3_sample_tag);
assert_eq!(read(Path::new("test/sample.ogg")).unwrap(), sample_tags);
assert_eq!(read(Path::new("test/sample.flac")).unwrap(), flac_sample_tag);
}
| read_flac | identifier_name |
metadata.rs | use ape;
use id3;
use lewton::inside_ogg::OggStreamReader;
use metaflac;
use mp3_duration;
use regex::Regex;
use std::fs;
use std::path::Path;
use errors::*;
use utils;
use utils::AudioFormat;
#[derive(Debug, Clone, PartialEq)]
pub struct SongTags {
pub disc_number: Option<u32>,
pub track_number: Option<u32>,
pub title: Option<String>,
pub duration: Option<u32>,
pub artist: Option<String>,
pub album_artist: Option<String>,
pub album: Option<String>,
pub year: Option<i32>,
}
pub fn read(path: &Path) -> Result<SongTags> {
match utils::get_audio_format(path) {
Some(AudioFormat::FLAC) => read_flac(path),
Some(AudioFormat::MP3) => read_id3(path),
Some(AudioFormat::MPC) => read_ape(path),
Some(AudioFormat::OGG) => read_vorbis(path),
_ => bail!("Unsupported file format for reading metadata"),
}
}
fn read_id3(path: &Path) -> Result<SongTags> {
let tag = id3::Tag::read_from_path(&path)?;
let duration = mp3_duration::from_path(&path).map(|d| d.as_secs() as u32).ok();
let artist = tag.artist().map(|s| s.to_string());
let album_artist = tag.album_artist().map(|s| s.to_string());
let album = tag.album().map(|s| s.to_string());
let title = tag.title().map(|s| s.to_string());
let disc_number = tag.disc();
let track_number = tag.track();
let year = tag.year()
.map(|y| y as i32)
.or(tag.date_released().and_then(|d| Some(d.year)))
.or(tag.date_recorded().and_then(|d| Some(d.year)));
Ok(SongTags {
artist: artist,
album_artist: album_artist,
album: album,
title: title,
duration: duration,
disc_number: disc_number,
track_number: track_number,
year: year,
})
}
fn read_ape_string(item: &ape::Item) -> Option<String> {
match item.value {
ape::ItemValue::Text(ref s) => Some(s.clone()),
_ => None,
}
}
fn read_ape_i32(item: &ape::Item) -> Option<i32> {
match item.value {
ape::ItemValue::Text(ref s) => s.parse::<i32>().ok(),
_ => None,
}
}
fn read_ape_x_of_y(item: &ape::Item) -> Option<u32> |
fn read_ape(path: &Path) -> Result<SongTags> {
let tag = ape::read(path)?;
let artist = tag.item("Artist").and_then(read_ape_string);
let album = tag.item("Album").and_then(read_ape_string);
let album_artist = tag.item("Album artist").and_then(read_ape_string);
let title = tag.item("Title").and_then(read_ape_string);
let year = tag.item("Year").and_then(read_ape_i32);
let disc_number = tag.item("Disc").and_then(read_ape_x_of_y);
let track_number = tag.item("Track").and_then(read_ape_x_of_y);
Ok(SongTags {
artist: artist,
album_artist: album_artist,
album: album,
title: title,
duration: None,
disc_number: disc_number,
track_number: track_number,
year: year,
})
}
fn read_vorbis(path: &Path) -> Result<SongTags> {
let file = fs::File::open(path)?;
let source = OggStreamReader::new(file)?;
let mut tags = SongTags {
artist: None,
album_artist: None,
album: None,
title: None,
duration:None,
disc_number: None,
track_number: None,
year: None,
};
for (key, value) in source.comment_hdr.comment_list {
match key.as_str() {
"TITLE" => tags.title = Some(value),
"ALBUM" => tags.album = Some(value),
"ARTIST" => tags.artist = Some(value),
"ALBUMARTIST" => tags.album_artist = Some(value),
"TRACKNUMBER" => tags.track_number = value.parse::<u32>().ok(),
"DISCNUMBER" => tags.disc_number = value.parse::<u32>().ok(),
"DATE" => tags.year = value.parse::<i32>().ok(),
_ => (),
}
}
Ok(tags)
}
fn read_flac(path: &Path) -> Result<SongTags> {
let tag = metaflac::Tag::read_from_path(path)?;
let vorbis = tag.vorbis_comments().ok_or("Missing Vorbis comments")?;
let disc_number = vorbis
.get("DISCNUMBER")
.and_then(|d| d[0].parse::<u32>().ok());
let year = vorbis.get("DATE").and_then(|d| d[0].parse::<i32>().ok());
let streaminfo = tag.get_blocks(metaflac::BlockType::StreamInfo);
let duration = match streaminfo.first() {
Some(&&metaflac::Block::StreamInfo(ref s)) => Some((s.total_samples as u32 / s.sample_rate) as u32),
_ => None
};
Ok(SongTags {
artist: vorbis.artist().map(|v| v[0].clone()),
album_artist: vorbis.album_artist().map(|v| v[0].clone()),
album: vorbis.album().map(|v| v[0].clone()),
title: vorbis.title().map(|v| v[0].clone()),
duration: duration,
disc_number: disc_number,
track_number: vorbis.track(),
year: year,
})
}
#[test]
fn test_read_metadata() {
let sample_tags = SongTags {
disc_number: Some(3),
track_number: Some(1),
title: Some("TEST TITLE".into()),
artist: Some("TEST ARTIST".into()),
album_artist: Some("TEST ALBUM ARTIST".into()),
album: Some("TEST ALBUM".into()),
duration: None,
year: Some(2016),
};
let flac_sample_tag = SongTags {duration: Some(0),..sample_tags.clone()};
let mp3_sample_tag = SongTags {duration: Some(0),..sample_tags.clone()};
assert_eq!(read(Path::new("test/sample.mp3")).unwrap(), mp3_sample_tag);
assert_eq!(read(Path::new("test/sample.ogg")).unwrap(), sample_tags);
assert_eq!(read(Path::new("test/sample.flac")).unwrap(), flac_sample_tag);
}
| {
match item.value {
ape::ItemValue::Text(ref s) => {
let format = Regex::new(r#"^\d+"#).unwrap();
if let Some(m) = format.find(s) {
s[m.start()..m.end()].parse().ok()
} else {
None
}
}
_ => None,
}
} | identifier_body |
app.rs | use clap::{App, Arg};
const DEFAULT_RETRY_INTERVAL: &str = "1000";
const DEFAULT_UPDATE_INTERVAL: &str = "1000";
const DEFAULT_CALCULATION_THREADS: &str = "1";
const DEFAULT_CALCULATION_LIMIT: &str = "1000";
const DEFAULT_GENERATION_LIMIT: &str = "10";
const DEFAULT_MILESTONE_ADDRESS: &str =
"KPWCHICGJZXKE9GSUDXZYUAPLHAKAHYHDXNPHENTE\
RYMMBQOPSQIDENXKLKCEYCPVTZQLEEJVYJZV9BWU";
const DEFAULT_MILESTONE_START_INDEX: &str = "62000";
const DEFAULT_LOG_CONFIG: &str = "log4rs.yaml";
pub fn build<'a, 'b>() -> App<'a, 'b> | .arg(
Arg::with_name("retry_interval")
.short("r")
.long("retry-interval")
.takes_value(true)
.value_name("INTERVAL")
.default_value(DEFAULT_RETRY_INTERVAL)
.help("MySQL connect retry interval in milliseconds"),
)
.arg(
Arg::with_name("update_interval")
.short("u")
.long("update-interval")
.takes_value(true)
.value_name("INTERVAL")
.default_value(DEFAULT_UPDATE_INTERVAL)
.help("MySQL update interval in milliseconds"),
)
.arg(
Arg::with_name("calculation_threads")
.short("T")
.long("calculation-threads")
.takes_value(true)
.value_name("THREADS")
.default_value(DEFAULT_CALCULATION_THREADS)
.help("Number of calculation threads"),
)
.arg(
Arg::with_name("calculation_limit")
.short("t")
.long("calculation-limit")
.takes_value(true)
.value_name("LIMIT")
.default_value(DEFAULT_CALCULATION_LIMIT)
.help("Calculation depth limit"),
)
.arg(
Arg::with_name("generation_limit")
.short("g")
.long("generation-limit")
.takes_value(true)
.value_name("LIMIT")
.default_value(DEFAULT_GENERATION_LIMIT)
.help("Garbage collector generation limit"),
)
.arg(
Arg::with_name("milestone_address")
.short("M")
.long("milestone-address")
.takes_value(true)
.value_name("ADDRESS")
.default_value(DEFAULT_MILESTONE_ADDRESS)
.help("Milestone address"),
)
.arg(
Arg::with_name("milestone_start_index")
.short("I")
.long("milestone-start-index")
.takes_value(true)
.value_name("INDEX")
.default_value(DEFAULT_MILESTONE_START_INDEX)
.help("Milestone start index"),
)
.arg(
Arg::with_name("log_config")
.short("C")
.long("log-config")
.takes_value(true)
.value_name("FILE")
.default_value(DEFAULT_LOG_CONFIG)
.help("Path to log4rs configuration file"),
)
}
| {
app_from_crate!()
.arg(
Arg::with_name("zmq_uri")
.short("z")
.long("zmq")
.takes_value(true)
.value_name("URI")
.required(true)
.help("ZMQ source server URI"),
)
.arg(
Arg::with_name("mysql_uri")
.short("m")
.long("mysql")
.takes_value(true)
.value_name("URI")
.required(true)
.help("MySQL destination server URI"),
) | identifier_body |
app.rs | use clap::{App, Arg};
const DEFAULT_RETRY_INTERVAL: &str = "1000";
const DEFAULT_UPDATE_INTERVAL: &str = "1000";
const DEFAULT_CALCULATION_THREADS: &str = "1";
const DEFAULT_CALCULATION_LIMIT: &str = "1000";
const DEFAULT_GENERATION_LIMIT: &str = "10";
const DEFAULT_MILESTONE_ADDRESS: &str =
"KPWCHICGJZXKE9GSUDXZYUAPLHAKAHYHDXNPHENTE\
RYMMBQOPSQIDENXKLKCEYCPVTZQLEEJVYJZV9BWU";
const DEFAULT_MILESTONE_START_INDEX: &str = "62000";
const DEFAULT_LOG_CONFIG: &str = "log4rs.yaml";
pub fn | <'a, 'b>() -> App<'a, 'b> {
app_from_crate!()
.arg(
Arg::with_name("zmq_uri")
.short("z")
.long("zmq")
.takes_value(true)
.value_name("URI")
.required(true)
.help("ZMQ source server URI"),
)
.arg(
Arg::with_name("mysql_uri")
.short("m")
.long("mysql")
.takes_value(true)
.value_name("URI")
.required(true)
.help("MySQL destination server URI"),
)
.arg(
Arg::with_name("retry_interval")
.short("r")
.long("retry-interval")
.takes_value(true)
.value_name("INTERVAL")
.default_value(DEFAULT_RETRY_INTERVAL)
.help("MySQL connect retry interval in milliseconds"),
)
.arg(
Arg::with_name("update_interval")
.short("u")
.long("update-interval")
.takes_value(true)
.value_name("INTERVAL")
.default_value(DEFAULT_UPDATE_INTERVAL)
.help("MySQL update interval in milliseconds"),
)
.arg(
Arg::with_name("calculation_threads")
.short("T")
.long("calculation-threads")
.takes_value(true)
.value_name("THREADS")
.default_value(DEFAULT_CALCULATION_THREADS)
.help("Number of calculation threads"),
)
.arg(
Arg::with_name("calculation_limit")
.short("t")
.long("calculation-limit")
.takes_value(true)
.value_name("LIMIT")
.default_value(DEFAULT_CALCULATION_LIMIT)
.help("Calculation depth limit"),
)
.arg(
Arg::with_name("generation_limit")
.short("g")
.long("generation-limit")
.takes_value(true)
.value_name("LIMIT")
.default_value(DEFAULT_GENERATION_LIMIT)
.help("Garbage collector generation limit"),
)
.arg(
Arg::with_name("milestone_address")
.short("M")
.long("milestone-address")
.takes_value(true)
.value_name("ADDRESS")
.default_value(DEFAULT_MILESTONE_ADDRESS)
.help("Milestone address"),
)
.arg(
Arg::with_name("milestone_start_index")
.short("I")
.long("milestone-start-index")
.takes_value(true)
.value_name("INDEX")
.default_value(DEFAULT_MILESTONE_START_INDEX)
.help("Milestone start index"),
)
.arg(
Arg::with_name("log_config")
.short("C")
.long("log-config")
.takes_value(true)
.value_name("FILE")
.default_value(DEFAULT_LOG_CONFIG)
.help("Path to log4rs configuration file"),
)
}
| build | identifier_name |
app.rs | use clap::{App, Arg};
const DEFAULT_RETRY_INTERVAL: &str = "1000";
const DEFAULT_UPDATE_INTERVAL: &str = "1000";
const DEFAULT_CALCULATION_THREADS: &str = "1";
const DEFAULT_CALCULATION_LIMIT: &str = "1000";
const DEFAULT_GENERATION_LIMIT: &str = "10";
const DEFAULT_MILESTONE_ADDRESS: &str =
"KPWCHICGJZXKE9GSUDXZYUAPLHAKAHYHDXNPHENTE\
RYMMBQOPSQIDENXKLKCEYCPVTZQLEEJVYJZV9BWU";
const DEFAULT_MILESTONE_START_INDEX: &str = "62000";
const DEFAULT_LOG_CONFIG: &str = "log4rs.yaml";
pub fn build<'a, 'b>() -> App<'a, 'b> {
app_from_crate!()
.arg(
Arg::with_name("zmq_uri")
.short("z")
.long("zmq")
.takes_value(true) | .help("ZMQ source server URI"),
)
.arg(
Arg::with_name("mysql_uri")
.short("m")
.long("mysql")
.takes_value(true)
.value_name("URI")
.required(true)
.help("MySQL destination server URI"),
)
.arg(
Arg::with_name("retry_interval")
.short("r")
.long("retry-interval")
.takes_value(true)
.value_name("INTERVAL")
.default_value(DEFAULT_RETRY_INTERVAL)
.help("MySQL connect retry interval in milliseconds"),
)
.arg(
Arg::with_name("update_interval")
.short("u")
.long("update-interval")
.takes_value(true)
.value_name("INTERVAL")
.default_value(DEFAULT_UPDATE_INTERVAL)
.help("MySQL update interval in milliseconds"),
)
.arg(
Arg::with_name("calculation_threads")
.short("T")
.long("calculation-threads")
.takes_value(true)
.value_name("THREADS")
.default_value(DEFAULT_CALCULATION_THREADS)
.help("Number of calculation threads"),
)
.arg(
Arg::with_name("calculation_limit")
.short("t")
.long("calculation-limit")
.takes_value(true)
.value_name("LIMIT")
.default_value(DEFAULT_CALCULATION_LIMIT)
.help("Calculation depth limit"),
)
.arg(
Arg::with_name("generation_limit")
.short("g")
.long("generation-limit")
.takes_value(true)
.value_name("LIMIT")
.default_value(DEFAULT_GENERATION_LIMIT)
.help("Garbage collector generation limit"),
)
.arg(
Arg::with_name("milestone_address")
.short("M")
.long("milestone-address")
.takes_value(true)
.value_name("ADDRESS")
.default_value(DEFAULT_MILESTONE_ADDRESS)
.help("Milestone address"),
)
.arg(
Arg::with_name("milestone_start_index")
.short("I")
.long("milestone-start-index")
.takes_value(true)
.value_name("INDEX")
.default_value(DEFAULT_MILESTONE_START_INDEX)
.help("Milestone start index"),
)
.arg(
Arg::with_name("log_config")
.short("C")
.long("log-config")
.takes_value(true)
.value_name("FILE")
.default_value(DEFAULT_LOG_CONFIG)
.help("Path to log4rs configuration file"),
)
} | .value_name("URI")
.required(true) | random_line_split |
stdio.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.
#[cfg(stage0)]
use prelude::v1::*;
use io;
use libc;
use sys::fd::FileDesc;
pub struct Stdin(());
pub struct Stdout(());
pub struct Stderr(());
impl Stdin {
pub fn new() -> io::Result<Stdin> { Ok(Stdin(())) }
pub fn read(&self, data: &mut [u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDIN_FILENO);
let ret = fd.read(data);
fd.into_raw();
return ret;
}
}
impl Stdout {
pub fn new() -> io::Result<Stdout> |
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDOUT_FILENO);
let ret = fd.write(data);
fd.into_raw();
return ret;
}
}
impl Stderr {
pub fn new() -> io::Result<Stderr> { Ok(Stderr(())) }
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDERR_FILENO);
let ret = fd.write(data);
fd.into_raw();
return ret;
}
}
// FIXME: right now this raw stderr handle is used in a few places because
// std::io::stderr_raw isn't exposed, but once that's exposed this impl
// should go away
impl io::Write for Stderr {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
Stderr::write(self, data)
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
| { Ok(Stdout(())) } | identifier_body |
stdio.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.
#[cfg(stage0)]
use prelude::v1::*;
use io;
use libc;
use sys::fd::FileDesc;
pub struct Stdin(());
pub struct Stdout(());
pub struct | (());
impl Stdin {
pub fn new() -> io::Result<Stdin> { Ok(Stdin(())) }
pub fn read(&self, data: &mut [u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDIN_FILENO);
let ret = fd.read(data);
fd.into_raw();
return ret;
}
}
impl Stdout {
pub fn new() -> io::Result<Stdout> { Ok(Stdout(())) }
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDOUT_FILENO);
let ret = fd.write(data);
fd.into_raw();
return ret;
}
}
impl Stderr {
pub fn new() -> io::Result<Stderr> { Ok(Stderr(())) }
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDERR_FILENO);
let ret = fd.write(data);
fd.into_raw();
return ret;
}
}
// FIXME: right now this raw stderr handle is used in a few places because
// std::io::stderr_raw isn't exposed, but once that's exposed this impl
// should go away
impl io::Write for Stderr {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
Stderr::write(self, data)
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
| Stderr | identifier_name |
stdio.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. | // except according to those terms.
#[cfg(stage0)]
use prelude::v1::*;
use io;
use libc;
use sys::fd::FileDesc;
pub struct Stdin(());
pub struct Stdout(());
pub struct Stderr(());
impl Stdin {
pub fn new() -> io::Result<Stdin> { Ok(Stdin(())) }
pub fn read(&self, data: &mut [u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDIN_FILENO);
let ret = fd.read(data);
fd.into_raw();
return ret;
}
}
impl Stdout {
pub fn new() -> io::Result<Stdout> { Ok(Stdout(())) }
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDOUT_FILENO);
let ret = fd.write(data);
fd.into_raw();
return ret;
}
}
impl Stderr {
pub fn new() -> io::Result<Stderr> { Ok(Stderr(())) }
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
let fd = FileDesc::new(libc::STDERR_FILENO);
let ret = fd.write(data);
fd.into_raw();
return ret;
}
}
// FIXME: right now this raw stderr handle is used in a few places because
// std::io::stderr_raw isn't exposed, but once that's exposed this impl
// should go away
impl io::Write for Stderr {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
Stderr::write(self, data)
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
} | //
// 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 | random_line_split |
cttz32.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::cttz32;
// pub fn cttz32(x: u32) -> u32;
macro_rules! cttz32_test {
($value:expr, $BITS:expr) => ({
let x: u32 = $value;
let result: u32 = unsafe { cttz32(x) };
assert_eq!(result, $BITS);
})
}
#[test]
fn cttz32_test1() | cttz32_test!(0x00080000, 19);
cttz32_test!(0x00100000, 20);
cttz32_test!(0x00200000, 21);
cttz32_test!(0x00400000, 22);
cttz32_test!(0x00800000, 23);
cttz32_test!(0x01000000, 24);
cttz32_test!(0x02000000, 25);
cttz32_test!(0x04000000, 26);
cttz32_test!(0x08000000, 27);
cttz32_test!(0x10000000, 28);
cttz32_test!(0x20000000, 29);
cttz32_test!(0x40000000, 30);
cttz32_test!(0x80000000, 31);
}
}
| {
cttz32_test!(0x00000001, 0);
cttz32_test!(0x00000002, 1);
cttz32_test!(0x00000004, 2);
cttz32_test!(0x00000008, 3);
cttz32_test!(0x00000010, 4);
cttz32_test!(0x00000020, 5);
cttz32_test!(0x00000040, 6);
cttz32_test!(0x00000080, 7);
cttz32_test!(0x00000100, 8);
cttz32_test!(0x00000200, 9);
cttz32_test!(0x00000400, 10);
cttz32_test!(0x00000800, 11);
cttz32_test!(0x00001000, 12);
cttz32_test!(0x00002000, 13);
cttz32_test!(0x00004000, 14);
cttz32_test!(0x00008000, 15);
cttz32_test!(0x00010000, 16);
cttz32_test!(0x00020000, 17);
cttz32_test!(0x00040000, 18); | identifier_body |
cttz32.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::cttz32;
// pub fn cttz32(x: u32) -> u32;
macro_rules! cttz32_test {
($value:expr, $BITS:expr) => ({
let x: u32 = $value;
let result: u32 = unsafe { cttz32(x) };
assert_eq!(result, $BITS);
})
}
#[test]
fn | () {
cttz32_test!(0x00000001, 0);
cttz32_test!(0x00000002, 1);
cttz32_test!(0x00000004, 2);
cttz32_test!(0x00000008, 3);
cttz32_test!(0x00000010, 4);
cttz32_test!(0x00000020, 5);
cttz32_test!(0x00000040, 6);
cttz32_test!(0x00000080, 7);
cttz32_test!(0x00000100, 8);
cttz32_test!(0x00000200, 9);
cttz32_test!(0x00000400, 10);
cttz32_test!(0x00000800, 11);
cttz32_test!(0x00001000, 12);
cttz32_test!(0x00002000, 13);
cttz32_test!(0x00004000, 14);
cttz32_test!(0x00008000, 15);
cttz32_test!(0x00010000, 16);
cttz32_test!(0x00020000, 17);
cttz32_test!(0x00040000, 18);
cttz32_test!(0x00080000, 19);
cttz32_test!(0x00100000, 20);
cttz32_test!(0x00200000, 21);
cttz32_test!(0x00400000, 22);
cttz32_test!(0x00800000, 23);
cttz32_test!(0x01000000, 24);
cttz32_test!(0x02000000, 25);
cttz32_test!(0x04000000, 26);
cttz32_test!(0x08000000, 27);
cttz32_test!(0x10000000, 28);
cttz32_test!(0x20000000, 29);
cttz32_test!(0x40000000, 30);
cttz32_test!(0x80000000, 31);
}
}
| cttz32_test1 | identifier_name |
cttz32.rs | #![feature(core, core_intrinsics)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::cttz32;
// pub fn cttz32(x: u32) -> u32;
macro_rules! cttz32_test {
($value:expr, $BITS:expr) => ({
let x: u32 = $value;
let result: u32 = unsafe { cttz32(x) };
assert_eq!(result, $BITS);
})
}
#[test]
fn cttz32_test1() {
cttz32_test!(0x00000001, 0);
cttz32_test!(0x00000002, 1);
cttz32_test!(0x00000004, 2);
cttz32_test!(0x00000008, 3); | cttz32_test!(0x00000080, 7);
cttz32_test!(0x00000100, 8);
cttz32_test!(0x00000200, 9);
cttz32_test!(0x00000400, 10);
cttz32_test!(0x00000800, 11);
cttz32_test!(0x00001000, 12);
cttz32_test!(0x00002000, 13);
cttz32_test!(0x00004000, 14);
cttz32_test!(0x00008000, 15);
cttz32_test!(0x00010000, 16);
cttz32_test!(0x00020000, 17);
cttz32_test!(0x00040000, 18);
cttz32_test!(0x00080000, 19);
cttz32_test!(0x00100000, 20);
cttz32_test!(0x00200000, 21);
cttz32_test!(0x00400000, 22);
cttz32_test!(0x00800000, 23);
cttz32_test!(0x01000000, 24);
cttz32_test!(0x02000000, 25);
cttz32_test!(0x04000000, 26);
cttz32_test!(0x08000000, 27);
cttz32_test!(0x10000000, 28);
cttz32_test!(0x20000000, 29);
cttz32_test!(0x40000000, 30);
cttz32_test!(0x80000000, 31);
}
} | cttz32_test!(0x00000010, 4);
cttz32_test!(0x00000020, 5);
cttz32_test!(0x00000040, 6); | random_line_split |
raw.rs | extern crate libsqlite3_sys as ffi;
extern crate libc;
use std::ffi::{CString, CStr};
use std::io::{stderr, Write};
use std::{ptr, str};
use result::*;
use result::Error::DatabaseError;
#[allow(missing_debug_implementations, missing_copy_implementations)]
pub struct RawConnection {
pub internal_connection: *mut ffi::sqlite3,
}
impl RawConnection {
pub fn establish(database_url: &str) -> ConnectionResult<Self> {
let mut conn_pointer = ptr::null_mut();
let database_url = try!(CString::new(database_url));
let connection_status = unsafe {
ffi::sqlite3_open(database_url.as_ptr(), &mut conn_pointer)
};
match connection_status {
ffi::SQLITE_OK => Ok(RawConnection {
internal_connection: conn_pointer,
}),
err_code => {
let message = super::error_message(err_code);
Err(ConnectionError::BadConnection(message.into()))
}
}
}
pub fn exec(&self, query: &str) -> QueryResult<()> {
let mut err_msg = ptr::null_mut();
let query = try!(CString::new(query));
let callback_fn = None;
let callback_arg = ptr::null_mut();
unsafe {
ffi::sqlite3_exec(
self.internal_connection,
query.as_ptr(),
callback_fn,
callback_arg,
&mut err_msg,
);
}
if!err_msg.is_null() {
let msg = convert_to_string_and_free(err_msg);
let error_kind = DatabaseErrorKind::__Unknown;
Err(DatabaseError(error_kind, Box::new(msg)))
} else {
Ok(())
}
}
pub fn rows_affected_by_last_query(&self) -> usize {
unsafe { ffi::sqlite3_changes(self.internal_connection) as usize }
}
pub fn last_error_message(&self) -> String {
let c_str = unsafe { CStr::from_ptr(ffi::sqlite3_errmsg(self.internal_connection)) };
c_str.to_string_lossy().into_owned()
}
pub fn last_error_code(&self) -> libc::c_int {
unsafe { ffi::sqlite3_extended_errcode(self.internal_connection) }
}
}
impl Drop for RawConnection {
fn drop(&mut self) {
use std::thread::panicking;
let close_result = unsafe { ffi::sqlite3_close(self.internal_connection) };
if close_result!= ffi::SQLITE_OK {
let error_message = super::error_message(close_result);
if panicking() {
write!(stderr(), "Error closing SQLite connection: {}", error_message).unwrap();
} else {
panic!("Error closing SQLite connection: {}", error_message);
}
}
}
}
fn | (err_msg: *const libc::c_char) -> String {
let msg = unsafe {
let bytes = CStr::from_ptr(err_msg).to_bytes();
str::from_utf8_unchecked(bytes).into()
};
unsafe { ffi::sqlite3_free(err_msg as *mut libc::c_void) };
msg
}
| convert_to_string_and_free | identifier_name |
raw.rs | extern crate libsqlite3_sys as ffi;
extern crate libc;
use std::ffi::{CString, CStr};
use std::io::{stderr, Write};
use std::{ptr, str};
use result::*;
use result::Error::DatabaseError;
#[allow(missing_debug_implementations, missing_copy_implementations)]
pub struct RawConnection {
pub internal_connection: *mut ffi::sqlite3,
}
impl RawConnection {
pub fn establish(database_url: &str) -> ConnectionResult<Self> {
let mut conn_pointer = ptr::null_mut();
let database_url = try!(CString::new(database_url));
let connection_status = unsafe {
ffi::sqlite3_open(database_url.as_ptr(), &mut conn_pointer)
};
match connection_status {
ffi::SQLITE_OK => Ok(RawConnection {
internal_connection: conn_pointer,
}),
err_code => {
let message = super::error_message(err_code);
Err(ConnectionError::BadConnection(message.into()))
}
}
}
pub fn exec(&self, query: &str) -> QueryResult<()> {
let mut err_msg = ptr::null_mut();
let query = try!(CString::new(query));
let callback_fn = None;
let callback_arg = ptr::null_mut();
unsafe {
ffi::sqlite3_exec(
self.internal_connection,
query.as_ptr(),
callback_fn,
callback_arg,
&mut err_msg,
);
}
if!err_msg.is_null() | else {
Ok(())
}
}
pub fn rows_affected_by_last_query(&self) -> usize {
unsafe { ffi::sqlite3_changes(self.internal_connection) as usize }
}
pub fn last_error_message(&self) -> String {
let c_str = unsafe { CStr::from_ptr(ffi::sqlite3_errmsg(self.internal_connection)) };
c_str.to_string_lossy().into_owned()
}
pub fn last_error_code(&self) -> libc::c_int {
unsafe { ffi::sqlite3_extended_errcode(self.internal_connection) }
}
}
impl Drop for RawConnection {
fn drop(&mut self) {
use std::thread::panicking;
let close_result = unsafe { ffi::sqlite3_close(self.internal_connection) };
if close_result!= ffi::SQLITE_OK {
let error_message = super::error_message(close_result);
if panicking() {
write!(stderr(), "Error closing SQLite connection: {}", error_message).unwrap();
} else {
panic!("Error closing SQLite connection: {}", error_message);
}
}
}
}
fn convert_to_string_and_free(err_msg: *const libc::c_char) -> String {
let msg = unsafe {
let bytes = CStr::from_ptr(err_msg).to_bytes();
str::from_utf8_unchecked(bytes).into()
};
unsafe { ffi::sqlite3_free(err_msg as *mut libc::c_void) };
msg
}
| {
let msg = convert_to_string_and_free(err_msg);
let error_kind = DatabaseErrorKind::__Unknown;
Err(DatabaseError(error_kind, Box::new(msg)))
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.