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 |
---|---|---|---|---|
scheduler.rs | use std::io;
use std::io::prelude::*;
use std::collections::{HashSet, HashMap};
use std::str::FromStr;
use time;
use regex::Regex;
use error::Error;
use error::Error::ErrCronFormat;
pub type SchedulerResult<'a> = Result<Scheduler<'a>, Error>;
#[derive(Debug)]
pub struct Scheduler<'a> {
seconds: &'a str,
minutes: &'a str,
hours: &'a str,
days: &'a str,
months: &'a str,
weekdays: &'a str,
timeFiledsLength: usize,
timePoints: HashMap<&'a str, HashSet<u32>>,
re: Regex,
}
impl<'a> Scheduler<'a> {
pub fn new(intervals: &'a str) -> SchedulerResult {
let reRes = Regex::new(r"^\s*((\*(/\d+)?)|[0-9-,/]+)(\s+((\*(/\d+)?)|[0-9-,/]+)){4,5}\s*$");
match reRes {
Ok(re) => {
if!re.is_match(intervals) {
return Err(ErrCronFormat(format!("invalid format: {}", intervals)));
}
let timeFileds: Vec<&str> = intervals.split_whitespace().collect();
let timeFiledsLength = timeFileds.len();
if timeFiledsLength!= 5 && timeFiledsLength!= 6 {
return Err(ErrCronFormat(format!("length of itervals should be 5 or 6, \
but got {}",
timeFiledsLength)));
}
let mut sec = "";
let mut startIndex: usize = 0;
if timeFiledsLength == 6 {
sec = timeFileds[0].clone();
startIndex = 1;
}
let mut sch = Scheduler {
seconds: sec,
minutes: timeFileds[startIndex],
hours: timeFileds[startIndex + 1],
days: timeFileds[startIndex + 2],
months: timeFileds[startIndex + 3],
weekdays: timeFileds[startIndex + 4],
timeFiledsLength: timeFiledsLength,
timePoints: HashMap::new(),
re: re,
};
try!(sch.parse_time_fields().map_err(|e| ErrCronFormat(e.to_string())));
Ok(sch)
}
Err(e) => Err(ErrCronFormat(e.to_string())),
}
}
pub fn parse_time_fields(&mut self) -> Result<(), Error> {
if self.seconds!= "" {
self.timePoints.insert("seconds", try!(parse_intervals_field(self.seconds, 0, 59)));
} else {
self.timePoints.insert("seconds", [0].iter().cloned().collect::<HashSet<u32>>());
}
self.timePoints.insert("minutes", try!(parse_intervals_field(self.minutes, 0, 59)));
self.timePoints.insert("hours", try!(parse_intervals_field(self.hours, 0, 23)));
self.timePoints.insert("days", try!(parse_intervals_field(self.days, 1, 31)));
self.timePoints.insert("months", try!(parse_intervals_field(self.months, 1, 12)));
self.timePoints.insert("weekdays", try!(parse_intervals_field(self.weekdays, 0, 6)));
Ok(())
}
pub fn is_time_up(&self, t: &time::Tm) -> bool | }
}
fn parse_intervals_field(inter: &str, min: u32, max: u32) -> Result<HashSet<u32>, Error> {
let mut points = HashSet::new();
let parts: Vec<&str> = inter.split(",").collect();
for part in parts {
let x: Vec<&str> = part.split("/").collect();
let y: Vec<&str> = x[0].split("-").collect();
let mut _min = min;
let mut _max = max;
let mut step = 1u32;
let (xLen, yLen) = (x.len(), y.len());
if xLen == 1 && yLen == 1 {
if y[0]!= "*" {
_min = try!(y[0].parse::<u32>());
_max = _min;
}
} else if xLen == 1 && yLen == 2 {
_min = try!(y[0].parse::<u32>());
_max = try!(y[1].parse::<u32>());
} else if xLen == 2 && yLen == 1 && x[0] == "*" {
step = try!(x[1].parse::<u32>());
} else {
return Err(ErrCronFormat(String::from(part)));
}
for i in (_min.._max + 1).filter(|x| x % step == 0).collect::<Vec<u32>>() {
points.insert(i);
}
}
Ok(points)
}
#[test]
fn test_parse_intervals() {
assert!(Scheduler::new("*/2 1-8,11 * * *").is_ok());
assert!(Scheduler::new("0 */2 1-8,11 * * *").is_ok());
assert!(Scheduler::new("*/2 1-4,16,11,17 * * *").is_ok());
assert!(Scheduler::new("05 */2 1-8,11 * * * *").is_err());
assert!(Scheduler::new("05 */ 1-8,11 * * *").is_err());
}
| {
let (second, minute, hour, day, month, weekday) = (t.tm_sec as u32,
t.tm_min as u32,
t.tm_hour as u32,
t.tm_mday as u32,
t.tm_mon as u32,
t.tm_wday as u32);
let isSecond = self.timePoints.get("seconds").unwrap().contains(&second);
let isLeft = self.timePoints.get("minutes").unwrap().contains(&minute) &&
self.timePoints.get("hours").unwrap().contains(&hour) &&
self.timePoints.get("days").unwrap().contains(&day) &&
self.timePoints.get("months").unwrap().contains(&month) &&
self.timePoints.get("weekdays").unwrap().contains(&weekday);
if self.timeFiledsLength == 5 {
isLeft
} else {
isSecond && isLeft
} | identifier_body |
scheduler.rs | use std::io;
use std::io::prelude::*;
use std::collections::{HashSet, HashMap};
use std::str::FromStr;
use time;
use regex::Regex;
use error::Error;
use error::Error::ErrCronFormat;
pub type SchedulerResult<'a> = Result<Scheduler<'a>, Error>;
#[derive(Debug)]
pub struct Scheduler<'a> {
seconds: &'a str,
minutes: &'a str,
hours: &'a str,
days: &'a str,
months: &'a str,
weekdays: &'a str,
timeFiledsLength: usize,
timePoints: HashMap<&'a str, HashSet<u32>>,
re: Regex,
}
impl<'a> Scheduler<'a> {
pub fn | (intervals: &'a str) -> SchedulerResult {
let reRes = Regex::new(r"^\s*((\*(/\d+)?)|[0-9-,/]+)(\s+((\*(/\d+)?)|[0-9-,/]+)){4,5}\s*$");
match reRes {
Ok(re) => {
if!re.is_match(intervals) {
return Err(ErrCronFormat(format!("invalid format: {}", intervals)));
}
let timeFileds: Vec<&str> = intervals.split_whitespace().collect();
let timeFiledsLength = timeFileds.len();
if timeFiledsLength!= 5 && timeFiledsLength!= 6 {
return Err(ErrCronFormat(format!("length of itervals should be 5 or 6, \
but got {}",
timeFiledsLength)));
}
let mut sec = "";
let mut startIndex: usize = 0;
if timeFiledsLength == 6 {
sec = timeFileds[0].clone();
startIndex = 1;
}
let mut sch = Scheduler {
seconds: sec,
minutes: timeFileds[startIndex],
hours: timeFileds[startIndex + 1],
days: timeFileds[startIndex + 2],
months: timeFileds[startIndex + 3],
weekdays: timeFileds[startIndex + 4],
timeFiledsLength: timeFiledsLength,
timePoints: HashMap::new(),
re: re,
};
try!(sch.parse_time_fields().map_err(|e| ErrCronFormat(e.to_string())));
Ok(sch)
}
Err(e) => Err(ErrCronFormat(e.to_string())),
}
}
pub fn parse_time_fields(&mut self) -> Result<(), Error> {
if self.seconds!= "" {
self.timePoints.insert("seconds", try!(parse_intervals_field(self.seconds, 0, 59)));
} else {
self.timePoints.insert("seconds", [0].iter().cloned().collect::<HashSet<u32>>());
}
self.timePoints.insert("minutes", try!(parse_intervals_field(self.minutes, 0, 59)));
self.timePoints.insert("hours", try!(parse_intervals_field(self.hours, 0, 23)));
self.timePoints.insert("days", try!(parse_intervals_field(self.days, 1, 31)));
self.timePoints.insert("months", try!(parse_intervals_field(self.months, 1, 12)));
self.timePoints.insert("weekdays", try!(parse_intervals_field(self.weekdays, 0, 6)));
Ok(())
}
pub fn is_time_up(&self, t: &time::Tm) -> bool {
let (second, minute, hour, day, month, weekday) = (t.tm_sec as u32,
t.tm_min as u32,
t.tm_hour as u32,
t.tm_mday as u32,
t.tm_mon as u32,
t.tm_wday as u32);
let isSecond = self.timePoints.get("seconds").unwrap().contains(&second);
let isLeft = self.timePoints.get("minutes").unwrap().contains(&minute) &&
self.timePoints.get("hours").unwrap().contains(&hour) &&
self.timePoints.get("days").unwrap().contains(&day) &&
self.timePoints.get("months").unwrap().contains(&month) &&
self.timePoints.get("weekdays").unwrap().contains(&weekday);
if self.timeFiledsLength == 5 {
isLeft
} else {
isSecond && isLeft
}
}
}
fn parse_intervals_field(inter: &str, min: u32, max: u32) -> Result<HashSet<u32>, Error> {
let mut points = HashSet::new();
let parts: Vec<&str> = inter.split(",").collect();
for part in parts {
let x: Vec<&str> = part.split("/").collect();
let y: Vec<&str> = x[0].split("-").collect();
let mut _min = min;
let mut _max = max;
let mut step = 1u32;
let (xLen, yLen) = (x.len(), y.len());
if xLen == 1 && yLen == 1 {
if y[0]!= "*" {
_min = try!(y[0].parse::<u32>());
_max = _min;
}
} else if xLen == 1 && yLen == 2 {
_min = try!(y[0].parse::<u32>());
_max = try!(y[1].parse::<u32>());
} else if xLen == 2 && yLen == 1 && x[0] == "*" {
step = try!(x[1].parse::<u32>());
} else {
return Err(ErrCronFormat(String::from(part)));
}
for i in (_min.._max + 1).filter(|x| x % step == 0).collect::<Vec<u32>>() {
points.insert(i);
}
}
Ok(points)
}
#[test]
fn test_parse_intervals() {
assert!(Scheduler::new("*/2 1-8,11 * * *").is_ok());
assert!(Scheduler::new("0 */2 1-8,11 * * *").is_ok());
assert!(Scheduler::new("*/2 1-4,16,11,17 * * *").is_ok());
assert!(Scheduler::new("05 */2 1-8,11 * * * *").is_err());
assert!(Scheduler::new("05 */ 1-8,11 * * *").is_err());
}
| new | identifier_name |
scheduler.rs | use std::io;
use std::io::prelude::*;
use std::collections::{HashSet, HashMap};
use std::str::FromStr;
use time;
use regex::Regex;
use error::Error;
use error::Error::ErrCronFormat;
pub type SchedulerResult<'a> = Result<Scheduler<'a>, Error>;
#[derive(Debug)]
pub struct Scheduler<'a> {
seconds: &'a str,
minutes: &'a str,
hours: &'a str,
days: &'a str,
months: &'a str,
weekdays: &'a str,
timeFiledsLength: usize,
timePoints: HashMap<&'a str, HashSet<u32>>,
re: Regex,
}
impl<'a> Scheduler<'a> {
pub fn new(intervals: &'a str) -> SchedulerResult {
let reRes = Regex::new(r"^\s*((\*(/\d+)?)|[0-9-,/]+)(\s+((\*(/\d+)?)|[0-9-,/]+)){4,5}\s*$");
match reRes {
Ok(re) => {
if!re.is_match(intervals) {
return Err(ErrCronFormat(format!("invalid format: {}", intervals)));
}
let timeFileds: Vec<&str> = intervals.split_whitespace().collect();
let timeFiledsLength = timeFileds.len();
if timeFiledsLength!= 5 && timeFiledsLength!= 6 {
return Err(ErrCronFormat(format!("length of itervals should be 5 or 6, \
but got {}",
timeFiledsLength)));
}
let mut sec = "";
let mut startIndex: usize = 0;
if timeFiledsLength == 6 {
sec = timeFileds[0].clone();
startIndex = 1;
}
let mut sch = Scheduler {
seconds: sec,
minutes: timeFileds[startIndex],
hours: timeFileds[startIndex + 1],
days: timeFileds[startIndex + 2],
months: timeFileds[startIndex + 3],
weekdays: timeFileds[startIndex + 4],
timeFiledsLength: timeFiledsLength,
timePoints: HashMap::new(),
re: re,
};
try!(sch.parse_time_fields().map_err(|e| ErrCronFormat(e.to_string())));
Ok(sch)
}
Err(e) => Err(ErrCronFormat(e.to_string())),
}
}
pub fn parse_time_fields(&mut self) -> Result<(), Error> {
if self.seconds!= "" {
self.timePoints.insert("seconds", try!(parse_intervals_field(self.seconds, 0, 59)));
} else {
self.timePoints.insert("seconds", [0].iter().cloned().collect::<HashSet<u32>>());
}
self.timePoints.insert("minutes", try!(parse_intervals_field(self.minutes, 0, 59)));
self.timePoints.insert("hours", try!(parse_intervals_field(self.hours, 0, 23)));
self.timePoints.insert("days", try!(parse_intervals_field(self.days, 1, 31)));
self.timePoints.insert("months", try!(parse_intervals_field(self.months, 1, 12)));
self.timePoints.insert("weekdays", try!(parse_intervals_field(self.weekdays, 0, 6)));
Ok(())
}
pub fn is_time_up(&self, t: &time::Tm) -> bool {
let (second, minute, hour, day, month, weekday) = (t.tm_sec as u32,
t.tm_min as u32,
t.tm_hour as u32,
t.tm_mday as u32,
t.tm_mon as u32,
t.tm_wday as u32);
let isSecond = self.timePoints.get("seconds").unwrap().contains(&second);
let isLeft = self.timePoints.get("minutes").unwrap().contains(&minute) &&
self.timePoints.get("hours").unwrap().contains(&hour) &&
self.timePoints.get("days").unwrap().contains(&day) &&
self.timePoints.get("months").unwrap().contains(&month) &&
self.timePoints.get("weekdays").unwrap().contains(&weekday);
if self.timeFiledsLength == 5 {
isLeft
} else {
isSecond && isLeft
}
}
}
fn parse_intervals_field(inter: &str, min: u32, max: u32) -> Result<HashSet<u32>, Error> {
let mut points = HashSet::new();
let parts: Vec<&str> = inter.split(",").collect();
for part in parts {
let x: Vec<&str> = part.split("/").collect();
let y: Vec<&str> = x[0].split("-").collect();
let mut _min = min;
let mut _max = max;
let mut step = 1u32;
let (xLen, yLen) = (x.len(), y.len());
if xLen == 1 && yLen == 1 {
if y[0]!= "*" {
_min = try!(y[0].parse::<u32>());
_max = _min;
}
} else if xLen == 1 && yLen == 2 {
_min = try!(y[0].parse::<u32>());
_max = try!(y[1].parse::<u32>());
} else if xLen == 2 && yLen == 1 && x[0] == "*" {
step = try!(x[1].parse::<u32>());
} else {
return Err(ErrCronFormat(String::from(part)));
}
for i in (_min.._max + 1).filter(|x| x % step == 0).collect::<Vec<u32>>() {
points.insert(i);
}
} | }
#[test]
fn test_parse_intervals() {
assert!(Scheduler::new("*/2 1-8,11 * * *").is_ok());
assert!(Scheduler::new("0 */2 1-8,11 * * *").is_ok());
assert!(Scheduler::new("*/2 1-4,16,11,17 * * *").is_ok());
assert!(Scheduler::new("05 */2 1-8,11 * * * *").is_err());
assert!(Scheduler::new("05 */ 1-8,11 * * *").is_err());
} |
Ok(points) | random_line_split |
certificate.rs | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use crate::{
get_sha256,
report::{AttestationInfo, Report},
};
use anyhow::Context;
use log::info;
use openssl::{
asn1::Asn1Time,
bn::{BigNum, MsbOption},
hash::MessageDigest,
pkey::{HasPublic, PKey, PKeyRef, Private},
rsa::Rsa,
stack::Stack,
x509::{
extension::{
AuthorityKeyIdentifier, BasicConstraints, KeyUsage, SubjectAlternativeName,
SubjectKeyIdentifier,
},
X509Builder, X509NameBuilder, X509Ref, X509Req, X509,
},
};
// X.509 certificate parameters.
//
// <https://tools.ietf.org/html/rfc5280>
const RSA_KEY_SIZE: u32 = 2048;
// Version is zero-indexed, so the value of `2` corresponds to the version `3`.
const CERTIFICATE_VERSION: i32 = 2;
// Length of the randomly generated X.509 certificate serial number (which is 20 bytes).
//
// The most significant bit is excluded because it's passed as a separate argument to:
// https://docs.rs/openssl/0.10.33/openssl/bn/struct.BigNum.html#method.rand
const SERIAL_NUMBER_SIZE: i32 = 159;
const CERTIFICATE_EXPIRATION_INTERVAL_IN_DAYS: u32 = 1;
const DEFAULT_DNS_NAME: &str = "localhost";
/// Indicates whether to add a custom TEE extension to a certificate.
#[derive(PartialEq)]
pub enum AddTeeExtension {
/// Enum value contains a PEM encoded TEE Provider's X.509 certificate that signs TEE firmware
/// key.
Yes(Vec<u8>),
No,
}
/// Convenience structure for generating X.509 certificates.
///
/// <https://tools.ietf.org/html/rfc5280>
pub struct CertificateAuthority {
pub key_pair: PKey<Private>,
pub root_certificate: X509,
}
impl CertificateAuthority {
/// Generates a root X.509 certificate and a corresponding private/public key pair.
///
/// `add_tee_extension` indicates whether to add a custom extension containing a TEE report to
/// the root certificate.
pub fn create(add_tee_extension: AddTeeExtension) -> anyhow::Result<Self> {
let key_pair = CertificateAuthority::generate_key_pair()?;
let root_certificate =
CertificateAuthority::generate_root_certificate(&key_pair, add_tee_extension)?;
Ok(Self {
key_pair,
root_certificate,
})
}
/// Generates RSA private/public key pair.
fn generate_key_pair() -> anyhow::Result<PKey<Private>> {
let rsa = Rsa::generate(RSA_KEY_SIZE).context("Couldn't generate RSA key")?;
PKey::from_rsa(rsa).context("Couldn't parse RSA key")
}
/// Creates a root X.509 certificate.
fn generate_root_certificate(
key_pair: &PKey<Private>,
add_tee_extension: AddTeeExtension,
) -> anyhow::Result<X509> {
info!("Generating root certificate");
let mut builder = CertificateBuilder::create()?;
builder.set_version(CERTIFICATE_VERSION)?;
builder.set_serial_number(SERIAL_NUMBER_SIZE)?;
builder.set_name()?;
builder.set_public_key(key_pair)?;
builder.set_expiration_interval(CERTIFICATE_EXPIRATION_INTERVAL_IN_DAYS)?;
builder.add_basic_constraints_extension(true)?;
builder.add_key_usage_extension(true)?;
builder.add_subject_key_identifier_extension(None)?;
builder.add_subject_alt_name_extension()?;
// Bind the certificate to the TEE firmware using an X.509 TEE extension.
if let AddTeeExtension::Yes(tee_certificate) = add_tee_extension {
builder.add_tee_extension(key_pair, tee_certificate)?;
}
let certificate = builder.build(key_pair)?;
Ok(certificate)
}
/// Generates an X.509 certificate based on the certificate signing `request`.
///
/// `add_tee_extension` indicates whether to add a custom extension containing a TEE report.
pub fn sign_certificate(
&self,
request: X509Req,
add_tee_extension: AddTeeExtension,
) -> anyhow::Result<X509> {
info!("Signing certificate");
let mut builder = CertificateBuilder::create()?;
builder.set_version(CERTIFICATE_VERSION)?;
builder.set_serial_number(SERIAL_NUMBER_SIZE)?;
builder.set_name()?;
builder.set_public_key(request.public_key()?.as_ref())?;
builder.set_expiration_interval(CERTIFICATE_EXPIRATION_INTERVAL_IN_DAYS)?;
builder.add_basic_constraints_extension(false)?;
builder.add_key_usage_extension(false)?;
builder.add_subject_key_identifier_extension(Some(&self.root_certificate))?;
builder.add_auth_key_identifier_extension(&self.root_certificate)?;
// Add X.509 extensions from the certificate signing request.
builder.add_extensions(request.extensions()?)?;
// Bind the certificate to the TEE firmware using an X.509 TEE extension.
if let AddTeeExtension::Yes(tee_certificate) = add_tee_extension {
builder.add_tee_extension(request.public_key()?.as_ref(), tee_certificate)?;
}
let certificate = builder.build(&self.key_pair)?;
Ok(certificate)
}
/// Get RSA key pair encoded in PEM format.
///
/// <https://tools.ietf.org/html/rfc7468>
pub fn get_private_key_pem(&self) -> anyhow::Result<Vec<u8>> {
self.key_pair
.private_key_to_pem_pkcs8()
.context("Couldn't encode key pair in PEM format")
}
/// Get a root X.509 certificate encoded in PEM format.
///
/// <https://tools.ietf.org/html/rfc7468>
pub fn get_root_certificate_pem(&self) -> anyhow::Result<Vec<u8>> {
self.root_certificate
.to_pem()
.context("Couldn't encode root certificate in PEM format")
}
}
/// Helper struct that implements certificate creation using `openssl`.
struct CertificateBuilder {
builder: X509Builder,
}
impl CertificateBuilder {
fn create() -> anyhow::Result<Self> {
let builder = X509::builder()?;
Ok(Self { builder })
}
fn set_version(&mut self, version: i32) -> anyhow::Result<&mut Self> {
self.builder.set_version(version)?;
Ok(self)
}
fn set_serial_number(&mut self, serial_number_size: i32) -> anyhow::Result<&mut Self> {
let serial_number = {
let mut serial = BigNum::new()?;
serial.rand(serial_number_size, MsbOption::MAYBE_ZERO, false)?;
serial.to_asn1_integer()?
};
self.builder.set_serial_number(&serial_number)?;
Ok(self)
}
fn set_name(&mut self) -> anyhow::Result<&mut Self> {
let mut name = X509NameBuilder::new()?;
name.append_entry_by_text("O", "Oak")?;
name.append_entry_by_text("CN", "Proxy Attestation Service")?;
let name = name.build();
self.builder.set_subject_name(&name)?;
self.builder.set_issuer_name(&name)?;
Ok(self)
}
fn set_public_key<T>(&mut self, public_key: &PKeyRef<T>) -> anyhow::Result<&mut Self>
where
T: HasPublic,
{
self.builder.set_pubkey(public_key)?;
Ok(self)
}
fn set_expiration_interval(&mut self, expiration_interval: u32) -> anyhow::Result<&mut Self> {
let not_before = Asn1Time::days_from_now(0)?;
self.builder.set_not_before(¬_before)?;
let not_after = Asn1Time::days_from_now(expiration_interval)?;
self.builder.set_not_after(¬_after)?;
Ok(self)
}
fn add_basic_constraints_extension(&mut self, is_critical: bool) -> anyhow::Result<&mut Self> {
if is_critical {
self.builder
.append_extension(BasicConstraints::new().critical().build()?)?;
} else {
self.builder
.append_extension(BasicConstraints::new().build()?)?;
}
Ok(self)
}
fn add_key_usage_extension(&mut self, is_root_certificate: bool) -> anyhow::Result<&mut Self> {
if is_root_certificate {
self.builder.append_extension(
KeyUsage::new()
.critical()
.key_cert_sign()
.crl_sign()
.build()?,
)?;
} else {
self.builder.append_extension(
KeyUsage::new()
.critical()
.non_repudiation()
.digital_signature()
.key_encipherment()
.build()?,
)?;
}
Ok(self)
}
fn add_subject_key_identifier_extension(
&mut self,
root_certificate: Option<&X509Ref>,
) -> anyhow::Result<&mut Self> {
let subject_key_identifier = SubjectKeyIdentifier::new()
.build(&self.builder.x509v3_context(root_certificate, None))?;
self.builder.append_extension(subject_key_identifier)?;
Ok(self)
}
fn add_subject_alt_name_extension(&mut self) -> anyhow::Result<&mut Self> {
let subject_alt_name = SubjectAlternativeName::new()
.dns(DEFAULT_DNS_NAME)
.build(&self.builder.x509v3_context(None, None))?;
self.builder.append_extension(subject_alt_name)?;
Ok(self)
}
fn add_auth_key_identifier_extension(
&mut self,
root_certificate: &X509Ref,
) -> anyhow::Result<&mut Self> {
let auth_key_identifier = AuthorityKeyIdentifier::new()
.keyid(false)
.issuer(false)
.build(&self.builder.x509v3_context(Some(root_certificate), None))?;
self.builder.append_extension(auth_key_identifier)?;
Ok(self)
}
// Generates a TEE report with the public key hash as data and add it to the certificate as a
// custom extension. This is required to bind the certificate to the TEE firmware.
fn | <T>(
&mut self,
public_key: &PKeyRef<T>,
tee_certificate: Vec<u8>,
) -> anyhow::Result<&mut Self>
where
T: HasPublic,
{
let public_key_hash = get_sha256(&public_key.public_key_to_der()?);
let tee_report = Report::new(&public_key_hash);
let attestation_info = AttestationInfo {
report: tee_report,
certificate: tee_certificate,
};
let tee_extension = attestation_info.to_extension()?;
self.builder.append_extension(tee_extension)?;
Ok(self)
}
fn add_extensions(
&mut self,
extensions: Stack<openssl::x509::X509Extension>,
) -> anyhow::Result<&mut Self> {
for extension in extensions.iter() {
self.builder.append_extension2(extension)?;
}
Ok(self)
}
fn build(mut self, private_key: &PKey<Private>) -> anyhow::Result<X509> {
self.builder.sign(private_key, MessageDigest::sha256())?;
Ok(self.builder.build())
}
}
| add_tee_extension | identifier_name |
certificate.rs | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use crate::{
get_sha256,
report::{AttestationInfo, Report},
};
use anyhow::Context;
use log::info;
use openssl::{
asn1::Asn1Time,
bn::{BigNum, MsbOption},
hash::MessageDigest,
pkey::{HasPublic, PKey, PKeyRef, Private},
rsa::Rsa,
stack::Stack,
x509::{
extension::{
AuthorityKeyIdentifier, BasicConstraints, KeyUsage, SubjectAlternativeName,
SubjectKeyIdentifier,
},
X509Builder, X509NameBuilder, X509Ref, X509Req, X509,
},
};
// X.509 certificate parameters.
//
// <https://tools.ietf.org/html/rfc5280>
const RSA_KEY_SIZE: u32 = 2048;
// Version is zero-indexed, so the value of `2` corresponds to the version `3`.
const CERTIFICATE_VERSION: i32 = 2;
// Length of the randomly generated X.509 certificate serial number (which is 20 bytes).
//
// The most significant bit is excluded because it's passed as a separate argument to:
// https://docs.rs/openssl/0.10.33/openssl/bn/struct.BigNum.html#method.rand
const SERIAL_NUMBER_SIZE: i32 = 159;
const CERTIFICATE_EXPIRATION_INTERVAL_IN_DAYS: u32 = 1;
const DEFAULT_DNS_NAME: &str = "localhost";
/// Indicates whether to add a custom TEE extension to a certificate.
#[derive(PartialEq)]
pub enum AddTeeExtension {
/// Enum value contains a PEM encoded TEE Provider's X.509 certificate that signs TEE firmware
/// key.
Yes(Vec<u8>),
No,
}
/// Convenience structure for generating X.509 certificates.
///
/// <https://tools.ietf.org/html/rfc5280>
pub struct CertificateAuthority {
pub key_pair: PKey<Private>,
pub root_certificate: X509,
}
impl CertificateAuthority {
/// Generates a root X.509 certificate and a corresponding private/public key pair.
///
/// `add_tee_extension` indicates whether to add a custom extension containing a TEE report to
/// the root certificate.
pub fn create(add_tee_extension: AddTeeExtension) -> anyhow::Result<Self> {
let key_pair = CertificateAuthority::generate_key_pair()?;
let root_certificate =
CertificateAuthority::generate_root_certificate(&key_pair, add_tee_extension)?;
Ok(Self {
key_pair,
root_certificate,
})
}
/// Generates RSA private/public key pair.
fn generate_key_pair() -> anyhow::Result<PKey<Private>> {
let rsa = Rsa::generate(RSA_KEY_SIZE).context("Couldn't generate RSA key")?;
PKey::from_rsa(rsa).context("Couldn't parse RSA key")
}
/// Creates a root X.509 certificate.
fn generate_root_certificate(
key_pair: &PKey<Private>,
add_tee_extension: AddTeeExtension,
) -> anyhow::Result<X509> {
info!("Generating root certificate");
let mut builder = CertificateBuilder::create()?;
builder.set_version(CERTIFICATE_VERSION)?;
builder.set_serial_number(SERIAL_NUMBER_SIZE)?;
builder.set_name()?;
builder.set_public_key(key_pair)?;
builder.set_expiration_interval(CERTIFICATE_EXPIRATION_INTERVAL_IN_DAYS)?;
builder.add_basic_constraints_extension(true)?;
builder.add_key_usage_extension(true)?;
builder.add_subject_key_identifier_extension(None)?;
builder.add_subject_alt_name_extension()?;
// Bind the certificate to the TEE firmware using an X.509 TEE extension.
if let AddTeeExtension::Yes(tee_certificate) = add_tee_extension {
builder.add_tee_extension(key_pair, tee_certificate)?;
}
let certificate = builder.build(key_pair)?;
Ok(certificate)
}
/// Generates an X.509 certificate based on the certificate signing `request`.
///
/// `add_tee_extension` indicates whether to add a custom extension containing a TEE report.
pub fn sign_certificate(
&self,
request: X509Req,
add_tee_extension: AddTeeExtension,
) -> anyhow::Result<X509> {
info!("Signing certificate");
let mut builder = CertificateBuilder::create()?;
builder.set_version(CERTIFICATE_VERSION)?;
builder.set_serial_number(SERIAL_NUMBER_SIZE)?;
builder.set_name()?;
builder.set_public_key(request.public_key()?.as_ref())?;
builder.set_expiration_interval(CERTIFICATE_EXPIRATION_INTERVAL_IN_DAYS)?;
builder.add_basic_constraints_extension(false)?;
builder.add_key_usage_extension(false)?;
builder.add_subject_key_identifier_extension(Some(&self.root_certificate))?;
builder.add_auth_key_identifier_extension(&self.root_certificate)?;
// Add X.509 extensions from the certificate signing request.
builder.add_extensions(request.extensions()?)?;
// Bind the certificate to the TEE firmware using an X.509 TEE extension.
if let AddTeeExtension::Yes(tee_certificate) = add_tee_extension {
builder.add_tee_extension(request.public_key()?.as_ref(), tee_certificate)?;
}
let certificate = builder.build(&self.key_pair)?;
Ok(certificate)
}
/// Get RSA key pair encoded in PEM format.
///
/// <https://tools.ietf.org/html/rfc7468>
pub fn get_private_key_pem(&self) -> anyhow::Result<Vec<u8>> {
self.key_pair
.private_key_to_pem_pkcs8()
.context("Couldn't encode key pair in PEM format")
}
/// Get a root X.509 certificate encoded in PEM format.
///
/// <https://tools.ietf.org/html/rfc7468>
pub fn get_root_certificate_pem(&self) -> anyhow::Result<Vec<u8>> {
self.root_certificate
.to_pem()
.context("Couldn't encode root certificate in PEM format")
}
}
/// Helper struct that implements certificate creation using `openssl`.
struct CertificateBuilder {
builder: X509Builder,
}
impl CertificateBuilder {
fn create() -> anyhow::Result<Self> |
fn set_version(&mut self, version: i32) -> anyhow::Result<&mut Self> {
self.builder.set_version(version)?;
Ok(self)
}
fn set_serial_number(&mut self, serial_number_size: i32) -> anyhow::Result<&mut Self> {
let serial_number = {
let mut serial = BigNum::new()?;
serial.rand(serial_number_size, MsbOption::MAYBE_ZERO, false)?;
serial.to_asn1_integer()?
};
self.builder.set_serial_number(&serial_number)?;
Ok(self)
}
fn set_name(&mut self) -> anyhow::Result<&mut Self> {
let mut name = X509NameBuilder::new()?;
name.append_entry_by_text("O", "Oak")?;
name.append_entry_by_text("CN", "Proxy Attestation Service")?;
let name = name.build();
self.builder.set_subject_name(&name)?;
self.builder.set_issuer_name(&name)?;
Ok(self)
}
fn set_public_key<T>(&mut self, public_key: &PKeyRef<T>) -> anyhow::Result<&mut Self>
where
T: HasPublic,
{
self.builder.set_pubkey(public_key)?;
Ok(self)
}
fn set_expiration_interval(&mut self, expiration_interval: u32) -> anyhow::Result<&mut Self> {
let not_before = Asn1Time::days_from_now(0)?;
self.builder.set_not_before(¬_before)?;
let not_after = Asn1Time::days_from_now(expiration_interval)?;
self.builder.set_not_after(¬_after)?;
Ok(self)
}
fn add_basic_constraints_extension(&mut self, is_critical: bool) -> anyhow::Result<&mut Self> {
if is_critical {
self.builder
.append_extension(BasicConstraints::new().critical().build()?)?;
} else {
self.builder
.append_extension(BasicConstraints::new().build()?)?;
}
Ok(self)
}
fn add_key_usage_extension(&mut self, is_root_certificate: bool) -> anyhow::Result<&mut Self> {
if is_root_certificate {
self.builder.append_extension(
KeyUsage::new()
.critical()
.key_cert_sign()
.crl_sign()
.build()?,
)?;
} else {
self.builder.append_extension(
KeyUsage::new()
.critical()
.non_repudiation()
.digital_signature()
.key_encipherment()
.build()?,
)?;
}
Ok(self)
}
fn add_subject_key_identifier_extension(
&mut self,
root_certificate: Option<&X509Ref>,
) -> anyhow::Result<&mut Self> {
let subject_key_identifier = SubjectKeyIdentifier::new()
.build(&self.builder.x509v3_context(root_certificate, None))?;
self.builder.append_extension(subject_key_identifier)?;
Ok(self)
}
fn add_subject_alt_name_extension(&mut self) -> anyhow::Result<&mut Self> {
let subject_alt_name = SubjectAlternativeName::new()
.dns(DEFAULT_DNS_NAME)
.build(&self.builder.x509v3_context(None, None))?;
self.builder.append_extension(subject_alt_name)?;
Ok(self)
}
fn add_auth_key_identifier_extension(
&mut self,
root_certificate: &X509Ref,
) -> anyhow::Result<&mut Self> {
let auth_key_identifier = AuthorityKeyIdentifier::new()
.keyid(false)
.issuer(false)
.build(&self.builder.x509v3_context(Some(root_certificate), None))?;
self.builder.append_extension(auth_key_identifier)?;
Ok(self)
}
// Generates a TEE report with the public key hash as data and add it to the certificate as a
// custom extension. This is required to bind the certificate to the TEE firmware.
fn add_tee_extension<T>(
&mut self,
public_key: &PKeyRef<T>,
tee_certificate: Vec<u8>,
) -> anyhow::Result<&mut Self>
where
T: HasPublic,
{
let public_key_hash = get_sha256(&public_key.public_key_to_der()?);
let tee_report = Report::new(&public_key_hash);
let attestation_info = AttestationInfo {
report: tee_report,
certificate: tee_certificate,
};
let tee_extension = attestation_info.to_extension()?;
self.builder.append_extension(tee_extension)?;
Ok(self)
}
fn add_extensions(
&mut self,
extensions: Stack<openssl::x509::X509Extension>,
) -> anyhow::Result<&mut Self> {
for extension in extensions.iter() {
self.builder.append_extension2(extension)?;
}
Ok(self)
}
fn build(mut self, private_key: &PKey<Private>) -> anyhow::Result<X509> {
self.builder.sign(private_key, MessageDigest::sha256())?;
Ok(self.builder.build())
}
}
| {
let builder = X509::builder()?;
Ok(Self { builder })
} | identifier_body |
certificate.rs | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use crate::{
get_sha256,
report::{AttestationInfo, Report},
};
use anyhow::Context;
use log::info;
use openssl::{
asn1::Asn1Time,
bn::{BigNum, MsbOption},
hash::MessageDigest,
pkey::{HasPublic, PKey, PKeyRef, Private},
rsa::Rsa,
stack::Stack,
x509::{
extension::{
AuthorityKeyIdentifier, BasicConstraints, KeyUsage, SubjectAlternativeName,
SubjectKeyIdentifier,
},
X509Builder, X509NameBuilder, X509Ref, X509Req, X509,
},
};
// X.509 certificate parameters.
//
// <https://tools.ietf.org/html/rfc5280>
const RSA_KEY_SIZE: u32 = 2048;
// Version is zero-indexed, so the value of `2` corresponds to the version `3`.
const CERTIFICATE_VERSION: i32 = 2;
// Length of the randomly generated X.509 certificate serial number (which is 20 bytes).
//
// The most significant bit is excluded because it's passed as a separate argument to:
// https://docs.rs/openssl/0.10.33/openssl/bn/struct.BigNum.html#method.rand
const SERIAL_NUMBER_SIZE: i32 = 159;
const CERTIFICATE_EXPIRATION_INTERVAL_IN_DAYS: u32 = 1;
const DEFAULT_DNS_NAME: &str = "localhost";
/// Indicates whether to add a custom TEE extension to a certificate.
#[derive(PartialEq)]
pub enum AddTeeExtension {
/// Enum value contains a PEM encoded TEE Provider's X.509 certificate that signs TEE firmware
/// key.
Yes(Vec<u8>),
No,
}
/// Convenience structure for generating X.509 certificates.
///
/// <https://tools.ietf.org/html/rfc5280>
pub struct CertificateAuthority {
pub key_pair: PKey<Private>,
pub root_certificate: X509,
}
impl CertificateAuthority {
/// Generates a root X.509 certificate and a corresponding private/public key pair.
///
/// `add_tee_extension` indicates whether to add a custom extension containing a TEE report to
/// the root certificate.
pub fn create(add_tee_extension: AddTeeExtension) -> anyhow::Result<Self> {
let key_pair = CertificateAuthority::generate_key_pair()?;
let root_certificate =
CertificateAuthority::generate_root_certificate(&key_pair, add_tee_extension)?;
Ok(Self {
key_pair,
root_certificate,
})
}
/// Generates RSA private/public key pair.
fn generate_key_pair() -> anyhow::Result<PKey<Private>> {
let rsa = Rsa::generate(RSA_KEY_SIZE).context("Couldn't generate RSA key")?;
PKey::from_rsa(rsa).context("Couldn't parse RSA key")
}
/// Creates a root X.509 certificate.
fn generate_root_certificate(
key_pair: &PKey<Private>,
add_tee_extension: AddTeeExtension,
) -> anyhow::Result<X509> {
info!("Generating root certificate");
let mut builder = CertificateBuilder::create()?;
builder.set_version(CERTIFICATE_VERSION)?;
builder.set_serial_number(SERIAL_NUMBER_SIZE)?;
builder.set_name()?;
builder.set_public_key(key_pair)?;
builder.set_expiration_interval(CERTIFICATE_EXPIRATION_INTERVAL_IN_DAYS)?;
builder.add_basic_constraints_extension(true)?;
builder.add_key_usage_extension(true)?;
builder.add_subject_key_identifier_extension(None)?;
builder.add_subject_alt_name_extension()?;
// Bind the certificate to the TEE firmware using an X.509 TEE extension.
if let AddTeeExtension::Yes(tee_certificate) = add_tee_extension |
let certificate = builder.build(key_pair)?;
Ok(certificate)
}
/// Generates an X.509 certificate based on the certificate signing `request`.
///
/// `add_tee_extension` indicates whether to add a custom extension containing a TEE report.
pub fn sign_certificate(
&self,
request: X509Req,
add_tee_extension: AddTeeExtension,
) -> anyhow::Result<X509> {
info!("Signing certificate");
let mut builder = CertificateBuilder::create()?;
builder.set_version(CERTIFICATE_VERSION)?;
builder.set_serial_number(SERIAL_NUMBER_SIZE)?;
builder.set_name()?;
builder.set_public_key(request.public_key()?.as_ref())?;
builder.set_expiration_interval(CERTIFICATE_EXPIRATION_INTERVAL_IN_DAYS)?;
builder.add_basic_constraints_extension(false)?;
builder.add_key_usage_extension(false)?;
builder.add_subject_key_identifier_extension(Some(&self.root_certificate))?;
builder.add_auth_key_identifier_extension(&self.root_certificate)?;
// Add X.509 extensions from the certificate signing request.
builder.add_extensions(request.extensions()?)?;
// Bind the certificate to the TEE firmware using an X.509 TEE extension.
if let AddTeeExtension::Yes(tee_certificate) = add_tee_extension {
builder.add_tee_extension(request.public_key()?.as_ref(), tee_certificate)?;
}
let certificate = builder.build(&self.key_pair)?;
Ok(certificate)
}
/// Get RSA key pair encoded in PEM format.
///
/// <https://tools.ietf.org/html/rfc7468>
pub fn get_private_key_pem(&self) -> anyhow::Result<Vec<u8>> {
self.key_pair
.private_key_to_pem_pkcs8()
.context("Couldn't encode key pair in PEM format")
}
/// Get a root X.509 certificate encoded in PEM format.
///
/// <https://tools.ietf.org/html/rfc7468>
pub fn get_root_certificate_pem(&self) -> anyhow::Result<Vec<u8>> {
self.root_certificate
.to_pem()
.context("Couldn't encode root certificate in PEM format")
}
}
/// Helper struct that implements certificate creation using `openssl`.
struct CertificateBuilder {
builder: X509Builder,
}
impl CertificateBuilder {
fn create() -> anyhow::Result<Self> {
let builder = X509::builder()?;
Ok(Self { builder })
}
fn set_version(&mut self, version: i32) -> anyhow::Result<&mut Self> {
self.builder.set_version(version)?;
Ok(self)
}
fn set_serial_number(&mut self, serial_number_size: i32) -> anyhow::Result<&mut Self> {
let serial_number = {
let mut serial = BigNum::new()?;
serial.rand(serial_number_size, MsbOption::MAYBE_ZERO, false)?;
serial.to_asn1_integer()?
};
self.builder.set_serial_number(&serial_number)?;
Ok(self)
}
fn set_name(&mut self) -> anyhow::Result<&mut Self> {
let mut name = X509NameBuilder::new()?;
name.append_entry_by_text("O", "Oak")?;
name.append_entry_by_text("CN", "Proxy Attestation Service")?;
let name = name.build();
self.builder.set_subject_name(&name)?;
self.builder.set_issuer_name(&name)?;
Ok(self)
}
fn set_public_key<T>(&mut self, public_key: &PKeyRef<T>) -> anyhow::Result<&mut Self>
where
T: HasPublic,
{
self.builder.set_pubkey(public_key)?;
Ok(self)
}
fn set_expiration_interval(&mut self, expiration_interval: u32) -> anyhow::Result<&mut Self> {
let not_before = Asn1Time::days_from_now(0)?;
self.builder.set_not_before(¬_before)?;
let not_after = Asn1Time::days_from_now(expiration_interval)?;
self.builder.set_not_after(¬_after)?;
Ok(self)
}
fn add_basic_constraints_extension(&mut self, is_critical: bool) -> anyhow::Result<&mut Self> {
if is_critical {
self.builder
.append_extension(BasicConstraints::new().critical().build()?)?;
} else {
self.builder
.append_extension(BasicConstraints::new().build()?)?;
}
Ok(self)
}
fn add_key_usage_extension(&mut self, is_root_certificate: bool) -> anyhow::Result<&mut Self> {
if is_root_certificate {
self.builder.append_extension(
KeyUsage::new()
.critical()
.key_cert_sign()
.crl_sign()
.build()?,
)?;
} else {
self.builder.append_extension(
KeyUsage::new()
.critical()
.non_repudiation()
.digital_signature()
.key_encipherment()
.build()?,
)?;
}
Ok(self)
}
fn add_subject_key_identifier_extension(
&mut self,
root_certificate: Option<&X509Ref>,
) -> anyhow::Result<&mut Self> {
let subject_key_identifier = SubjectKeyIdentifier::new()
.build(&self.builder.x509v3_context(root_certificate, None))?;
self.builder.append_extension(subject_key_identifier)?;
Ok(self)
}
fn add_subject_alt_name_extension(&mut self) -> anyhow::Result<&mut Self> {
let subject_alt_name = SubjectAlternativeName::new()
.dns(DEFAULT_DNS_NAME)
.build(&self.builder.x509v3_context(None, None))?;
self.builder.append_extension(subject_alt_name)?;
Ok(self)
}
fn add_auth_key_identifier_extension(
&mut self,
root_certificate: &X509Ref,
) -> anyhow::Result<&mut Self> {
let auth_key_identifier = AuthorityKeyIdentifier::new()
.keyid(false)
.issuer(false)
.build(&self.builder.x509v3_context(Some(root_certificate), None))?;
self.builder.append_extension(auth_key_identifier)?;
Ok(self)
}
// Generates a TEE report with the public key hash as data and add it to the certificate as a
// custom extension. This is required to bind the certificate to the TEE firmware.
fn add_tee_extension<T>(
&mut self,
public_key: &PKeyRef<T>,
tee_certificate: Vec<u8>,
) -> anyhow::Result<&mut Self>
where
T: HasPublic,
{
let public_key_hash = get_sha256(&public_key.public_key_to_der()?);
let tee_report = Report::new(&public_key_hash);
let attestation_info = AttestationInfo {
report: tee_report,
certificate: tee_certificate,
};
let tee_extension = attestation_info.to_extension()?;
self.builder.append_extension(tee_extension)?;
Ok(self)
}
fn add_extensions(
&mut self,
extensions: Stack<openssl::x509::X509Extension>,
) -> anyhow::Result<&mut Self> {
for extension in extensions.iter() {
self.builder.append_extension2(extension)?;
}
Ok(self)
}
fn build(mut self, private_key: &PKey<Private>) -> anyhow::Result<X509> {
self.builder.sign(private_key, MessageDigest::sha256())?;
Ok(self.builder.build())
}
}
| {
builder.add_tee_extension(key_pair, tee_certificate)?;
} | conditional_block |
certificate.rs | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use crate::{
get_sha256,
report::{AttestationInfo, Report},
};
use anyhow::Context;
use log::info;
use openssl::{
asn1::Asn1Time,
bn::{BigNum, MsbOption},
hash::MessageDigest,
pkey::{HasPublic, PKey, PKeyRef, Private},
rsa::Rsa,
stack::Stack,
x509::{
extension::{
AuthorityKeyIdentifier, BasicConstraints, KeyUsage, SubjectAlternativeName,
SubjectKeyIdentifier,
},
X509Builder, X509NameBuilder, X509Ref, X509Req, X509,
},
};
// X.509 certificate parameters.
//
// <https://tools.ietf.org/html/rfc5280>
const RSA_KEY_SIZE: u32 = 2048;
// Version is zero-indexed, so the value of `2` corresponds to the version `3`.
const CERTIFICATE_VERSION: i32 = 2;
// Length of the randomly generated X.509 certificate serial number (which is 20 bytes).
//
// The most significant bit is excluded because it's passed as a separate argument to:
// https://docs.rs/openssl/0.10.33/openssl/bn/struct.BigNum.html#method.rand
const SERIAL_NUMBER_SIZE: i32 = 159;
const CERTIFICATE_EXPIRATION_INTERVAL_IN_DAYS: u32 = 1;
const DEFAULT_DNS_NAME: &str = "localhost";
/// Indicates whether to add a custom TEE extension to a certificate.
#[derive(PartialEq)]
pub enum AddTeeExtension {
/// Enum value contains a PEM encoded TEE Provider's X.509 certificate that signs TEE firmware
/// key.
Yes(Vec<u8>),
No,
}
/// Convenience structure for generating X.509 certificates.
///
/// <https://tools.ietf.org/html/rfc5280>
pub struct CertificateAuthority {
pub key_pair: PKey<Private>,
pub root_certificate: X509,
}
impl CertificateAuthority {
/// Generates a root X.509 certificate and a corresponding private/public key pair.
///
/// `add_tee_extension` indicates whether to add a custom extension containing a TEE report to
/// the root certificate.
pub fn create(add_tee_extension: AddTeeExtension) -> anyhow::Result<Self> {
let key_pair = CertificateAuthority::generate_key_pair()?;
let root_certificate =
CertificateAuthority::generate_root_certificate(&key_pair, add_tee_extension)?;
Ok(Self {
key_pair,
root_certificate,
})
}
/// Generates RSA private/public key pair.
fn generate_key_pair() -> anyhow::Result<PKey<Private>> {
let rsa = Rsa::generate(RSA_KEY_SIZE).context("Couldn't generate RSA key")?;
PKey::from_rsa(rsa).context("Couldn't parse RSA key")
}
/// Creates a root X.509 certificate.
fn generate_root_certificate(
key_pair: &PKey<Private>,
add_tee_extension: AddTeeExtension,
) -> anyhow::Result<X509> {
info!("Generating root certificate");
let mut builder = CertificateBuilder::create()?;
builder.set_version(CERTIFICATE_VERSION)?;
builder.set_serial_number(SERIAL_NUMBER_SIZE)?;
builder.set_name()?;
builder.set_public_key(key_pair)?;
builder.set_expiration_interval(CERTIFICATE_EXPIRATION_INTERVAL_IN_DAYS)?;
builder.add_basic_constraints_extension(true)?;
builder.add_key_usage_extension(true)?;
builder.add_subject_key_identifier_extension(None)?;
builder.add_subject_alt_name_extension()?;
// Bind the certificate to the TEE firmware using an X.509 TEE extension.
if let AddTeeExtension::Yes(tee_certificate) = add_tee_extension {
builder.add_tee_extension(key_pair, tee_certificate)?;
}
let certificate = builder.build(key_pair)?;
Ok(certificate)
}
/// Generates an X.509 certificate based on the certificate signing `request`.
///
/// `add_tee_extension` indicates whether to add a custom extension containing a TEE report.
pub fn sign_certificate(
&self,
request: X509Req,
add_tee_extension: AddTeeExtension,
) -> anyhow::Result<X509> {
info!("Signing certificate");
let mut builder = CertificateBuilder::create()?;
builder.set_version(CERTIFICATE_VERSION)?;
builder.set_serial_number(SERIAL_NUMBER_SIZE)?;
builder.set_name()?;
builder.set_public_key(request.public_key()?.as_ref())?;
builder.set_expiration_interval(CERTIFICATE_EXPIRATION_INTERVAL_IN_DAYS)?;
builder.add_basic_constraints_extension(false)?;
builder.add_key_usage_extension(false)?;
builder.add_subject_key_identifier_extension(Some(&self.root_certificate))?;
builder.add_auth_key_identifier_extension(&self.root_certificate)?;
// Add X.509 extensions from the certificate signing request.
builder.add_extensions(request.extensions()?)?;
// Bind the certificate to the TEE firmware using an X.509 TEE extension.
if let AddTeeExtension::Yes(tee_certificate) = add_tee_extension {
builder.add_tee_extension(request.public_key()?.as_ref(), tee_certificate)?;
}
let certificate = builder.build(&self.key_pair)?;
Ok(certificate)
}
/// Get RSA key pair encoded in PEM format.
///
/// <https://tools.ietf.org/html/rfc7468>
pub fn get_private_key_pem(&self) -> anyhow::Result<Vec<u8>> {
self.key_pair
.private_key_to_pem_pkcs8()
.context("Couldn't encode key pair in PEM format")
}
/// Get a root X.509 certificate encoded in PEM format.
///
/// <https://tools.ietf.org/html/rfc7468>
pub fn get_root_certificate_pem(&self) -> anyhow::Result<Vec<u8>> {
self.root_certificate
.to_pem()
.context("Couldn't encode root certificate in PEM format")
}
}
/// Helper struct that implements certificate creation using `openssl`.
struct CertificateBuilder {
builder: X509Builder,
}
impl CertificateBuilder {
fn create() -> anyhow::Result<Self> {
let builder = X509::builder()?;
Ok(Self { builder })
}
fn set_version(&mut self, version: i32) -> anyhow::Result<&mut Self> {
self.builder.set_version(version)?;
Ok(self)
}
fn set_serial_number(&mut self, serial_number_size: i32) -> anyhow::Result<&mut Self> {
let serial_number = {
let mut serial = BigNum::new()?;
serial.rand(serial_number_size, MsbOption::MAYBE_ZERO, false)?;
serial.to_asn1_integer()?
};
self.builder.set_serial_number(&serial_number)?;
Ok(self)
}
fn set_name(&mut self) -> anyhow::Result<&mut Self> {
let mut name = X509NameBuilder::new()?;
name.append_entry_by_text("O", "Oak")?;
name.append_entry_by_text("CN", "Proxy Attestation Service")?;
let name = name.build();
self.builder.set_subject_name(&name)?;
self.builder.set_issuer_name(&name)?;
Ok(self)
}
fn set_public_key<T>(&mut self, public_key: &PKeyRef<T>) -> anyhow::Result<&mut Self>
where
T: HasPublic,
{
self.builder.set_pubkey(public_key)?;
Ok(self)
}
fn set_expiration_interval(&mut self, expiration_interval: u32) -> anyhow::Result<&mut Self> {
let not_before = Asn1Time::days_from_now(0)?;
self.builder.set_not_before(¬_before)?;
let not_after = Asn1Time::days_from_now(expiration_interval)?;
self.builder.set_not_after(¬_after)?;
Ok(self)
}
fn add_basic_constraints_extension(&mut self, is_critical: bool) -> anyhow::Result<&mut Self> {
if is_critical {
self.builder
.append_extension(BasicConstraints::new().critical().build()?)?;
} else {
self.builder
.append_extension(BasicConstraints::new().build()?)?;
}
Ok(self)
}
fn add_key_usage_extension(&mut self, is_root_certificate: bool) -> anyhow::Result<&mut Self> {
if is_root_certificate {
self.builder.append_extension(
KeyUsage::new()
.critical()
.key_cert_sign()
.crl_sign()
.build()?,
)?;
} else {
self.builder.append_extension(
KeyUsage::new()
.critical()
.non_repudiation()
.digital_signature()
.key_encipherment()
.build()?,
)?;
}
Ok(self)
}
fn add_subject_key_identifier_extension(
&mut self,
root_certificate: Option<&X509Ref>,
) -> anyhow::Result<&mut Self> {
let subject_key_identifier = SubjectKeyIdentifier::new() | .build(&self.builder.x509v3_context(root_certificate, None))?;
self.builder.append_extension(subject_key_identifier)?;
Ok(self)
}
fn add_subject_alt_name_extension(&mut self) -> anyhow::Result<&mut Self> {
let subject_alt_name = SubjectAlternativeName::new()
.dns(DEFAULT_DNS_NAME)
.build(&self.builder.x509v3_context(None, None))?;
self.builder.append_extension(subject_alt_name)?;
Ok(self)
}
fn add_auth_key_identifier_extension(
&mut self,
root_certificate: &X509Ref,
) -> anyhow::Result<&mut Self> {
let auth_key_identifier = AuthorityKeyIdentifier::new()
.keyid(false)
.issuer(false)
.build(&self.builder.x509v3_context(Some(root_certificate), None))?;
self.builder.append_extension(auth_key_identifier)?;
Ok(self)
}
// Generates a TEE report with the public key hash as data and add it to the certificate as a
// custom extension. This is required to bind the certificate to the TEE firmware.
fn add_tee_extension<T>(
&mut self,
public_key: &PKeyRef<T>,
tee_certificate: Vec<u8>,
) -> anyhow::Result<&mut Self>
where
T: HasPublic,
{
let public_key_hash = get_sha256(&public_key.public_key_to_der()?);
let tee_report = Report::new(&public_key_hash);
let attestation_info = AttestationInfo {
report: tee_report,
certificate: tee_certificate,
};
let tee_extension = attestation_info.to_extension()?;
self.builder.append_extension(tee_extension)?;
Ok(self)
}
fn add_extensions(
&mut self,
extensions: Stack<openssl::x509::X509Extension>,
) -> anyhow::Result<&mut Self> {
for extension in extensions.iter() {
self.builder.append_extension2(extension)?;
}
Ok(self)
}
fn build(mut self, private_key: &PKey<Private>) -> anyhow::Result<X509> {
self.builder.sign(private_key, MessageDigest::sha256())?;
Ok(self.builder.build())
}
} | random_line_split |
|
print_context.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use PageSetup; | use std::mem;
glib_wrapper! {
pub struct PrintContext(Object<ffi::GtkPrintContext, PrintContextClass>);
match fn {
get_type => || ffi::gtk_print_context_get_type(),
}
}
impl PrintContext {
pub fn create_pango_context(&self) -> Option<pango::Context> {
unsafe {
from_glib_full(ffi::gtk_print_context_create_pango_context(self.to_glib_none().0))
}
}
pub fn create_pango_layout(&self) -> Option<pango::Layout> {
unsafe {
from_glib_full(ffi::gtk_print_context_create_pango_layout(self.to_glib_none().0))
}
}
pub fn get_cairo_context(&self) -> Option<cairo::Context> {
unsafe {
from_glib_none(ffi::gtk_print_context_get_cairo_context(self.to_glib_none().0))
}
}
pub fn get_dpi_x(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_dpi_x(self.to_glib_none().0)
}
}
pub fn get_dpi_y(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_dpi_y(self.to_glib_none().0)
}
}
pub fn get_hard_margins(&self) -> Option<(f64, f64, f64, f64)> {
unsafe {
let mut top = mem::uninitialized();
let mut bottom = mem::uninitialized();
let mut left = mem::uninitialized();
let mut right = mem::uninitialized();
let ret = from_glib(ffi::gtk_print_context_get_hard_margins(self.to_glib_none().0, &mut top, &mut bottom, &mut left, &mut right));
if ret { Some((top, bottom, left, right)) } else { None }
}
}
pub fn get_height(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_height(self.to_glib_none().0)
}
}
pub fn get_page_setup(&self) -> Option<PageSetup> {
unsafe {
from_glib_none(ffi::gtk_print_context_get_page_setup(self.to_glib_none().0))
}
}
pub fn get_pango_fontmap(&self) -> Option<pango::FontMap> {
unsafe {
from_glib_none(ffi::gtk_print_context_get_pango_fontmap(self.to_glib_none().0))
}
}
pub fn get_width(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_width(self.to_glib_none().0)
}
}
pub fn set_cairo_context(&self, cr: &cairo::Context, dpi_x: f64, dpi_y: f64) {
unsafe {
ffi::gtk_print_context_set_cairo_context(self.to_glib_none().0, mut_override(cr.to_glib_none().0), dpi_x, dpi_y);
}
}
}
impl fmt::Display for PrintContext {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "PrintContext")
}
} | use cairo;
use ffi;
use glib::translate::*;
use pango;
use std::fmt; | random_line_split |
print_context.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use PageSetup;
use cairo;
use ffi;
use glib::translate::*;
use pango;
use std::fmt;
use std::mem;
glib_wrapper! {
pub struct PrintContext(Object<ffi::GtkPrintContext, PrintContextClass>);
match fn {
get_type => || ffi::gtk_print_context_get_type(),
}
}
impl PrintContext {
pub fn create_pango_context(&self) -> Option<pango::Context> {
unsafe {
from_glib_full(ffi::gtk_print_context_create_pango_context(self.to_glib_none().0))
}
}
pub fn create_pango_layout(&self) -> Option<pango::Layout> {
unsafe {
from_glib_full(ffi::gtk_print_context_create_pango_layout(self.to_glib_none().0))
}
}
pub fn get_cairo_context(&self) -> Option<cairo::Context> {
unsafe {
from_glib_none(ffi::gtk_print_context_get_cairo_context(self.to_glib_none().0))
}
}
pub fn get_dpi_x(&self) -> f64 |
pub fn get_dpi_y(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_dpi_y(self.to_glib_none().0)
}
}
pub fn get_hard_margins(&self) -> Option<(f64, f64, f64, f64)> {
unsafe {
let mut top = mem::uninitialized();
let mut bottom = mem::uninitialized();
let mut left = mem::uninitialized();
let mut right = mem::uninitialized();
let ret = from_glib(ffi::gtk_print_context_get_hard_margins(self.to_glib_none().0, &mut top, &mut bottom, &mut left, &mut right));
if ret { Some((top, bottom, left, right)) } else { None }
}
}
pub fn get_height(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_height(self.to_glib_none().0)
}
}
pub fn get_page_setup(&self) -> Option<PageSetup> {
unsafe {
from_glib_none(ffi::gtk_print_context_get_page_setup(self.to_glib_none().0))
}
}
pub fn get_pango_fontmap(&self) -> Option<pango::FontMap> {
unsafe {
from_glib_none(ffi::gtk_print_context_get_pango_fontmap(self.to_glib_none().0))
}
}
pub fn get_width(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_width(self.to_glib_none().0)
}
}
pub fn set_cairo_context(&self, cr: &cairo::Context, dpi_x: f64, dpi_y: f64) {
unsafe {
ffi::gtk_print_context_set_cairo_context(self.to_glib_none().0, mut_override(cr.to_glib_none().0), dpi_x, dpi_y);
}
}
}
impl fmt::Display for PrintContext {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "PrintContext")
}
}
| {
unsafe {
ffi::gtk_print_context_get_dpi_x(self.to_glib_none().0)
}
} | identifier_body |
print_context.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use PageSetup;
use cairo;
use ffi;
use glib::translate::*;
use pango;
use std::fmt;
use std::mem;
glib_wrapper! {
pub struct PrintContext(Object<ffi::GtkPrintContext, PrintContextClass>);
match fn {
get_type => || ffi::gtk_print_context_get_type(),
}
}
impl PrintContext {
pub fn create_pango_context(&self) -> Option<pango::Context> {
unsafe {
from_glib_full(ffi::gtk_print_context_create_pango_context(self.to_glib_none().0))
}
}
pub fn create_pango_layout(&self) -> Option<pango::Layout> {
unsafe {
from_glib_full(ffi::gtk_print_context_create_pango_layout(self.to_glib_none().0))
}
}
pub fn get_cairo_context(&self) -> Option<cairo::Context> {
unsafe {
from_glib_none(ffi::gtk_print_context_get_cairo_context(self.to_glib_none().0))
}
}
pub fn get_dpi_x(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_dpi_x(self.to_glib_none().0)
}
}
pub fn get_dpi_y(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_dpi_y(self.to_glib_none().0)
}
}
pub fn get_hard_margins(&self) -> Option<(f64, f64, f64, f64)> {
unsafe {
let mut top = mem::uninitialized();
let mut bottom = mem::uninitialized();
let mut left = mem::uninitialized();
let mut right = mem::uninitialized();
let ret = from_glib(ffi::gtk_print_context_get_hard_margins(self.to_glib_none().0, &mut top, &mut bottom, &mut left, &mut right));
if ret { Some((top, bottom, left, right)) } else { None }
}
}
pub fn get_height(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_height(self.to_glib_none().0)
}
}
pub fn get_page_setup(&self) -> Option<PageSetup> {
unsafe {
from_glib_none(ffi::gtk_print_context_get_page_setup(self.to_glib_none().0))
}
}
pub fn | (&self) -> Option<pango::FontMap> {
unsafe {
from_glib_none(ffi::gtk_print_context_get_pango_fontmap(self.to_glib_none().0))
}
}
pub fn get_width(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_width(self.to_glib_none().0)
}
}
pub fn set_cairo_context(&self, cr: &cairo::Context, dpi_x: f64, dpi_y: f64) {
unsafe {
ffi::gtk_print_context_set_cairo_context(self.to_glib_none().0, mut_override(cr.to_glib_none().0), dpi_x, dpi_y);
}
}
}
impl fmt::Display for PrintContext {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "PrintContext")
}
}
| get_pango_fontmap | identifier_name |
print_context.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use PageSetup;
use cairo;
use ffi;
use glib::translate::*;
use pango;
use std::fmt;
use std::mem;
glib_wrapper! {
pub struct PrintContext(Object<ffi::GtkPrintContext, PrintContextClass>);
match fn {
get_type => || ffi::gtk_print_context_get_type(),
}
}
impl PrintContext {
pub fn create_pango_context(&self) -> Option<pango::Context> {
unsafe {
from_glib_full(ffi::gtk_print_context_create_pango_context(self.to_glib_none().0))
}
}
pub fn create_pango_layout(&self) -> Option<pango::Layout> {
unsafe {
from_glib_full(ffi::gtk_print_context_create_pango_layout(self.to_glib_none().0))
}
}
pub fn get_cairo_context(&self) -> Option<cairo::Context> {
unsafe {
from_glib_none(ffi::gtk_print_context_get_cairo_context(self.to_glib_none().0))
}
}
pub fn get_dpi_x(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_dpi_x(self.to_glib_none().0)
}
}
pub fn get_dpi_y(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_dpi_y(self.to_glib_none().0)
}
}
pub fn get_hard_margins(&self) -> Option<(f64, f64, f64, f64)> {
unsafe {
let mut top = mem::uninitialized();
let mut bottom = mem::uninitialized();
let mut left = mem::uninitialized();
let mut right = mem::uninitialized();
let ret = from_glib(ffi::gtk_print_context_get_hard_margins(self.to_glib_none().0, &mut top, &mut bottom, &mut left, &mut right));
if ret | else { None }
}
}
pub fn get_height(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_height(self.to_glib_none().0)
}
}
pub fn get_page_setup(&self) -> Option<PageSetup> {
unsafe {
from_glib_none(ffi::gtk_print_context_get_page_setup(self.to_glib_none().0))
}
}
pub fn get_pango_fontmap(&self) -> Option<pango::FontMap> {
unsafe {
from_glib_none(ffi::gtk_print_context_get_pango_fontmap(self.to_glib_none().0))
}
}
pub fn get_width(&self) -> f64 {
unsafe {
ffi::gtk_print_context_get_width(self.to_glib_none().0)
}
}
pub fn set_cairo_context(&self, cr: &cairo::Context, dpi_x: f64, dpi_y: f64) {
unsafe {
ffi::gtk_print_context_set_cairo_context(self.to_glib_none().0, mut_override(cr.to_glib_none().0), dpi_x, dpi_y);
}
}
}
impl fmt::Display for PrintContext {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "PrintContext")
}
}
| { Some((top, bottom, left, right)) } | conditional_block |
trie.rs | /* Copyright 2017 Joel Pedraza
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* A Radix 26 Trie
*
* I'd prefer if if each letter was represented as Enum rather than a u8 (for safety)
* Can they be used without sacrifing perf?
*/
use boggle_util;
use bitset::BitSet32;
use bitset::IndexIter32;
use std::mem;
type Node = Option<Box<Trie>>;
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum NodeType {
Prefix,
Word(usize),
}
#[derive(Debug)]
pub struct | {
node_type: NodeType,
children: [Node; boggle_util::ALPHABET_SIZE],
child_set: BitSet32,
}
impl Trie {
pub fn new() -> Self {
Trie {
node_type: NodeType::Prefix,
children: Default::default(),
child_set: BitSet32::new(),
}
}
pub fn node_type(&self) -> NodeType {
self.node_type
}
pub fn insert(&mut self, s: &str, id: usize) -> bool {
if boggle_util::is_alpha(s) {
self.ins(s.to_lowercase().as_bytes(), id);
true
} else {
false
}
}
#[inline]
fn ins(&mut self, s: &[u8], id: usize) -> () {
let first = boggle_util::ascii_byte_to_idx(s[0]);
if self.children[first].is_none() {
self.child_set.add(first as u32);
mem::replace(&mut (self.children[first]), Some(Box::new(Trie::new())));
}
let child = self.children[first].as_mut().unwrap();
if s.len() > 1 {
child.ins(&s[1..], id);
} else {
child.node_type = NodeType::Word(id);
}
}
#[allow(dead_code)]
pub fn contains(&self, s: &str) -> Option<NodeType> {
if boggle_util::is_alpha(s) {
self.cns(s.to_lowercase().as_bytes())
} else {
None
}
}
#[inline]
fn cns(&self, s: &[u8]) -> Option<NodeType> {
let first = boggle_util::ascii_byte_to_idx(s[0]);
if let Some(child) = self.children[first].as_ref() {
if s.len() == 1 {
Some(child.node_type)
} else {
let rest = &s[1..];
child.cns(rest)
}
} else {
None
}
}
pub fn iter(&self) -> TrieIterator {
TrieIterator::new(self)
}
}
pub struct TrieIterator<'a> {
trie: &'a Trie,
iter: IndexIter32<'a>,
}
impl<'a> TrieIterator<'a> {
fn new(trie: &'a Trie) -> TrieIterator<'a> {
TrieIterator {
trie: trie,
iter: trie.child_set.iter_ones(),
}
}
}
impl<'a> Iterator for TrieIterator<'a> {
type Item = (&'a Trie, u8);
fn next(&mut self) -> Option<(&'a Trie, u8)> {
match self.iter.next() {
Some(i) => {
match self.trie.children[i as usize] {
Some(ref trie) => Some((trie, i as u8)),
None => None
}
},
None => None
}
}
}
//==============================================================================
#[cfg(test)]
mod test{
use std::str;
use super::Trie;
use super::NodeType;
#[test]
fn valid_words_are_inserted() {
let mut trie = Trie::new();
assert_eq!(trie.contains("a"), None);
assert_eq!(trie.contains("abba"), None);
assert!(trie.insert("abba", 0));
assert_eq!(trie.contains("a"), Some(NodeType::Prefix));
assert_eq!(trie.contains("ab"), Some(NodeType::Prefix));
assert_eq!(trie.contains("abb"), Some(NodeType::Prefix));
assert_eq!(trie.contains("abba"), Some(NodeType::Word(0)));
}
#[test]
fn invalid_words_are_not_inserted() {
let mut trie = Trie::new();
let mut id = 0;
for s in ('\u{0}' as u8.. 'A' as u8)
.chain('[' as u8.. 'a' as u8)
.chain('{' as u8.. '\u{ff}' as u8)
.map(|b| unsafe { str::from_utf8_unchecked(&[b]) }.to_owned() ) {
id += 1;
assert!(!trie.insert(&s, id));
assert_eq!(trie.contains(&s), None);
}
}
#[test]
fn is_case_insensitive() {
let mut trie = Trie::new();
trie.insert("a", 0);
assert_eq!(trie.contains("a"), Some(NodeType::Word(0)));
assert_eq!(trie.contains("A"), Some(NodeType::Word(0)));
trie.insert("B", 1);
assert_eq!(trie.contains("b"), Some(NodeType::Word(1)));
assert_eq!(trie.contains("B"), Some(NodeType::Word(1)));
}
} | Trie | identifier_name |
trie.rs | /* Copyright 2017 Joel Pedraza
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* A Radix 26 Trie
*
* I'd prefer if if each letter was represented as Enum rather than a u8 (for safety)
* Can they be used without sacrifing perf?
*/
use boggle_util;
use bitset::BitSet32;
use bitset::IndexIter32;
use std::mem;
type Node = Option<Box<Trie>>;
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum NodeType {
Prefix,
Word(usize),
}
#[derive(Debug)]
pub struct Trie {
node_type: NodeType,
children: [Node; boggle_util::ALPHABET_SIZE],
child_set: BitSet32,
}
impl Trie {
pub fn new() -> Self {
Trie {
node_type: NodeType::Prefix,
children: Default::default(),
child_set: BitSet32::new(),
}
}
pub fn node_type(&self) -> NodeType {
self.node_type
}
pub fn insert(&mut self, s: &str, id: usize) -> bool {
if boggle_util::is_alpha(s) {
self.ins(s.to_lowercase().as_bytes(), id);
true
} else {
false
}
}
#[inline]
fn ins(&mut self, s: &[u8], id: usize) -> () {
let first = boggle_util::ascii_byte_to_idx(s[0]);
if self.children[first].is_none() {
self.child_set.add(first as u32);
mem::replace(&mut (self.children[first]), Some(Box::new(Trie::new())));
}
let child = self.children[first].as_mut().unwrap();
if s.len() > 1 {
child.ins(&s[1..], id);
} else {
child.node_type = NodeType::Word(id);
}
}
#[allow(dead_code)]
pub fn contains(&self, s: &str) -> Option<NodeType> {
if boggle_util::is_alpha(s) {
self.cns(s.to_lowercase().as_bytes())
} else {
None
}
}
#[inline]
fn cns(&self, s: &[u8]) -> Option<NodeType> {
let first = boggle_util::ascii_byte_to_idx(s[0]);
if let Some(child) = self.children[first].as_ref() {
if s.len() == 1 {
Some(child.node_type)
} else {
let rest = &s[1..];
child.cns(rest)
}
} else {
None
}
}
pub fn iter(&self) -> TrieIterator {
TrieIterator::new(self)
}
}
| trie: &'a Trie,
iter: IndexIter32<'a>,
}
impl<'a> TrieIterator<'a> {
fn new(trie: &'a Trie) -> TrieIterator<'a> {
TrieIterator {
trie: trie,
iter: trie.child_set.iter_ones(),
}
}
}
impl<'a> Iterator for TrieIterator<'a> {
type Item = (&'a Trie, u8);
fn next(&mut self) -> Option<(&'a Trie, u8)> {
match self.iter.next() {
Some(i) => {
match self.trie.children[i as usize] {
Some(ref trie) => Some((trie, i as u8)),
None => None
}
},
None => None
}
}
}
//==============================================================================
#[cfg(test)]
mod test{
use std::str;
use super::Trie;
use super::NodeType;
#[test]
fn valid_words_are_inserted() {
let mut trie = Trie::new();
assert_eq!(trie.contains("a"), None);
assert_eq!(trie.contains("abba"), None);
assert!(trie.insert("abba", 0));
assert_eq!(trie.contains("a"), Some(NodeType::Prefix));
assert_eq!(trie.contains("ab"), Some(NodeType::Prefix));
assert_eq!(trie.contains("abb"), Some(NodeType::Prefix));
assert_eq!(trie.contains("abba"), Some(NodeType::Word(0)));
}
#[test]
fn invalid_words_are_not_inserted() {
let mut trie = Trie::new();
let mut id = 0;
for s in ('\u{0}' as u8.. 'A' as u8)
.chain('[' as u8.. 'a' as u8)
.chain('{' as u8.. '\u{ff}' as u8)
.map(|b| unsafe { str::from_utf8_unchecked(&[b]) }.to_owned() ) {
id += 1;
assert!(!trie.insert(&s, id));
assert_eq!(trie.contains(&s), None);
}
}
#[test]
fn is_case_insensitive() {
let mut trie = Trie::new();
trie.insert("a", 0);
assert_eq!(trie.contains("a"), Some(NodeType::Word(0)));
assert_eq!(trie.contains("A"), Some(NodeType::Word(0)));
trie.insert("B", 1);
assert_eq!(trie.contains("b"), Some(NodeType::Word(1)));
assert_eq!(trie.contains("B"), Some(NodeType::Word(1)));
}
} |
pub struct TrieIterator<'a> { | random_line_split |
trie.rs | /* Copyright 2017 Joel Pedraza
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* A Radix 26 Trie
*
* I'd prefer if if each letter was represented as Enum rather than a u8 (for safety)
* Can they be used without sacrifing perf?
*/
use boggle_util;
use bitset::BitSet32;
use bitset::IndexIter32;
use std::mem;
type Node = Option<Box<Trie>>;
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum NodeType {
Prefix,
Word(usize),
}
#[derive(Debug)]
pub struct Trie {
node_type: NodeType,
children: [Node; boggle_util::ALPHABET_SIZE],
child_set: BitSet32,
}
impl Trie {
pub fn new() -> Self {
Trie {
node_type: NodeType::Prefix,
children: Default::default(),
child_set: BitSet32::new(),
}
}
pub fn node_type(&self) -> NodeType {
self.node_type
}
pub fn insert(&mut self, s: &str, id: usize) -> bool {
if boggle_util::is_alpha(s) {
self.ins(s.to_lowercase().as_bytes(), id);
true
} else {
false
}
}
#[inline]
fn ins(&mut self, s: &[u8], id: usize) -> () {
let first = boggle_util::ascii_byte_to_idx(s[0]);
if self.children[first].is_none() {
self.child_set.add(first as u32);
mem::replace(&mut (self.children[first]), Some(Box::new(Trie::new())));
}
let child = self.children[first].as_mut().unwrap();
if s.len() > 1 {
child.ins(&s[1..], id);
} else {
child.node_type = NodeType::Word(id);
}
}
#[allow(dead_code)]
pub fn contains(&self, s: &str) -> Option<NodeType> {
if boggle_util::is_alpha(s) {
self.cns(s.to_lowercase().as_bytes())
} else {
None
}
}
#[inline]
fn cns(&self, s: &[u8]) -> Option<NodeType> {
let first = boggle_util::ascii_byte_to_idx(s[0]);
if let Some(child) = self.children[first].as_ref() {
if s.len() == 1 {
Some(child.node_type)
} else |
} else {
None
}
}
pub fn iter(&self) -> TrieIterator {
TrieIterator::new(self)
}
}
pub struct TrieIterator<'a> {
trie: &'a Trie,
iter: IndexIter32<'a>,
}
impl<'a> TrieIterator<'a> {
fn new(trie: &'a Trie) -> TrieIterator<'a> {
TrieIterator {
trie: trie,
iter: trie.child_set.iter_ones(),
}
}
}
impl<'a> Iterator for TrieIterator<'a> {
type Item = (&'a Trie, u8);
fn next(&mut self) -> Option<(&'a Trie, u8)> {
match self.iter.next() {
Some(i) => {
match self.trie.children[i as usize] {
Some(ref trie) => Some((trie, i as u8)),
None => None
}
},
None => None
}
}
}
//==============================================================================
#[cfg(test)]
mod test{
use std::str;
use super::Trie;
use super::NodeType;
#[test]
fn valid_words_are_inserted() {
let mut trie = Trie::new();
assert_eq!(trie.contains("a"), None);
assert_eq!(trie.contains("abba"), None);
assert!(trie.insert("abba", 0));
assert_eq!(trie.contains("a"), Some(NodeType::Prefix));
assert_eq!(trie.contains("ab"), Some(NodeType::Prefix));
assert_eq!(trie.contains("abb"), Some(NodeType::Prefix));
assert_eq!(trie.contains("abba"), Some(NodeType::Word(0)));
}
#[test]
fn invalid_words_are_not_inserted() {
let mut trie = Trie::new();
let mut id = 0;
for s in ('\u{0}' as u8.. 'A' as u8)
.chain('[' as u8.. 'a' as u8)
.chain('{' as u8.. '\u{ff}' as u8)
.map(|b| unsafe { str::from_utf8_unchecked(&[b]) }.to_owned() ) {
id += 1;
assert!(!trie.insert(&s, id));
assert_eq!(trie.contains(&s), None);
}
}
#[test]
fn is_case_insensitive() {
let mut trie = Trie::new();
trie.insert("a", 0);
assert_eq!(trie.contains("a"), Some(NodeType::Word(0)));
assert_eq!(trie.contains("A"), Some(NodeType::Word(0)));
trie.insert("B", 1);
assert_eq!(trie.contains("b"), Some(NodeType::Word(1)));
assert_eq!(trie.contains("B"), Some(NodeType::Word(1)));
}
} | {
let rest = &s[1..];
child.cns(rest)
} | conditional_block |
unused-attr.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![deny(unused_attributes)]
#![allow(dead_code, unused_imports)]
#![feature(core, custom_attribute)]
#![foo] //~ ERROR unused attribute
#[foo] //~ ERROR unused attribute
extern crate core;
#[foo] //~ ERROR unused attribute
use std::collections;
#[foo] //~ ERROR unused attribute
extern "C" {
#[foo] //~ ERROR unused attribute
fn foo();
}
#[foo] //~ ERROR unused attribute
mod foo {
#[foo] //~ ERROR unused attribute
pub enum Foo {
#[foo] //~ ERROR unused attribute
Bar,
}
}
#[foo] //~ ERROR unused attribute
fn bar(f: foo::Foo) {
match f {
#[foo] //~ ERROR unused attribute
foo::Foo::Bar => |
}
}
#[foo] //~ ERROR unused attribute
struct Foo {
#[foo] //~ ERROR unused attribute
a: isize
}
#[foo] //~ ERROR unused attribute
trait Baz {
#[foo] //~ ERROR unused attribute
fn blah();
#[foo] //~ ERROR unused attribute
fn blah2() {}
}
fn main() {}
| {} | conditional_block |
unused-attr.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![deny(unused_attributes)]
#![allow(dead_code, unused_imports)]
#![feature(core, custom_attribute)]
#![foo] //~ ERROR unused attribute
#[foo] //~ ERROR unused attribute
extern crate core;
#[foo] //~ ERROR unused attribute
use std::collections;
#[foo] //~ ERROR unused attribute
extern "C" {
#[foo] //~ ERROR unused attribute
fn foo();
}
#[foo] //~ ERROR unused attribute
mod foo {
#[foo] //~ ERROR unused attribute
pub enum Foo {
#[foo] //~ ERROR unused attribute
Bar,
}
}
#[foo] //~ ERROR unused attribute
fn bar(f: foo::Foo) |
#[foo] //~ ERROR unused attribute
struct Foo {
#[foo] //~ ERROR unused attribute
a: isize
}
#[foo] //~ ERROR unused attribute
trait Baz {
#[foo] //~ ERROR unused attribute
fn blah();
#[foo] //~ ERROR unused attribute
fn blah2() {}
}
fn main() {}
| {
match f {
#[foo] //~ ERROR unused attribute
foo::Foo::Bar => {}
}
} | identifier_body |
unused-attr.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![deny(unused_attributes)]
#![allow(dead_code, unused_imports)]
#![feature(core, custom_attribute)]
#![foo] //~ ERROR unused attribute
#[foo] //~ ERROR unused attribute
extern crate core;
#[foo] //~ ERROR unused attribute
use std::collections;
#[foo] //~ ERROR unused attribute
extern "C" {
#[foo] //~ ERROR unused attribute
fn foo();
}
#[foo] //~ ERROR unused attribute
mod foo {
#[foo] //~ ERROR unused attribute
pub enum Foo {
#[foo] //~ ERROR unused attribute
Bar,
}
}
#[foo] //~ ERROR unused attribute
fn bar(f: foo::Foo) {
match f {
#[foo] //~ ERROR unused attribute
foo::Foo::Bar => {}
}
}
#[foo] //~ ERROR unused attribute
struct | {
#[foo] //~ ERROR unused attribute
a: isize
}
#[foo] //~ ERROR unused attribute
trait Baz {
#[foo] //~ ERROR unused attribute
fn blah();
#[foo] //~ ERROR unused attribute
fn blah2() {}
}
fn main() {}
| Foo | identifier_name |
unused-attr.rs | // Copyright 2014 The Rust Project Developers. See the 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.
#![deny(unused_attributes)]
#![allow(dead_code, unused_imports)]
#![feature(core, custom_attribute)]
#![foo] //~ ERROR unused attribute
#[foo] //~ ERROR unused attribute
extern crate core;
#[foo] //~ ERROR unused attribute
use std::collections;
#[foo] //~ ERROR unused attribute
extern "C" {
#[foo] //~ ERROR unused attribute
fn foo();
}
#[foo] //~ ERROR unused attribute
mod foo {
#[foo] //~ ERROR unused attribute
pub enum Foo {
#[foo] //~ ERROR unused attribute
Bar,
}
}
#[foo] //~ ERROR unused attribute
fn bar(f: foo::Foo) {
match f {
#[foo] //~ ERROR unused attribute
foo::Foo::Bar => {}
}
}
#[foo] //~ ERROR unused attribute
struct Foo {
#[foo] //~ ERROR unused attribute
a: isize
}
#[foo] //~ ERROR unused attribute
trait Baz {
#[foo] //~ ERROR unused attribute
fn blah();
#[foo] //~ ERROR unused attribute
fn blah2() {}
}
fn main() {} | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | random_line_split |
use-from-trait-xc.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:use_from_trait_xc.rs
extern crate use_from_trait_xc; |
fn main() {
} |
use use_from_trait_xc::Trait::foo; //~ ERROR cannot import from a trait or type implementation
//~^ ERROR failed to resolve import
use use_from_trait_xc::Foo::new; //~ ERROR cannot import from a trait or type implementation
//~^ ERROR failed to resolve import | random_line_split |
use-from-trait-xc.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:use_from_trait_xc.rs
extern crate use_from_trait_xc;
use use_from_trait_xc::Trait::foo; //~ ERROR cannot import from a trait or type implementation
//~^ ERROR failed to resolve import
use use_from_trait_xc::Foo::new; //~ ERROR cannot import from a trait or type implementation
//~^ ERROR failed to resolve import
fn main() | {
} | identifier_body |
|
use-from-trait-xc.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:use_from_trait_xc.rs
extern crate use_from_trait_xc;
use use_from_trait_xc::Trait::foo; //~ ERROR cannot import from a trait or type implementation
//~^ ERROR failed to resolve import
use use_from_trait_xc::Foo::new; //~ ERROR cannot import from a trait or type implementation
//~^ ERROR failed to resolve import
fn | () {
}
| main | identifier_name |
layout_collection.rs | extern crate wtftw;
use self::wtftw::config::GeneralConfig;
use self::wtftw::core::stack::Stack;
use self::wtftw::layout::Layout;
use self::wtftw::layout::LayoutMessage;
use self::wtftw::window_system::Rectangle;
use self::wtftw::window_system::Window;
use self::wtftw::window_system::WindowSystem;
pub struct LayoutCollection {
pub layouts: Vec<Box<Layout>>, | }
impl LayoutCollection {
pub fn new(layouts: Vec<Box<Layout>>) -> Box<Layout> {
Box::new(LayoutCollection {
layouts: layouts,
current: 0
})
}
}
impl Layout for LayoutCollection {
fn apply_layout(&mut self, window_system: &WindowSystem, screen: Rectangle, config: &GeneralConfig,
stack: &Option<Stack<Window>>) -> Vec<(Window, Rectangle)> {
self.layouts[self.current].apply_layout(window_system, screen, config, stack)
}
fn apply_message(&mut self, message: LayoutMessage, window_system: &WindowSystem,
stack: &Option<Stack<Window>>, config: &GeneralConfig) -> bool {
match message {
LayoutMessage::Next => {
self.layouts[self.current].unhook(window_system, stack, config);
self.current = (self.current + 1) % self.layouts.len();
true
}
LayoutMessage::Prev => {
self.layouts[self.current].unhook(window_system, stack, config);
self.current = (self.current + (self.layouts.len() - 1)) % self.layouts.len();
true
}
_ => self.layouts[self.current].apply_message(message, window_system, stack,
config)
}
}
fn description(&self) -> String {
self.layouts[self.current].description()
}
fn copy(&self) -> Box<Layout> {
Box::new(LayoutCollection {
current: self.current,
layouts: self.layouts.iter().map(|x| x.copy()).collect()
})
}
} | pub current: usize | random_line_split |
layout_collection.rs | extern crate wtftw;
use self::wtftw::config::GeneralConfig;
use self::wtftw::core::stack::Stack;
use self::wtftw::layout::Layout;
use self::wtftw::layout::LayoutMessage;
use self::wtftw::window_system::Rectangle;
use self::wtftw::window_system::Window;
use self::wtftw::window_system::WindowSystem;
pub struct | {
pub layouts: Vec<Box<Layout>>,
pub current: usize
}
impl LayoutCollection {
pub fn new(layouts: Vec<Box<Layout>>) -> Box<Layout> {
Box::new(LayoutCollection {
layouts: layouts,
current: 0
})
}
}
impl Layout for LayoutCollection {
fn apply_layout(&mut self, window_system: &WindowSystem, screen: Rectangle, config: &GeneralConfig,
stack: &Option<Stack<Window>>) -> Vec<(Window, Rectangle)> {
self.layouts[self.current].apply_layout(window_system, screen, config, stack)
}
fn apply_message(&mut self, message: LayoutMessage, window_system: &WindowSystem,
stack: &Option<Stack<Window>>, config: &GeneralConfig) -> bool {
match message {
LayoutMessage::Next => {
self.layouts[self.current].unhook(window_system, stack, config);
self.current = (self.current + 1) % self.layouts.len();
true
}
LayoutMessage::Prev => {
self.layouts[self.current].unhook(window_system, stack, config);
self.current = (self.current + (self.layouts.len() - 1)) % self.layouts.len();
true
}
_ => self.layouts[self.current].apply_message(message, window_system, stack,
config)
}
}
fn description(&self) -> String {
self.layouts[self.current].description()
}
fn copy(&self) -> Box<Layout> {
Box::new(LayoutCollection {
current: self.current,
layouts: self.layouts.iter().map(|x| x.copy()).collect()
})
}
}
| LayoutCollection | identifier_name |
layout_collection.rs | extern crate wtftw;
use self::wtftw::config::GeneralConfig;
use self::wtftw::core::stack::Stack;
use self::wtftw::layout::Layout;
use self::wtftw::layout::LayoutMessage;
use self::wtftw::window_system::Rectangle;
use self::wtftw::window_system::Window;
use self::wtftw::window_system::WindowSystem;
pub struct LayoutCollection {
pub layouts: Vec<Box<Layout>>,
pub current: usize
}
impl LayoutCollection {
pub fn new(layouts: Vec<Box<Layout>>) -> Box<Layout> {
Box::new(LayoutCollection {
layouts: layouts,
current: 0
})
}
}
impl Layout for LayoutCollection {
fn apply_layout(&mut self, window_system: &WindowSystem, screen: Rectangle, config: &GeneralConfig,
stack: &Option<Stack<Window>>) -> Vec<(Window, Rectangle)> {
self.layouts[self.current].apply_layout(window_system, screen, config, stack)
}
fn apply_message(&mut self, message: LayoutMessage, window_system: &WindowSystem,
stack: &Option<Stack<Window>>, config: &GeneralConfig) -> bool {
match message {
LayoutMessage::Next => {
self.layouts[self.current].unhook(window_system, stack, config);
self.current = (self.current + 1) % self.layouts.len();
true
}
LayoutMessage::Prev => |
_ => self.layouts[self.current].apply_message(message, window_system, stack,
config)
}
}
fn description(&self) -> String {
self.layouts[self.current].description()
}
fn copy(&self) -> Box<Layout> {
Box::new(LayoutCollection {
current: self.current,
layouts: self.layouts.iter().map(|x| x.copy()).collect()
})
}
}
| {
self.layouts[self.current].unhook(window_system, stack, config);
self.current = (self.current + (self.layouts.len() - 1)) % self.layouts.len();
true
} | conditional_block |
conversions_tests.rs | use std::convert::TryInto;
use hashing;
use crate::gen::build::bazel::remote::execution::v2 as remexec;
#[test]
fn from_our_digest() {
let our_digest = &hashing::Digest::new(
hashing::Fingerprint::from_hex_string(
"0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff",
)
.unwrap(),
10,
);
let converted: remexec::Digest = our_digest.into();
let want = remexec::Digest {
hash: "0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff".to_owned(),
size_bytes: 10,
};
assert_eq!(converted, want);
}
#[test]
fn from_bazel_digest() { | let bazel_digest = remexec::Digest {
hash: "0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff".to_owned(),
size_bytes: 10,
};
let converted: Result<hashing::Digest, String> = (&bazel_digest).try_into();
let want = hashing::Digest::new(
hashing::Fingerprint::from_hex_string(
"0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff",
)
.unwrap(),
10,
);
assert_eq!(converted, Ok(want));
}
#[test]
fn from_bad_bazel_digest() {
let bazel_digest = remexec::Digest {
hash: "0".to_owned(),
size_bytes: 10,
};
let converted: Result<hashing::Digest, String> = (&bazel_digest).try_into();
let err = converted.expect_err("Want Err converting bad digest");
assert!(
err.starts_with("Bad fingerprint in Digest \"0\":"),
"Bad error message: {}",
err
);
} | random_line_split |
|
conversions_tests.rs | use std::convert::TryInto;
use hashing;
use crate::gen::build::bazel::remote::execution::v2 as remexec;
#[test]
fn from_our_digest() |
#[test]
fn from_bazel_digest() {
let bazel_digest = remexec::Digest {
hash: "0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff".to_owned(),
size_bytes: 10,
};
let converted: Result<hashing::Digest, String> = (&bazel_digest).try_into();
let want = hashing::Digest::new(
hashing::Fingerprint::from_hex_string(
"0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff",
)
.unwrap(),
10,
);
assert_eq!(converted, Ok(want));
}
#[test]
fn from_bad_bazel_digest() {
let bazel_digest = remexec::Digest {
hash: "0".to_owned(),
size_bytes: 10,
};
let converted: Result<hashing::Digest, String> = (&bazel_digest).try_into();
let err = converted.expect_err("Want Err converting bad digest");
assert!(
err.starts_with("Bad fingerprint in Digest \"0\":"),
"Bad error message: {}",
err
);
}
| {
let our_digest = &hashing::Digest::new(
hashing::Fingerprint::from_hex_string(
"0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff",
)
.unwrap(),
10,
);
let converted: remexec::Digest = our_digest.into();
let want = remexec::Digest {
hash: "0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff".to_owned(),
size_bytes: 10,
};
assert_eq!(converted, want);
} | identifier_body |
conversions_tests.rs | use std::convert::TryInto;
use hashing;
use crate::gen::build::bazel::remote::execution::v2 as remexec;
#[test]
fn from_our_digest() {
let our_digest = &hashing::Digest::new(
hashing::Fingerprint::from_hex_string(
"0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff",
)
.unwrap(),
10,
);
let converted: remexec::Digest = our_digest.into();
let want = remexec::Digest {
hash: "0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff".to_owned(),
size_bytes: 10,
};
assert_eq!(converted, want);
}
#[test]
fn | () {
let bazel_digest = remexec::Digest {
hash: "0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff".to_owned(),
size_bytes: 10,
};
let converted: Result<hashing::Digest, String> = (&bazel_digest).try_into();
let want = hashing::Digest::new(
hashing::Fingerprint::from_hex_string(
"0123456789abcdeffedcba98765432100000000000000000ffffffffffffffff",
)
.unwrap(),
10,
);
assert_eq!(converted, Ok(want));
}
#[test]
fn from_bad_bazel_digest() {
let bazel_digest = remexec::Digest {
hash: "0".to_owned(),
size_bytes: 10,
};
let converted: Result<hashing::Digest, String> = (&bazel_digest).try_into();
let err = converted.expect_err("Want Err converting bad digest");
assert!(
err.starts_with("Bad fingerprint in Digest \"0\":"),
"Bad error message: {}",
err
);
}
| from_bazel_digest | identifier_name |
siphash24.rs | //! `SipHash-2-4`
use ffi;
use libc::c_ulonglong;
use randombytes::randombytes_into;
pub const HASHBYTES: usize = ffi::crypto_shorthash_siphash24_BYTES;
pub const KEYBYTES: usize = ffi::crypto_shorthash_siphash24_KEYBYTES;
/// Digest-structure
#[derive(Copy)]
pub struct Digest(pub [u8; HASHBYTES]);
newtype_clone!(Digest);
newtype_impl!(Digest, HASHBYTES);
/// Key
///
/// When a `Key` goes out of scope its contents
/// will be zeroed out
pub struct Key(pub [u8; KEYBYTES]);
newtype_drop!(Key);
newtype_clone!(Key);
newtype_impl!(Key, KEYBYTES);
/// `gen_key()` randomly generates a key for shorthash
///
/// THREAD SAFETY: `gen_key()` is thread-safe provided that you have
/// called `sodiumoxide::init()` once before using any other function
/// from sodiumoxide.
pub fn gen_key() -> Key {
let mut k = [0; KEYBYTES];
randombytes_into(&mut k);
Key(k)
}
/// `shorthash` hashes a message `m` under a key `k`. It
/// returns a hash `h`.
pub fn shorthash(m: &[u8],
&Key(ref k): &Key) -> Digest {
unsafe {
let mut h = [0; HASHBYTES];
ffi::crypto_shorthash_siphash24(&mut h, m.as_ptr(),
m.len() as c_ulonglong,
k);
Digest(h)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_vectors() {
let maxlen = 64;
let mut m = Vec::with_capacity(64);
for i in (0usize..64) {
m.push(i as u8);
}
let h_expecteds = [[0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72]
,[0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74]
,[0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d]
,[0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85]
,[0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf]
,[0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18]
,[0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb]
,[0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab]
,[0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93]
,[0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e]
,[0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a]
,[0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4]
,[0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75]
,[0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14]
,[0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7]
,[0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1]
,[0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f]
,[0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69]
,[0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b]
,[0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb]
,[0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe]
,[0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0]
,[0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93]
,[0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8]
,[0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8]
,[0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc]
,[0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17]
,[0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f]
,[0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde]
,[0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6]
,[0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad]
,[0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32]
,[0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71]
,[0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7]
,[0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12]
,[0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15]
,[0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31]
,[0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02]
,[0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca]
,[0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a]
,[0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e]
,[0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad]
,[0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18]
,[0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4]
,[0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9]
,[0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9]
,[0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb]
,[0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0]
,[0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6]
,[0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7]
,[0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee]
,[0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1]
,[0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a]
,[0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81]
,[0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f]
,[0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24]
,[0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7]
,[0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea]
,[0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60]
,[0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66]
,[0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c]
,[0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f]
,[0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5]
,[0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95]];
let k = Key([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
for i in (0usize..maxlen) {
let Digest(h) = shorthash(&m[..i], &k);
assert!(h == h_expecteds[i]);
}
}
}
#[cfg(feature = "benchmarks")]
#[cfg(test)]
mod bench {
extern crate test;
use randombytes::randombytes;
use super::*;
const BENCH_SIZES: [usize; 14] = [0, 1, 2, 4, 8, 16, 32, 64,
128, 256, 512, 1024, 2048, 4096];
#[bench]
fn | (b: &mut test::Bencher) {
let k = gen_key();
let ms: Vec<Vec<u8>> = BENCH_SIZES.iter().map(|s| {
randombytes(*s)
}).collect();
b.iter(|| {
for m in ms.iter() {
shorthash(m, &k);
}
});
}
}
| bench_shorthash | identifier_name |
siphash24.rs | //! `SipHash-2-4`
use ffi;
use libc::c_ulonglong;
use randombytes::randombytes_into;
pub const HASHBYTES: usize = ffi::crypto_shorthash_siphash24_BYTES;
pub const KEYBYTES: usize = ffi::crypto_shorthash_siphash24_KEYBYTES;
/// Digest-structure
#[derive(Copy)]
pub struct Digest(pub [u8; HASHBYTES]);
newtype_clone!(Digest);
newtype_impl!(Digest, HASHBYTES);
/// Key
///
/// When a `Key` goes out of scope its contents
/// will be zeroed out
pub struct Key(pub [u8; KEYBYTES]);
newtype_drop!(Key);
newtype_clone!(Key);
newtype_impl!(Key, KEYBYTES);
/// `gen_key()` randomly generates a key for shorthash
///
/// THREAD SAFETY: `gen_key()` is thread-safe provided that you have
/// called `sodiumoxide::init()` once before using any other function
/// from sodiumoxide.
pub fn gen_key() -> Key {
let mut k = [0; KEYBYTES];
randombytes_into(&mut k);
Key(k)
}
/// `shorthash` hashes a message `m` under a key `k`. It
/// returns a hash `h`.
pub fn shorthash(m: &[u8],
&Key(ref k): &Key) -> Digest {
unsafe {
let mut h = [0; HASHBYTES];
ffi::crypto_shorthash_siphash24(&mut h, m.as_ptr(),
m.len() as c_ulonglong,
k);
Digest(h)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_vectors() {
let maxlen = 64;
let mut m = Vec::with_capacity(64);
for i in (0usize..64) {
m.push(i as u8);
}
let h_expecteds = [[0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72]
,[0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74]
,[0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d]
,[0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85]
,[0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf]
,[0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18]
,[0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb]
,[0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab]
,[0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93]
,[0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e]
,[0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a]
,[0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4]
,[0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75]
,[0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14]
,[0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7]
,[0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1]
,[0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f]
,[0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69]
,[0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b]
,[0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb]
,[0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe]
,[0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0]
,[0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93]
,[0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8]
,[0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8]
,[0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc]
,[0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17]
,[0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f]
,[0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde]
,[0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6]
,[0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad]
,[0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32]
,[0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71]
,[0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7]
,[0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12]
,[0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15]
,[0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31]
,[0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02]
,[0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca]
,[0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a]
,[0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e]
,[0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad]
,[0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18]
,[0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4]
,[0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9]
,[0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9]
,[0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb]
,[0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0]
,[0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6]
,[0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7] | ,[0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f]
,[0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24]
,[0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7]
,[0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea]
,[0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60]
,[0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66]
,[0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c]
,[0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f]
,[0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5]
,[0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95]];
let k = Key([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
for i in (0usize..maxlen) {
let Digest(h) = shorthash(&m[..i], &k);
assert!(h == h_expecteds[i]);
}
}
}
#[cfg(feature = "benchmarks")]
#[cfg(test)]
mod bench {
extern crate test;
use randombytes::randombytes;
use super::*;
const BENCH_SIZES: [usize; 14] = [0, 1, 2, 4, 8, 16, 32, 64,
128, 256, 512, 1024, 2048, 4096];
#[bench]
fn bench_shorthash(b: &mut test::Bencher) {
let k = gen_key();
let ms: Vec<Vec<u8>> = BENCH_SIZES.iter().map(|s| {
randombytes(*s)
}).collect();
b.iter(|| {
for m in ms.iter() {
shorthash(m, &k);
}
});
}
} | ,[0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee]
,[0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1]
,[0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a]
,[0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81] | random_line_split |
siphash24.rs | //! `SipHash-2-4`
use ffi;
use libc::c_ulonglong;
use randombytes::randombytes_into;
pub const HASHBYTES: usize = ffi::crypto_shorthash_siphash24_BYTES;
pub const KEYBYTES: usize = ffi::crypto_shorthash_siphash24_KEYBYTES;
/// Digest-structure
#[derive(Copy)]
pub struct Digest(pub [u8; HASHBYTES]);
newtype_clone!(Digest);
newtype_impl!(Digest, HASHBYTES);
/// Key
///
/// When a `Key` goes out of scope its contents
/// will be zeroed out
pub struct Key(pub [u8; KEYBYTES]);
newtype_drop!(Key);
newtype_clone!(Key);
newtype_impl!(Key, KEYBYTES);
/// `gen_key()` randomly generates a key for shorthash
///
/// THREAD SAFETY: `gen_key()` is thread-safe provided that you have
/// called `sodiumoxide::init()` once before using any other function
/// from sodiumoxide.
pub fn gen_key() -> Key {
let mut k = [0; KEYBYTES];
randombytes_into(&mut k);
Key(k)
}
/// `shorthash` hashes a message `m` under a key `k`. It
/// returns a hash `h`.
pub fn shorthash(m: &[u8],
&Key(ref k): &Key) -> Digest {
unsafe {
let mut h = [0; HASHBYTES];
ffi::crypto_shorthash_siphash24(&mut h, m.as_ptr(),
m.len() as c_ulonglong,
k);
Digest(h)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_vectors() {
let maxlen = 64;
let mut m = Vec::with_capacity(64);
for i in (0usize..64) {
m.push(i as u8);
}
let h_expecteds = [[0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72]
,[0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74]
,[0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d]
,[0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85]
,[0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf]
,[0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18]
,[0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb]
,[0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab]
,[0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93]
,[0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e]
,[0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a]
,[0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4]
,[0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75]
,[0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14]
,[0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7]
,[0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1]
,[0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f]
,[0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69]
,[0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b]
,[0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb]
,[0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe]
,[0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0]
,[0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93]
,[0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8]
,[0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8]
,[0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc]
,[0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17]
,[0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f]
,[0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde]
,[0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6]
,[0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad]
,[0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32]
,[0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71]
,[0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7]
,[0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12]
,[0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15]
,[0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31]
,[0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02]
,[0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca]
,[0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a]
,[0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e]
,[0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad]
,[0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18]
,[0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4]
,[0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9]
,[0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9]
,[0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb]
,[0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0]
,[0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6]
,[0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7]
,[0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee]
,[0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1]
,[0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a]
,[0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81]
,[0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f]
,[0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24]
,[0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7]
,[0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea]
,[0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60]
,[0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66]
,[0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c]
,[0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f]
,[0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5]
,[0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95]];
let k = Key([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
for i in (0usize..maxlen) {
let Digest(h) = shorthash(&m[..i], &k);
assert!(h == h_expecteds[i]);
}
}
}
#[cfg(feature = "benchmarks")]
#[cfg(test)]
mod bench {
extern crate test;
use randombytes::randombytes;
use super::*;
const BENCH_SIZES: [usize; 14] = [0, 1, 2, 4, 8, 16, 32, 64,
128, 256, 512, 1024, 2048, 4096];
#[bench]
fn bench_shorthash(b: &mut test::Bencher) |
}
| {
let k = gen_key();
let ms: Vec<Vec<u8>> = BENCH_SIZES.iter().map(|s| {
randombytes(*s)
}).collect();
b.iter(|| {
for m in ms.iter() {
shorthash(m, &k);
}
});
} | identifier_body |
u32.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.
//! Operations and constants for `u32`
mod inst {
use num::{Primitive, BitCount};
use unstable::intrinsics;
pub type T = u32;
#[allow(non_camel_case_types)]
pub type T_SIGNED = i32;
pub static bits: uint = 32;
impl Primitive for u32 {
#[inline(always)]
fn bits() -> uint { 32 }
#[inline(always)]
fn bytes() -> uint { Primitive::bits::<u32>() / 8 }
}
impl BitCount for u32 {
/// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic.
#[inline(always)]
fn population_count(&self) -> u32 { unsafe { intrinsics::ctpop32(*self as i32) as u32 } }
/// Counts the number of leading zeros. Wraps LLVM's `ctlp` intrinsic.
#[inline(always)]
fn leading_zeros(&self) -> u32 { unsafe { intrinsics::ctlz32(*self as i32) as u32 } }
/// Counts the number of trailing zeros. Wraps LLVM's `cttp` intrinsic.
#[inline(always)]
fn trailing_zeros(&self) -> u32 { unsafe { intrinsics::cttz32(*self as i32) as u32 } } | } | } | random_line_split |
u32.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.
//! Operations and constants for `u32`
mod inst {
use num::{Primitive, BitCount};
use unstable::intrinsics;
pub type T = u32;
#[allow(non_camel_case_types)]
pub type T_SIGNED = i32;
pub static bits: uint = 32;
impl Primitive for u32 {
#[inline(always)]
fn bits() -> uint { 32 }
#[inline(always)]
fn bytes() -> uint { Primitive::bits::<u32>() / 8 }
}
impl BitCount for u32 {
/// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic.
#[inline(always)]
fn population_count(&self) -> u32 |
/// Counts the number of leading zeros. Wraps LLVM's `ctlp` intrinsic.
#[inline(always)]
fn leading_zeros(&self) -> u32 { unsafe { intrinsics::ctlz32(*self as i32) as u32 } }
/// Counts the number of trailing zeros. Wraps LLVM's `cttp` intrinsic.
#[inline(always)]
fn trailing_zeros(&self) -> u32 { unsafe { intrinsics::cttz32(*self as i32) as u32 } }
}
}
| { unsafe { intrinsics::ctpop32(*self as i32) as u32 } } | identifier_body |
u32.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.
//! Operations and constants for `u32`
mod inst {
use num::{Primitive, BitCount};
use unstable::intrinsics;
pub type T = u32;
#[allow(non_camel_case_types)]
pub type T_SIGNED = i32;
pub static bits: uint = 32;
impl Primitive for u32 {
#[inline(always)]
fn bits() -> uint { 32 }
#[inline(always)]
fn bytes() -> uint { Primitive::bits::<u32>() / 8 }
}
impl BitCount for u32 {
/// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic.
#[inline(always)]
fn population_count(&self) -> u32 { unsafe { intrinsics::ctpop32(*self as i32) as u32 } }
/// Counts the number of leading zeros. Wraps LLVM's `ctlp` intrinsic.
#[inline(always)]
fn leading_zeros(&self) -> u32 { unsafe { intrinsics::ctlz32(*self as i32) as u32 } }
/// Counts the number of trailing zeros. Wraps LLVM's `cttp` intrinsic.
#[inline(always)]
fn | (&self) -> u32 { unsafe { intrinsics::cttz32(*self as i32) as u32 } }
}
}
| trailing_zeros | identifier_name |
mod.rs |
fn create_plugin_jail(root: &Path, log_failures: bool, seccomp_policy: &Path) -> Result<Minijail> {
// All child jails run in a new user namespace without any users mapped,
// they run as nobody unless otherwise configured.
let mut j = Minijail::new().context("failed to create jail")?;
j.namespace_pids();
j.namespace_user();
j.uidmap(&format!("0 {0} 1", geteuid()))
.context("failed to set uidmap for jail")?;
j.gidmap(&format!("0 {0} 1", getegid()))
.context("failed to set gidmap for jail")?;
j.namespace_user_disable_setgroups();
// Don't need any capabilities.
j.use_caps(0);
// Create a new mount namespace with an empty root FS.
j.namespace_vfs();
j.enter_pivot_root(root)
.context("failed to set jail pivot root")?;
// Run in an empty network namespace.
j.namespace_net();
j.no_new_privs();
// By default we'll prioritize using the pre-compiled.bpf over the.policy
// file (the.bpf is expected to be compiled using "trap" as the failure
// behavior instead of the default "kill" behavior).
// Refer to the code comment for the "seccomp-log-failures"
// command-line parameter for an explanation about why the |log_failures|
// flag forces the use of.policy files (and the build-time alternative to
// this run-time flag).
let bpf_policy_file = seccomp_policy.with_extension("bpf");
if bpf_policy_file.exists() &&!log_failures {
j.parse_seccomp_program(&bpf_policy_file)
.context("failed to parse jail seccomp BPF program")?;
} else {
// Use TSYNC only for the side effect of it using SECCOMP_RET_TRAP,
// which will correctly kill the entire device process if a worker
// thread commits a seccomp violation.
j.set_seccomp_filter_tsync();
if log_failures {
j.log_seccomp_filter_failures();
}
j.parse_seccomp_filters(&seccomp_policy.with_extension("policy"))
.context("failed to parse jail seccomp filter")?;
}
j.use_seccomp_filter();
// Don't do init setup.
j.run_as_init();
// Create a tmpfs in the plugin's root directory so that we can bind mount it's executable
// file into it. The size=67108864 is size=64*1024*1024 or size=64MB.
j.mount_with_data(
Path::new("none"),
Path::new("/"),
"tmpfs",
(MS_NOSUID | MS_NODEV | MS_NOEXEC) as usize,
"size=67108864",
)
.context("failed to mount root")?;
// Because we requested to "run as init", minijail will not mount /proc for us even though
// plugin will be running in its own PID namespace, so we have to mount it ourselves.
j.mount(
Path::new("proc"),
Path::new("/proc"),
"proc",
(MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_RDONLY) as usize,
)
.context("failed to mount proc")?;
Ok(j)
}
/// Each `PluginObject` represents one object that was instantiated by the guest using the `Create`
/// request.
///
/// Each such object has an ID associated with it that exists in an ID space shared by every variant
/// of `PluginObject`. This allows all the objects to be indexed in a single map, and allows for a
/// common destroy method.
///
/// In addition to the destory method, each object may have methods specific to its variant type.
/// These variant methods must be done by matching the variant to the expected type for that method.
/// For example, getting the dirty log from a `Memory` object starting with an ID:
///
/// ```ignore
/// match objects.get(&request_id) {
/// Some(&PluginObject::Memory { slot, length }) => vm.get_dirty_log(slot, &mut dirty_log[..]),
/// _ => return Err(SysError::new(ENOENT)),
/// }
/// ```
enum PluginObject {
IoEvent {
evt: Event,
addr: IoeventAddress,
length: u32,
datamatch: u64,
},
Memory {
slot: u32,
length: usize,
},
IrqEvent {
irq_id: u32,
evt: Event,
},
}
impl PluginObject {
fn destroy(self, vm: &mut Vm) -> SysResult<()> {
match self {
PluginObject::IoEvent {
evt,
addr,
length,
datamatch,
} => match length {
0 => vm.unregister_ioevent(&evt, addr, Datamatch::AnyLength),
1 => vm.unregister_ioevent(&evt, addr, Datamatch::U8(Some(datamatch as u8))),
2 => vm.unregister_ioevent(&evt, addr, Datamatch::U16(Some(datamatch as u16))),
4 => vm.unregister_ioevent(&evt, addr, Datamatch::U32(Some(datamatch as u32))),
8 => vm.unregister_ioevent(&evt, addr, Datamatch::U64(Some(datamatch as u64))),
_ => Err(SysError::new(EINVAL)),
},
PluginObject::Memory { slot,.. } => vm.remove_memory_region(slot).and(Ok(())),
PluginObject::IrqEvent { irq_id, evt } => vm.unregister_irqfd(&evt, irq_id),
}
}
}
pub fn run_vcpus(
kvm: &Kvm,
vm: &Vm,
plugin: &Process,
vcpu_count: u32,
kill_signaled: &Arc<AtomicBool>,
exit_evt: &Event,
vcpu_handles: &mut Vec<thread::JoinHandle<()>>,
) -> Result<()> {
let vcpu_thread_barrier = Arc::new(Barrier::new((vcpu_count) as usize));
let use_kvm_signals =!kvm.check_extension(Cap::ImmediateExit);
// If we need to force a vcpu to exit from a VM then a SIGRTMIN signal is sent
// to that vcpu's thread. If KVM is running the VM then it'll return -EINTR.
// An issue is what to do when KVM isn't running the VM (where we could be
// in the kernel or in the app).
//
// If KVM supports "immediate exit" then we set a signal handler that will
// set the |immediate_exit| flag that tells KVM to return -EINTR before running
// the VM.
//
// If KVM doesn't support immediate exit then we'll block SIGRTMIN in the app
// and tell KVM to unblock SIGRTMIN before running the VM (at which point a blocked
// signal might get asserted). There's overhead to have KVM unblock and re-block
// SIGRTMIN each time it runs the VM, so this mode should be avoided.
if use_kvm_signals {
unsafe {
extern "C" fn handle_signal(_: c_int) {}
// Our signal handler does nothing and is trivially async signal safe.
// We need to install this signal handler even though we do block
// the signal below, to ensure that this signal will interrupt
// execution of KVM_RUN (this is implementation issue).
register_rt_signal_handler(SIGRTMIN() + 0, handle_signal)
.expect("failed to register vcpu signal handler");
}
// We do not really want the signal handler to run...
block_signal(SIGRTMIN() + 0).expect("failed to block signal");
} else {
unsafe {
extern "C" fn handle_signal(_: c_int) {
Vcpu::set_local_immediate_exit(true);
}
register_rt_signal_handler(SIGRTMIN() + 0, handle_signal)
.expect("failed to register vcpu signal handler");
}
}
for cpu_id in 0..vcpu_count {
let kill_signaled = kill_signaled.clone();
let vcpu_thread_barrier = vcpu_thread_barrier.clone();
let vcpu_exit_evt = exit_evt.try_clone().context("failed to clone event")?;
let vcpu_plugin = plugin.create_vcpu(cpu_id)?;
let vcpu = Vcpu::new(cpu_id as c_ulong, kvm, vm).context("error creating vcpu")?;
vcpu_handles.push(
thread::Builder::new()
.name(format!("crosvm_vcpu{}", cpu_id))
.spawn(move || {
if use_kvm_signals {
// Tell KVM to not block anything when entering kvm run
// because we will be using first RT signal to kick the VCPU.
vcpu.set_signal_mask(&[])
.expect("failed to set up KVM VCPU signal mask");
}
if let Err(e) = enable_core_scheduling() {
error!("Failed to enable core scheduling: {}", e);
}
let vcpu = vcpu
.to_runnable(Some(SIGRTMIN() + 0))
.expect("Failed to set thread id");
let res = vcpu_plugin.init(&vcpu);
vcpu_thread_barrier.wait();
if let Err(e) = res {
error!("failed to initialize vcpu {}: {}", cpu_id, e);
} else {
loop {
let mut interrupted_by_signal = false;
let run_res = vcpu.run();
match run_res {
Ok(run) => match run {
VcpuExit::IoIn { port, mut size } => {
let mut data = [0; 256];
if size > data.len() {
error!(
"unsupported IoIn size of {} bytes at port {:#x}",
size, port
);
size = data.len();
}
vcpu_plugin.io_read(port as u64, &mut data[..size], &vcpu);
if let Err(e) = vcpu.set_data(&data[..size]) {
error!(
"failed to set return data for IoIn at port {:#x}: {}",
port, e
);
}
}
VcpuExit::IoOut {
port,
mut size,
data,
} => {
if size > data.len() {
error!("unsupported IoOut size of {} bytes at port {:#x}", size, port);
size = data.len();
}
vcpu_plugin.io_write(port as u64, &data[..size], &vcpu);
}
VcpuExit::MmioRead { address, size } => {
let mut data = [0; 8];
vcpu_plugin.mmio_read(
address as u64,
&mut data[..size],
&vcpu,
);
// Setting data for mmio can not fail.
let _ = vcpu.set_data(&data[..size]);
}
VcpuExit::MmioWrite {
address,
size,
data,
} => {
vcpu_plugin.mmio_write(
address as u64,
&data[..size],
&vcpu,
);
}
VcpuExit::HypervHcall { input, params } => {
let mut data = [0; 8];
vcpu_plugin.hyperv_call(input, params, &mut data, &vcpu);
// Setting data for hyperv call can not fail.
let _ = vcpu.set_data(&data);
}
VcpuExit::HypervSynic {
msr,
control,
evt_page,
msg_page,
} => {
vcpu_plugin
.hyperv_synic(msr, control, evt_page, msg_page, &vcpu);
}
VcpuExit::Hlt => break,
VcpuExit::Shutdown => break,
VcpuExit::InternalError => {
error!("vcpu {} has internal error", cpu_id);
break;
}
r => warn!("unexpected vcpu exit: {:?}", r),
},
Err(e) => match e.errno() {
EINTR => interrupted_by_signal = true,
EAGAIN => {}
_ => {
error!("vcpu hit unknown error: {}", e);
break;
}
},
}
if kill_signaled.load(Ordering::SeqCst) {
break;
}
// Only handle the pause request if kvm reported that it was
// interrupted by a signal. This helps to entire that KVM has had a chance
// to finish emulating any IO that may have immediately happened.
// If we eagerly check pre_run() then any IO that we
// just reported to the plugin won't have been processed yet by KVM.
// Not eagerly calling pre_run() also helps to reduce
// any overhead from checking if a pause request is pending.
// The assumption is that pause requests aren't common
// or frequent so it's better to optimize for the non-pause execution paths.
if interrupted_by_signal {
if use_kvm_signals {
clear_signal(SIGRTMIN() + 0)
.expect("failed to clear pending signal");
| {
match e {
MmapError::SystemCallFailed(e) => e,
_ => SysError::new(EINVAL),
}
} | identifier_body |
|
mod.rs | has an ID associated with it that exists in an ID space shared by every variant
/// of `PluginObject`. This allows all the objects to be indexed in a single map, and allows for a
/// common destroy method.
///
/// In addition to the destory method, each object may have methods specific to its variant type.
/// These variant methods must be done by matching the variant to the expected type for that method.
/// For example, getting the dirty log from a `Memory` object starting with an ID:
///
/// ```ignore
/// match objects.get(&request_id) {
/// Some(&PluginObject::Memory { slot, length }) => vm.get_dirty_log(slot, &mut dirty_log[..]),
/// _ => return Err(SysError::new(ENOENT)),
/// }
/// ```
enum PluginObject {
IoEvent {
evt: Event,
addr: IoeventAddress,
length: u32,
datamatch: u64,
},
Memory {
slot: u32,
length: usize,
},
IrqEvent {
irq_id: u32,
evt: Event,
},
}
impl PluginObject {
fn destroy(self, vm: &mut Vm) -> SysResult<()> {
match self {
PluginObject::IoEvent {
evt,
addr,
length,
datamatch,
} => match length {
0 => vm.unregister_ioevent(&evt, addr, Datamatch::AnyLength),
1 => vm.unregister_ioevent(&evt, addr, Datamatch::U8(Some(datamatch as u8))),
2 => vm.unregister_ioevent(&evt, addr, Datamatch::U16(Some(datamatch as u16))),
4 => vm.unregister_ioevent(&evt, addr, Datamatch::U32(Some(datamatch as u32))),
8 => vm.unregister_ioevent(&evt, addr, Datamatch::U64(Some(datamatch as u64))),
_ => Err(SysError::new(EINVAL)),
},
PluginObject::Memory { slot,.. } => vm.remove_memory_region(slot).and(Ok(())),
PluginObject::IrqEvent { irq_id, evt } => vm.unregister_irqfd(&evt, irq_id),
}
}
}
pub fn run_vcpus(
kvm: &Kvm,
vm: &Vm,
plugin: &Process,
vcpu_count: u32,
kill_signaled: &Arc<AtomicBool>,
exit_evt: &Event,
vcpu_handles: &mut Vec<thread::JoinHandle<()>>,
) -> Result<()> {
let vcpu_thread_barrier = Arc::new(Barrier::new((vcpu_count) as usize));
let use_kvm_signals =!kvm.check_extension(Cap::ImmediateExit);
// If we need to force a vcpu to exit from a VM then a SIGRTMIN signal is sent
// to that vcpu's thread. If KVM is running the VM then it'll return -EINTR.
// An issue is what to do when KVM isn't running the VM (where we could be
// in the kernel or in the app).
//
// If KVM supports "immediate exit" then we set a signal handler that will
// set the |immediate_exit| flag that tells KVM to return -EINTR before running
// the VM.
//
// If KVM doesn't support immediate exit then we'll block SIGRTMIN in the app
// and tell KVM to unblock SIGRTMIN before running the VM (at which point a blocked
// signal might get asserted). There's overhead to have KVM unblock and re-block
// SIGRTMIN each time it runs the VM, so this mode should be avoided.
if use_kvm_signals {
unsafe {
extern "C" fn handle_signal(_: c_int) {}
// Our signal handler does nothing and is trivially async signal safe.
// We need to install this signal handler even though we do block
// the signal below, to ensure that this signal will interrupt
// execution of KVM_RUN (this is implementation issue).
register_rt_signal_handler(SIGRTMIN() + 0, handle_signal)
.expect("failed to register vcpu signal handler");
}
// We do not really want the signal handler to run...
block_signal(SIGRTMIN() + 0).expect("failed to block signal");
} else {
unsafe {
extern "C" fn handle_signal(_: c_int) {
Vcpu::set_local_immediate_exit(true);
}
register_rt_signal_handler(SIGRTMIN() + 0, handle_signal)
.expect("failed to register vcpu signal handler");
}
}
for cpu_id in 0..vcpu_count {
let kill_signaled = kill_signaled.clone();
let vcpu_thread_barrier = vcpu_thread_barrier.clone();
let vcpu_exit_evt = exit_evt.try_clone().context("failed to clone event")?;
let vcpu_plugin = plugin.create_vcpu(cpu_id)?;
let vcpu = Vcpu::new(cpu_id as c_ulong, kvm, vm).context("error creating vcpu")?;
vcpu_handles.push(
thread::Builder::new()
.name(format!("crosvm_vcpu{}", cpu_id))
.spawn(move || {
if use_kvm_signals {
// Tell KVM to not block anything when entering kvm run
// because we will be using first RT signal to kick the VCPU.
vcpu.set_signal_mask(&[])
.expect("failed to set up KVM VCPU signal mask");
}
if let Err(e) = enable_core_scheduling() {
error!("Failed to enable core scheduling: {}", e);
}
let vcpu = vcpu
.to_runnable(Some(SIGRTMIN() + 0)) |
let res = vcpu_plugin.init(&vcpu);
vcpu_thread_barrier.wait();
if let Err(e) = res {
error!("failed to initialize vcpu {}: {}", cpu_id, e);
} else {
loop {
let mut interrupted_by_signal = false;
let run_res = vcpu.run();
match run_res {
Ok(run) => match run {
VcpuExit::IoIn { port, mut size } => {
let mut data = [0; 256];
if size > data.len() {
error!(
"unsupported IoIn size of {} bytes at port {:#x}",
size, port
);
size = data.len();
}
vcpu_plugin.io_read(port as u64, &mut data[..size], &vcpu);
if let Err(e) = vcpu.set_data(&data[..size]) {
error!(
"failed to set return data for IoIn at port {:#x}: {}",
port, e
);
}
}
VcpuExit::IoOut {
port,
mut size,
data,
} => {
if size > data.len() {
error!("unsupported IoOut size of {} bytes at port {:#x}", size, port);
size = data.len();
}
vcpu_plugin.io_write(port as u64, &data[..size], &vcpu);
}
VcpuExit::MmioRead { address, size } => {
let mut data = [0; 8];
vcpu_plugin.mmio_read(
address as u64,
&mut data[..size],
&vcpu,
);
// Setting data for mmio can not fail.
let _ = vcpu.set_data(&data[..size]);
}
VcpuExit::MmioWrite {
address,
size,
data,
} => {
vcpu_plugin.mmio_write(
address as u64,
&data[..size],
&vcpu,
);
}
VcpuExit::HypervHcall { input, params } => {
let mut data = [0; 8];
vcpu_plugin.hyperv_call(input, params, &mut data, &vcpu);
// Setting data for hyperv call can not fail.
let _ = vcpu.set_data(&data);
}
VcpuExit::HypervSynic {
msr,
control,
evt_page,
msg_page,
} => {
vcpu_plugin
.hyperv_synic(msr, control, evt_page, msg_page, &vcpu);
}
VcpuExit::Hlt => break,
VcpuExit::Shutdown => break,
VcpuExit::InternalError => {
error!("vcpu {} has internal error", cpu_id);
break;
}
r => warn!("unexpected vcpu exit: {:?}", r),
},
Err(e) => match e.errno() {
EINTR => interrupted_by_signal = true,
EAGAIN => {}
_ => {
error!("vcpu hit unknown error: {}", e);
break;
}
},
}
if kill_signaled.load(Ordering::SeqCst) {
break;
}
// Only handle the pause request if kvm reported that it was
// interrupted by a signal. This helps to entire that KVM has had a chance
// to finish emulating any IO that may have immediately happened.
// If we eagerly check pre_run() then any IO that we
// just reported to the plugin won't have been processed yet by KVM.
// Not eagerly calling pre_run() also helps to reduce
// any overhead from checking if a pause request is pending.
// The assumption is that pause requests aren't common
// or frequent so it's better to optimize for the non-pause execution paths.
if interrupted_by_signal {
if use_kvm_signals {
clear_signal(SIGRTMIN() + 0)
.expect("failed to clear pending signal");
} else {
vcpu.set_immediate_exit(false);
}
if let Err(e) = vcpu_plugin.pre_run(&vcpu) {
error!("failed to process pause on vcpu {}: {}", cpu_id, e);
break;
}
}
}
}
vcpu_exit_evt
.write(1)
.expect("failed to signal vcpu exit event");
})
.context("error spawning vcpu thread")?,
);
}
Ok(())
}
#[derive(PollToken)]
enum Token {
Exit,
ChildSignal,
Stderr,
Plugin { index: usize },
}
/// Run a VM with a plugin process specified by `cfg`.
///
/// Not every field of `cfg` will be used. In particular, most field that pertain to a specific
/// device are ignored because the plugin is responsible for emulating hardware.
pub fn run_config(cfg: Config) -> Result<()> {
info!("crosvm starting plugin process");
// Masking signals is inherently dangerous, since this can persist across clones/execs. Do this
// before any jailed devices have been spawned, so that we can catch any of them that fail very
// quickly.
let sigchld_fd = SignalFd::new(SIGCHLD).context("failed to create signalfd")?;
// Create a pipe to capture error messages from plugin and minijail.
let (mut stderr_rd, stderr_wr) = pipe(true).context("failed to create stderr pipe")?;
add_fd_flags(stderr_rd.as_raw_descriptor(), O_NONBLOCK)
.context("error marking stderr nonblocking")?;
let jail = if cfg.sandbox {
// An empty directory for jailed plugin pivot root.
let root_path = match &cfg.plugin_root {
Some(dir) => dir,
None => Path::new(option_env!("DEFAULT_PIVOT_ROOT").unwrap_or("/var/empty")),
};
if root_path.is_relative() {
bail!("path to the root directory must be absolute");
}
if!root_path.exists() {
bail!("no root directory for jailed process to pivot root into");
}
if!root_path.is_dir() {
bail!("specified root directory is not a directory");
}
let policy_path = cfg.seccomp_policy_dir.join("plugin");
let mut jail = create_plugin_jail(root_path, cfg.seccomp_log_failures, &policy_path)?;
// Update gid map of the jail if caller provided supplemental groups.
if!cfg.plugin_gid_maps.is_empty | .expect("Failed to set thread id"); | random_line_split |
mod.rs | an ID associated with it that exists in an ID space shared by every variant
/// of `PluginObject`. This allows all the objects to be indexed in a single map, and allows for a
/// common destroy method.
///
/// In addition to the destory method, each object may have methods specific to its variant type.
/// These variant methods must be done by matching the variant to the expected type for that method.
/// For example, getting the dirty log from a `Memory` object starting with an ID:
///
/// ```ignore
/// match objects.get(&request_id) {
/// Some(&PluginObject::Memory { slot, length }) => vm.get_dirty_log(slot, &mut dirty_log[..]),
/// _ => return Err(SysError::new(ENOENT)),
/// }
/// ```
enum | {
IoEvent {
evt: Event,
addr: IoeventAddress,
length: u32,
datamatch: u64,
},
Memory {
slot: u32,
length: usize,
},
IrqEvent {
irq_id: u32,
evt: Event,
},
}
impl PluginObject {
fn destroy(self, vm: &mut Vm) -> SysResult<()> {
match self {
PluginObject::IoEvent {
evt,
addr,
length,
datamatch,
} => match length {
0 => vm.unregister_ioevent(&evt, addr, Datamatch::AnyLength),
1 => vm.unregister_ioevent(&evt, addr, Datamatch::U8(Some(datamatch as u8))),
2 => vm.unregister_ioevent(&evt, addr, Datamatch::U16(Some(datamatch as u16))),
4 => vm.unregister_ioevent(&evt, addr, Datamatch::U32(Some(datamatch as u32))),
8 => vm.unregister_ioevent(&evt, addr, Datamatch::U64(Some(datamatch as u64))),
_ => Err(SysError::new(EINVAL)),
},
PluginObject::Memory { slot,.. } => vm.remove_memory_region(slot).and(Ok(())),
PluginObject::IrqEvent { irq_id, evt } => vm.unregister_irqfd(&evt, irq_id),
}
}
}
pub fn run_vcpus(
kvm: &Kvm,
vm: &Vm,
plugin: &Process,
vcpu_count: u32,
kill_signaled: &Arc<AtomicBool>,
exit_evt: &Event,
vcpu_handles: &mut Vec<thread::JoinHandle<()>>,
) -> Result<()> {
let vcpu_thread_barrier = Arc::new(Barrier::new((vcpu_count) as usize));
let use_kvm_signals =!kvm.check_extension(Cap::ImmediateExit);
// If we need to force a vcpu to exit from a VM then a SIGRTMIN signal is sent
// to that vcpu's thread. If KVM is running the VM then it'll return -EINTR.
// An issue is what to do when KVM isn't running the VM (where we could be
// in the kernel or in the app).
//
// If KVM supports "immediate exit" then we set a signal handler that will
// set the |immediate_exit| flag that tells KVM to return -EINTR before running
// the VM.
//
// If KVM doesn't support immediate exit then we'll block SIGRTMIN in the app
// and tell KVM to unblock SIGRTMIN before running the VM (at which point a blocked
// signal might get asserted). There's overhead to have KVM unblock and re-block
// SIGRTMIN each time it runs the VM, so this mode should be avoided.
if use_kvm_signals {
unsafe {
extern "C" fn handle_signal(_: c_int) {}
// Our signal handler does nothing and is trivially async signal safe.
// We need to install this signal handler even though we do block
// the signal below, to ensure that this signal will interrupt
// execution of KVM_RUN (this is implementation issue).
register_rt_signal_handler(SIGRTMIN() + 0, handle_signal)
.expect("failed to register vcpu signal handler");
}
// We do not really want the signal handler to run...
block_signal(SIGRTMIN() + 0).expect("failed to block signal");
} else {
unsafe {
extern "C" fn handle_signal(_: c_int) {
Vcpu::set_local_immediate_exit(true);
}
register_rt_signal_handler(SIGRTMIN() + 0, handle_signal)
.expect("failed to register vcpu signal handler");
}
}
for cpu_id in 0..vcpu_count {
let kill_signaled = kill_signaled.clone();
let vcpu_thread_barrier = vcpu_thread_barrier.clone();
let vcpu_exit_evt = exit_evt.try_clone().context("failed to clone event")?;
let vcpu_plugin = plugin.create_vcpu(cpu_id)?;
let vcpu = Vcpu::new(cpu_id as c_ulong, kvm, vm).context("error creating vcpu")?;
vcpu_handles.push(
thread::Builder::new()
.name(format!("crosvm_vcpu{}", cpu_id))
.spawn(move || {
if use_kvm_signals {
// Tell KVM to not block anything when entering kvm run
// because we will be using first RT signal to kick the VCPU.
vcpu.set_signal_mask(&[])
.expect("failed to set up KVM VCPU signal mask");
}
if let Err(e) = enable_core_scheduling() {
error!("Failed to enable core scheduling: {}", e);
}
let vcpu = vcpu
.to_runnable(Some(SIGRTMIN() + 0))
.expect("Failed to set thread id");
let res = vcpu_plugin.init(&vcpu);
vcpu_thread_barrier.wait();
if let Err(e) = res {
error!("failed to initialize vcpu {}: {}", cpu_id, e);
} else {
loop {
let mut interrupted_by_signal = false;
let run_res = vcpu.run();
match run_res {
Ok(run) => match run {
VcpuExit::IoIn { port, mut size } => {
let mut data = [0; 256];
if size > data.len() {
error!(
"unsupported IoIn size of {} bytes at port {:#x}",
size, port
);
size = data.len();
}
vcpu_plugin.io_read(port as u64, &mut data[..size], &vcpu);
if let Err(e) = vcpu.set_data(&data[..size]) {
error!(
"failed to set return data for IoIn at port {:#x}: {}",
port, e
);
}
}
VcpuExit::IoOut {
port,
mut size,
data,
} => {
if size > data.len() {
error!("unsupported IoOut size of {} bytes at port {:#x}", size, port);
size = data.len();
}
vcpu_plugin.io_write(port as u64, &data[..size], &vcpu);
}
VcpuExit::MmioRead { address, size } => {
let mut data = [0; 8];
vcpu_plugin.mmio_read(
address as u64,
&mut data[..size],
&vcpu,
);
// Setting data for mmio can not fail.
let _ = vcpu.set_data(&data[..size]);
}
VcpuExit::MmioWrite {
address,
size,
data,
} => {
vcpu_plugin.mmio_write(
address as u64,
&data[..size],
&vcpu,
);
}
VcpuExit::HypervHcall { input, params } => {
let mut data = [0; 8];
vcpu_plugin.hyperv_call(input, params, &mut data, &vcpu);
// Setting data for hyperv call can not fail.
let _ = vcpu.set_data(&data);
}
VcpuExit::HypervSynic {
msr,
control,
evt_page,
msg_page,
} => {
vcpu_plugin
.hyperv_synic(msr, control, evt_page, msg_page, &vcpu);
}
VcpuExit::Hlt => break,
VcpuExit::Shutdown => break,
VcpuExit::InternalError => {
error!("vcpu {} has internal error", cpu_id);
break;
}
r => warn!("unexpected vcpu exit: {:?}", r),
},
Err(e) => match e.errno() {
EINTR => interrupted_by_signal = true,
EAGAIN => {}
_ => {
error!("vcpu hit unknown error: {}", e);
break;
}
},
}
if kill_signaled.load(Ordering::SeqCst) {
break;
}
// Only handle the pause request if kvm reported that it was
// interrupted by a signal. This helps to entire that KVM has had a chance
// to finish emulating any IO that may have immediately happened.
// If we eagerly check pre_run() then any IO that we
// just reported to the plugin won't have been processed yet by KVM.
// Not eagerly calling pre_run() also helps to reduce
// any overhead from checking if a pause request is pending.
// The assumption is that pause requests aren't common
// or frequent so it's better to optimize for the non-pause execution paths.
if interrupted_by_signal {
if use_kvm_signals {
clear_signal(SIGRTMIN() + 0)
.expect("failed to clear pending signal");
} else {
vcpu.set_immediate_exit(false);
}
if let Err(e) = vcpu_plugin.pre_run(&vcpu) {
error!("failed to process pause on vcpu {}: {}", cpu_id, e);
break;
}
}
}
}
vcpu_exit_evt
.write(1)
.expect("failed to signal vcpu exit event");
})
.context("error spawning vcpu thread")?,
);
}
Ok(())
}
#[derive(PollToken)]
enum Token {
Exit,
ChildSignal,
Stderr,
Plugin { index: usize },
}
/// Run a VM with a plugin process specified by `cfg`.
///
/// Not every field of `cfg` will be used. In particular, most field that pertain to a specific
/// device are ignored because the plugin is responsible for emulating hardware.
pub fn run_config(cfg: Config) -> Result<()> {
info!("crosvm starting plugin process");
// Masking signals is inherently dangerous, since this can persist across clones/execs. Do this
// before any jailed devices have been spawned, so that we can catch any of them that fail very
// quickly.
let sigchld_fd = SignalFd::new(SIGCHLD).context("failed to create signalfd")?;
// Create a pipe to capture error messages from plugin and minijail.
let (mut stderr_rd, stderr_wr) = pipe(true).context("failed to create stderr pipe")?;
add_fd_flags(stderr_rd.as_raw_descriptor(), O_NONBLOCK)
.context("error marking stderr nonblocking")?;
let jail = if cfg.sandbox {
// An empty directory for jailed plugin pivot root.
let root_path = match &cfg.plugin_root {
Some(dir) => dir,
None => Path::new(option_env!("DEFAULT_PIVOT_ROOT").unwrap_or("/var/empty")),
};
if root_path.is_relative() {
bail!("path to the root directory must be absolute");
}
if!root_path.exists() {
bail!("no root directory for jailed process to pivot root into");
}
if!root_path.is_dir() {
bail!("specified root directory is not a directory");
}
let policy_path = cfg.seccomp_policy_dir.join("plugin");
let mut jail = create_plugin_jail(root_path, cfg.seccomp_log_failures, &policy_path)?;
// Update gid map of the jail if caller provided supplemental groups.
if!cfg.plugin_gid_maps.is | PluginObject | identifier_name |
conversion_from_glib.rs | use super::parameter_ffi_call_out;
use crate::{
analysis::{self, try_from_glib::TryFromGlib},
library,
};
#[derive(Clone, Debug)]
pub struct Mode {
pub typ: library::TypeId,
pub transfer: library::Transfer,
pub is_uninitialized: bool,
pub try_from_glib: TryFromGlib,
}
impl From<¶meter_ffi_call_out::Parameter> for Mode {
fn from(orig: ¶meter_ffi_call_out::Parameter) -> Mode {
Mode {
typ: orig.typ,
transfer: orig.transfer, | is_uninitialized: orig.is_uninitialized,
try_from_glib: orig.try_from_glib.clone(),
}
}
}
impl From<&analysis::Parameter> for Mode {
fn from(orig: &analysis::Parameter) -> Mode {
Mode {
typ: orig.lib_par.typ,
transfer: orig.lib_par.transfer,
is_uninitialized: false,
try_from_glib: orig.try_from_glib.clone(),
}
}
} | random_line_split |
|
conversion_from_glib.rs | use super::parameter_ffi_call_out;
use crate::{
analysis::{self, try_from_glib::TryFromGlib},
library,
};
#[derive(Clone, Debug)]
pub struct | {
pub typ: library::TypeId,
pub transfer: library::Transfer,
pub is_uninitialized: bool,
pub try_from_glib: TryFromGlib,
}
impl From<¶meter_ffi_call_out::Parameter> for Mode {
fn from(orig: ¶meter_ffi_call_out::Parameter) -> Mode {
Mode {
typ: orig.typ,
transfer: orig.transfer,
is_uninitialized: orig.is_uninitialized,
try_from_glib: orig.try_from_glib.clone(),
}
}
}
impl From<&analysis::Parameter> for Mode {
fn from(orig: &analysis::Parameter) -> Mode {
Mode {
typ: orig.lib_par.typ,
transfer: orig.lib_par.transfer,
is_uninitialized: false,
try_from_glib: orig.try_from_glib.clone(),
}
}
}
| Mode | identifier_name |
conversion_from_glib.rs | use super::parameter_ffi_call_out;
use crate::{
analysis::{self, try_from_glib::TryFromGlib},
library,
};
#[derive(Clone, Debug)]
pub struct Mode {
pub typ: library::TypeId,
pub transfer: library::Transfer,
pub is_uninitialized: bool,
pub try_from_glib: TryFromGlib,
}
impl From<¶meter_ffi_call_out::Parameter> for Mode {
fn from(orig: ¶meter_ffi_call_out::Parameter) -> Mode |
}
impl From<&analysis::Parameter> for Mode {
fn from(orig: &analysis::Parameter) -> Mode {
Mode {
typ: orig.lib_par.typ,
transfer: orig.lib_par.transfer,
is_uninitialized: false,
try_from_glib: orig.try_from_glib.clone(),
}
}
}
| {
Mode {
typ: orig.typ,
transfer: orig.transfer,
is_uninitialized: orig.is_uninitialized,
try_from_glib: orig.try_from_glib.clone(),
}
} | identifier_body |
fieldinfo.rs | // GObject Introspection Rust bindings.
// Copyright (C) 2014 Luis Araujo <[email protected]>
// This library 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 2.1 of the License, or (at your option) any later version.
// This library 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 this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
extern crate libc;
use fieldinfo::libc::c_int;
use glib_gobject::{GPointer, GBoolean};
use types::{GITypeInfo, GIFieldInfo, GIArgument, GIFieldInfoFlags};
use std::mem::transmute;
#[link(name = "girepository-1.0")]
extern "C" {
fn g_field_info_get_flags(info: *GIFieldInfo) -> c_int;
fn g_field_info_get_size(info: *GIFieldInfo) -> c_int;
fn g_field_info_get_offset(info: *GIFieldInfo) -> c_int;
fn g_field_info_get_type(info: *GIFieldInfo) -> *GITypeInfo;
fn g_field_info_get_field(info: *GIFieldInfo,
mem: GPointer,
value: *GIArgument) -> GBoolean;
fn g_field_info_set_field(info: *GIFieldInfo,
mem: GPointer,
value: *GIArgument) -> GBoolean;
}
/// Obtain the flags for this GIFieldInfo.
pub fn get_flags(info: *GIFieldInfo) -> Option<GIFieldInfoFlags> {
let flag: Option<GIFieldInfoFlags> =
FromPrimitive::from_i32(unsafe { g_field_info_get_flags(info) });
return flag
}
/// Obtain the size in bits of the field member, this is how much space
/// you need to allocate to store the field.
pub fn get_size(info: *GIFieldInfo) -> int |
/// Obtain the offset in bits of the field member, this is relative to the
/// beginning of the struct or union.
pub fn get_offset(info: *GIFieldInfo) -> int {
unsafe { g_field_info_get_offset(info) as int }
}
/// Obtain the type of a field as a GITypeInfo.
pub fn get_type(info: *GIFieldInfo) -> *GITypeInfo {
unsafe { g_field_info_get_type(info) }
}
/// Reads a field identified by a GIFieldInfo from a C structure or union.
pub fn get_field(info: *GIFieldInfo, mem: GPointer, value: *GIArgument) -> GBoolean {
unsafe { g_field_info_get_field(info, mem, value) }
}
/// Writes a field identified by a GIFieldInfo to a C structure or union.
pub fn set_field(info: *GIFieldInfo, mem: GPointer, value: *GIArgument) -> GBoolean {
unsafe { g_field_info_set_field(info, mem, value) }
}
/// Convert GIBaseInfo to GIFieldInfo.
pub fn to_gi_field_info<T>(object: *T) -> *GIFieldInfo {
unsafe { transmute(object) }
}
| {
unsafe { g_field_info_get_size(info) as int }
} | identifier_body |
fieldinfo.rs | // GObject Introspection Rust bindings.
// Copyright (C) 2014 Luis Araujo <[email protected]>
// This library 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 2.1 of the License, or (at your option) any later version.
// This library 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 this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
extern crate libc;
use fieldinfo::libc::c_int;
use glib_gobject::{GPointer, GBoolean};
use types::{GITypeInfo, GIFieldInfo, GIArgument, GIFieldInfoFlags};
use std::mem::transmute;
#[link(name = "girepository-1.0")]
extern "C" {
fn g_field_info_get_flags(info: *GIFieldInfo) -> c_int;
fn g_field_info_get_size(info: *GIFieldInfo) -> c_int;
fn g_field_info_get_offset(info: *GIFieldInfo) -> c_int;
fn g_field_info_get_type(info: *GIFieldInfo) -> *GITypeInfo;
fn g_field_info_get_field(info: *GIFieldInfo, | value: *GIArgument) -> GBoolean;
}
/// Obtain the flags for this GIFieldInfo.
pub fn get_flags(info: *GIFieldInfo) -> Option<GIFieldInfoFlags> {
let flag: Option<GIFieldInfoFlags> =
FromPrimitive::from_i32(unsafe { g_field_info_get_flags(info) });
return flag
}
/// Obtain the size in bits of the field member, this is how much space
/// you need to allocate to store the field.
pub fn get_size(info: *GIFieldInfo) -> int {
unsafe { g_field_info_get_size(info) as int }
}
/// Obtain the offset in bits of the field member, this is relative to the
/// beginning of the struct or union.
pub fn get_offset(info: *GIFieldInfo) -> int {
unsafe { g_field_info_get_offset(info) as int }
}
/// Obtain the type of a field as a GITypeInfo.
pub fn get_type(info: *GIFieldInfo) -> *GITypeInfo {
unsafe { g_field_info_get_type(info) }
}
/// Reads a field identified by a GIFieldInfo from a C structure or union.
pub fn get_field(info: *GIFieldInfo, mem: GPointer, value: *GIArgument) -> GBoolean {
unsafe { g_field_info_get_field(info, mem, value) }
}
/// Writes a field identified by a GIFieldInfo to a C structure or union.
pub fn set_field(info: *GIFieldInfo, mem: GPointer, value: *GIArgument) -> GBoolean {
unsafe { g_field_info_set_field(info, mem, value) }
}
/// Convert GIBaseInfo to GIFieldInfo.
pub fn to_gi_field_info<T>(object: *T) -> *GIFieldInfo {
unsafe { transmute(object) }
} | mem: GPointer,
value: *GIArgument) -> GBoolean;
fn g_field_info_set_field(info: *GIFieldInfo,
mem: GPointer, | random_line_split |
fieldinfo.rs | // GObject Introspection Rust bindings.
// Copyright (C) 2014 Luis Araujo <[email protected]>
// This library 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 2.1 of the License, or (at your option) any later version.
// This library 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 this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
extern crate libc;
use fieldinfo::libc::c_int;
use glib_gobject::{GPointer, GBoolean};
use types::{GITypeInfo, GIFieldInfo, GIArgument, GIFieldInfoFlags};
use std::mem::transmute;
#[link(name = "girepository-1.0")]
extern "C" {
fn g_field_info_get_flags(info: *GIFieldInfo) -> c_int;
fn g_field_info_get_size(info: *GIFieldInfo) -> c_int;
fn g_field_info_get_offset(info: *GIFieldInfo) -> c_int;
fn g_field_info_get_type(info: *GIFieldInfo) -> *GITypeInfo;
fn g_field_info_get_field(info: *GIFieldInfo,
mem: GPointer,
value: *GIArgument) -> GBoolean;
fn g_field_info_set_field(info: *GIFieldInfo,
mem: GPointer,
value: *GIArgument) -> GBoolean;
}
/// Obtain the flags for this GIFieldInfo.
pub fn get_flags(info: *GIFieldInfo) -> Option<GIFieldInfoFlags> {
let flag: Option<GIFieldInfoFlags> =
FromPrimitive::from_i32(unsafe { g_field_info_get_flags(info) });
return flag
}
/// Obtain the size in bits of the field member, this is how much space
/// you need to allocate to store the field.
pub fn get_size(info: *GIFieldInfo) -> int {
unsafe { g_field_info_get_size(info) as int }
}
/// Obtain the offset in bits of the field member, this is relative to the
/// beginning of the struct or union.
pub fn | (info: *GIFieldInfo) -> int {
unsafe { g_field_info_get_offset(info) as int }
}
/// Obtain the type of a field as a GITypeInfo.
pub fn get_type(info: *GIFieldInfo) -> *GITypeInfo {
unsafe { g_field_info_get_type(info) }
}
/// Reads a field identified by a GIFieldInfo from a C structure or union.
pub fn get_field(info: *GIFieldInfo, mem: GPointer, value: *GIArgument) -> GBoolean {
unsafe { g_field_info_get_field(info, mem, value) }
}
/// Writes a field identified by a GIFieldInfo to a C structure or union.
pub fn set_field(info: *GIFieldInfo, mem: GPointer, value: *GIArgument) -> GBoolean {
unsafe { g_field_info_set_field(info, mem, value) }
}
/// Convert GIBaseInfo to GIFieldInfo.
pub fn to_gi_field_info<T>(object: *T) -> *GIFieldInfo {
unsafe { transmute(object) }
}
| get_offset | identifier_name |
event.rs | // Copyright 2015-2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::*;
use gdk_ffi as ffi;
use EventType;
use Window;
glib_wrapper! {
/// A generic GDK event.
pub struct Event(Boxed<ffi::GdkEvent>);
match fn {
copy => |ptr| ffi::gdk_event_copy(ptr),
free => |ptr| ffi::gdk_event_free(ptr),
}
}
impl Event {
/// Returns the event type.
pub fn get_event_type(&self) -> EventType {
self.as_ref().type_
}
/// Returns the associated `Window` if applicable.
pub fn get_window(&self) -> Option<Window> {
unsafe { from_glib_none(self.as_ref().window) }
}
/// Returns whether the event was sent explicitly.
pub fn get_send_event(&self) -> bool {
from_glib(self.as_ref().send_event as i32)
}
/// Returns `true` if the event type matches `T`.
pub fn is<T: FromEvent>(&self) -> bool {
T::is(self)
}
/// Tries to downcast to a specific event type.
pub fn downcast<T: FromEvent>(self) -> Result<T, Self> {
T::from(self)
}
}
/// A helper trait implemented by all event subtypes.
pub trait FromEvent: Sized {
fn is(ev: &Event) -> bool;
fn from(ev: Event) -> Result<Self, Event>;
}
macro_rules! event_wrapper {
($name:ident, $ffi_name:ident) => {
impl<'a> ToGlibPtr<'a, *const ::gdk_ffi::$ffi_name> for $name {
type Storage = &'a Self;
#[inline]
fn to_glib_none(&'a self) -> Stash<'a, *const ::gdk_ffi::$ffi_name, Self> {
let ptr = ToGlibPtr::<*const ::gdk_ffi::GdkEvent>::to_glib_none(&self.0).0;
Stash(ptr as *const ::gdk_ffi::$ffi_name, self)
}
}
impl<'a> ToGlibPtrMut<'a, *mut ::gdk_ffi::$ffi_name> for $name {
type Storage = &'a mut Self;
#[inline]
fn to_glib_none_mut(&'a mut self) -> StashMut<'a, *mut ::gdk_ffi::$ffi_name, Self> {
let ptr = ToGlibPtrMut::<*mut ::gdk_ffi::GdkEvent>::to_glib_none_mut(&mut self.0).0;
StashMut(ptr as *mut ::gdk_ffi::$ffi_name, self)
}
}
impl FromGlibPtr<*mut ::gdk_ffi::$ffi_name> for $name {
#[inline]
unsafe fn from_glib_none(ptr: *mut ::gdk_ffi::$ffi_name) -> Self {
$name(from_glib_none(ptr as *mut ::gdk_ffi::GdkEvent))
}
#[inline]
unsafe fn from_glib_full(ptr: *mut ::gdk_ffi::$ffi_name) -> Self {
$name(from_glib_full(ptr as *mut ::gdk_ffi::GdkEvent))
}
}
impl AsRef<::gdk_ffi::$ffi_name> for $name {
#[inline]
fn as_ref(&self) -> &::gdk_ffi::$ffi_name {
unsafe {
let ptr: *const ::gdk_ffi::$ffi_name = self.to_glib_none().0;
&*ptr
}
}
}
impl AsMut<::gdk_ffi::$ffi_name> for $name {
#[inline]
fn as_mut(&mut self) -> &mut ::gdk_ffi::$ffi_name {
unsafe {
let ptr: *mut ::gdk_ffi::$ffi_name = self.to_glib_none_mut().0;
&mut *ptr
}
}
}
}
}
event_wrapper!(Event, GdkEventAny);
macro_rules! event_subtype {
($name:ident, $($ty:ident)|+) => {
impl ::event::FromEvent for $name {
#[inline]
fn is(ev: &::event::Event) -> bool {
skip_assert_initialized!();
use EventType::*;
match ev.as_ref().type_ {
$($ty)|+ => true,
_ => false,
}
}
#[inline]
fn from(ev: ::event::Event) -> Result<Self, ::event::Event> {
skip_assert_initialized!();
if Self::is(&ev) {
Ok($name(ev))
}
else {
Err(ev)
} | impl ::std::ops::Deref for $name {
type Target = ::event::Event;
fn deref(&self) -> &::event::Event {
&self.0
}
}
impl ::std::ops::DerefMut for $name {
fn deref_mut(&mut self) -> &mut ::event::Event {
&mut self.0
}
}
}
} | }
}
| random_line_split |
event.rs | // Copyright 2015-2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::*;
use gdk_ffi as ffi;
use EventType;
use Window;
glib_wrapper! {
/// A generic GDK event.
pub struct Event(Boxed<ffi::GdkEvent>);
match fn {
copy => |ptr| ffi::gdk_event_copy(ptr),
free => |ptr| ffi::gdk_event_free(ptr),
}
}
impl Event {
/// Returns the event type.
pub fn | (&self) -> EventType {
self.as_ref().type_
}
/// Returns the associated `Window` if applicable.
pub fn get_window(&self) -> Option<Window> {
unsafe { from_glib_none(self.as_ref().window) }
}
/// Returns whether the event was sent explicitly.
pub fn get_send_event(&self) -> bool {
from_glib(self.as_ref().send_event as i32)
}
/// Returns `true` if the event type matches `T`.
pub fn is<T: FromEvent>(&self) -> bool {
T::is(self)
}
/// Tries to downcast to a specific event type.
pub fn downcast<T: FromEvent>(self) -> Result<T, Self> {
T::from(self)
}
}
/// A helper trait implemented by all event subtypes.
pub trait FromEvent: Sized {
fn is(ev: &Event) -> bool;
fn from(ev: Event) -> Result<Self, Event>;
}
macro_rules! event_wrapper {
($name:ident, $ffi_name:ident) => {
impl<'a> ToGlibPtr<'a, *const ::gdk_ffi::$ffi_name> for $name {
type Storage = &'a Self;
#[inline]
fn to_glib_none(&'a self) -> Stash<'a, *const ::gdk_ffi::$ffi_name, Self> {
let ptr = ToGlibPtr::<*const ::gdk_ffi::GdkEvent>::to_glib_none(&self.0).0;
Stash(ptr as *const ::gdk_ffi::$ffi_name, self)
}
}
impl<'a> ToGlibPtrMut<'a, *mut ::gdk_ffi::$ffi_name> for $name {
type Storage = &'a mut Self;
#[inline]
fn to_glib_none_mut(&'a mut self) -> StashMut<'a, *mut ::gdk_ffi::$ffi_name, Self> {
let ptr = ToGlibPtrMut::<*mut ::gdk_ffi::GdkEvent>::to_glib_none_mut(&mut self.0).0;
StashMut(ptr as *mut ::gdk_ffi::$ffi_name, self)
}
}
impl FromGlibPtr<*mut ::gdk_ffi::$ffi_name> for $name {
#[inline]
unsafe fn from_glib_none(ptr: *mut ::gdk_ffi::$ffi_name) -> Self {
$name(from_glib_none(ptr as *mut ::gdk_ffi::GdkEvent))
}
#[inline]
unsafe fn from_glib_full(ptr: *mut ::gdk_ffi::$ffi_name) -> Self {
$name(from_glib_full(ptr as *mut ::gdk_ffi::GdkEvent))
}
}
impl AsRef<::gdk_ffi::$ffi_name> for $name {
#[inline]
fn as_ref(&self) -> &::gdk_ffi::$ffi_name {
unsafe {
let ptr: *const ::gdk_ffi::$ffi_name = self.to_glib_none().0;
&*ptr
}
}
}
impl AsMut<::gdk_ffi::$ffi_name> for $name {
#[inline]
fn as_mut(&mut self) -> &mut ::gdk_ffi::$ffi_name {
unsafe {
let ptr: *mut ::gdk_ffi::$ffi_name = self.to_glib_none_mut().0;
&mut *ptr
}
}
}
}
}
event_wrapper!(Event, GdkEventAny);
macro_rules! event_subtype {
($name:ident, $($ty:ident)|+) => {
impl ::event::FromEvent for $name {
#[inline]
fn is(ev: &::event::Event) -> bool {
skip_assert_initialized!();
use EventType::*;
match ev.as_ref().type_ {
$($ty)|+ => true,
_ => false,
}
}
#[inline]
fn from(ev: ::event::Event) -> Result<Self, ::event::Event> {
skip_assert_initialized!();
if Self::is(&ev) {
Ok($name(ev))
}
else {
Err(ev)
}
}
}
impl ::std::ops::Deref for $name {
type Target = ::event::Event;
fn deref(&self) -> &::event::Event {
&self.0
}
}
impl ::std::ops::DerefMut for $name {
fn deref_mut(&mut self) -> &mut ::event::Event {
&mut self.0
}
}
}
}
| get_event_type | identifier_name |
event.rs | // Copyright 2015-2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::*;
use gdk_ffi as ffi;
use EventType;
use Window;
glib_wrapper! {
/// A generic GDK event.
pub struct Event(Boxed<ffi::GdkEvent>);
match fn {
copy => |ptr| ffi::gdk_event_copy(ptr),
free => |ptr| ffi::gdk_event_free(ptr),
}
}
impl Event {
/// Returns the event type.
pub fn get_event_type(&self) -> EventType |
/// Returns the associated `Window` if applicable.
pub fn get_window(&self) -> Option<Window> {
unsafe { from_glib_none(self.as_ref().window) }
}
/// Returns whether the event was sent explicitly.
pub fn get_send_event(&self) -> bool {
from_glib(self.as_ref().send_event as i32)
}
/// Returns `true` if the event type matches `T`.
pub fn is<T: FromEvent>(&self) -> bool {
T::is(self)
}
/// Tries to downcast to a specific event type.
pub fn downcast<T: FromEvent>(self) -> Result<T, Self> {
T::from(self)
}
}
/// A helper trait implemented by all event subtypes.
pub trait FromEvent: Sized {
fn is(ev: &Event) -> bool;
fn from(ev: Event) -> Result<Self, Event>;
}
macro_rules! event_wrapper {
($name:ident, $ffi_name:ident) => {
impl<'a> ToGlibPtr<'a, *const ::gdk_ffi::$ffi_name> for $name {
type Storage = &'a Self;
#[inline]
fn to_glib_none(&'a self) -> Stash<'a, *const ::gdk_ffi::$ffi_name, Self> {
let ptr = ToGlibPtr::<*const ::gdk_ffi::GdkEvent>::to_glib_none(&self.0).0;
Stash(ptr as *const ::gdk_ffi::$ffi_name, self)
}
}
impl<'a> ToGlibPtrMut<'a, *mut ::gdk_ffi::$ffi_name> for $name {
type Storage = &'a mut Self;
#[inline]
fn to_glib_none_mut(&'a mut self) -> StashMut<'a, *mut ::gdk_ffi::$ffi_name, Self> {
let ptr = ToGlibPtrMut::<*mut ::gdk_ffi::GdkEvent>::to_glib_none_mut(&mut self.0).0;
StashMut(ptr as *mut ::gdk_ffi::$ffi_name, self)
}
}
impl FromGlibPtr<*mut ::gdk_ffi::$ffi_name> for $name {
#[inline]
unsafe fn from_glib_none(ptr: *mut ::gdk_ffi::$ffi_name) -> Self {
$name(from_glib_none(ptr as *mut ::gdk_ffi::GdkEvent))
}
#[inline]
unsafe fn from_glib_full(ptr: *mut ::gdk_ffi::$ffi_name) -> Self {
$name(from_glib_full(ptr as *mut ::gdk_ffi::GdkEvent))
}
}
impl AsRef<::gdk_ffi::$ffi_name> for $name {
#[inline]
fn as_ref(&self) -> &::gdk_ffi::$ffi_name {
unsafe {
let ptr: *const ::gdk_ffi::$ffi_name = self.to_glib_none().0;
&*ptr
}
}
}
impl AsMut<::gdk_ffi::$ffi_name> for $name {
#[inline]
fn as_mut(&mut self) -> &mut ::gdk_ffi::$ffi_name {
unsafe {
let ptr: *mut ::gdk_ffi::$ffi_name = self.to_glib_none_mut().0;
&mut *ptr
}
}
}
}
}
event_wrapper!(Event, GdkEventAny);
macro_rules! event_subtype {
($name:ident, $($ty:ident)|+) => {
impl ::event::FromEvent for $name {
#[inline]
fn is(ev: &::event::Event) -> bool {
skip_assert_initialized!();
use EventType::*;
match ev.as_ref().type_ {
$($ty)|+ => true,
_ => false,
}
}
#[inline]
fn from(ev: ::event::Event) -> Result<Self, ::event::Event> {
skip_assert_initialized!();
if Self::is(&ev) {
Ok($name(ev))
}
else {
Err(ev)
}
}
}
impl ::std::ops::Deref for $name {
type Target = ::event::Event;
fn deref(&self) -> &::event::Event {
&self.0
}
}
impl ::std::ops::DerefMut for $name {
fn deref_mut(&mut self) -> &mut ::event::Event {
&mut self.0
}
}
}
}
| {
self.as_ref().type_
} | identifier_body |
aio.rs | //! IGD async API example.
//!
//! It demonstrates how to:
//! * get external IP
//! * add port mappings
//! * remove port mappings
//!
//! If everything works fine, 2 port mappings are added, 1 removed and we're left with single
//! port mapping: External 1234 ---> 4321 Internal
use std::env;
use std::net::SocketAddrV4;
use igd::aio::search_gateway;
use igd::PortMappingProtocol;
use simplelog::{Config as LogConfig, LevelFilter, SimpleLogger};
#[tokio::main]
async fn main() | Ok(ip) => ip,
Err(err) => return println!("Failed to get external IP: {}", err),
};
println!("Our public IP is {}", pub_ip);
if let Err(e) = gateway
.add_port(PortMappingProtocol::TCP, 1234, ip, 120, "rust-igd-async-example")
.await
{
println!("Failed to add port mapping: {}", e);
}
println!("New port mapping was successfully added.");
if let Err(e) = gateway
.add_port(PortMappingProtocol::TCP, 2345, ip, 120, "rust-igd-async-example")
.await
{
println!("Failed to add port mapping: {}", e);
}
println!("New port mapping was successfully added.");
if gateway.remove_port(PortMappingProtocol::TCP, 2345).await.is_err() {
println!("Port mapping was not successfully removed");
} else {
println!("Port was removed.");
}
}
| {
let ip = match env::args().nth(1) {
Some(ip) => ip,
None => {
println!("Local socket address is missing!");
println!("This example requires a socket address representing the local machine and the port to bind to as an argument");
println!("Example: target/debug/examples/io 192.168.0.198:4321");
println!("Example: cargo run --features aio --example aio -- 192.168.0.198:4321");
return;
}
};
let ip: SocketAddrV4 = ip.parse().expect("Invalid socket address");
let _ = SimpleLogger::init(LevelFilter::Debug, LogConfig::default());
let gateway = match search_gateway(Default::default()).await {
Ok(g) => g,
Err(err) => return println!("Faild to find IGD: {}", err),
};
let pub_ip = match gateway.get_external_ip().await { | identifier_body |
aio.rs | //! IGD async API example.
//!
//! It demonstrates how to:
//! * get external IP
//! * add port mappings
//! * remove port mappings
//!
//! If everything works fine, 2 port mappings are added, 1 removed and we're left with single
//! port mapping: External 1234 ---> 4321 Internal
use std::env;
use std::net::SocketAddrV4;
use igd::aio::search_gateway;
use igd::PortMappingProtocol;
use simplelog::{Config as LogConfig, LevelFilter, SimpleLogger};
#[tokio::main]
async fn | () {
let ip = match env::args().nth(1) {
Some(ip) => ip,
None => {
println!("Local socket address is missing!");
println!("This example requires a socket address representing the local machine and the port to bind to as an argument");
println!("Example: target/debug/examples/io 192.168.0.198:4321");
println!("Example: cargo run --features aio --example aio -- 192.168.0.198:4321");
return;
}
};
let ip: SocketAddrV4 = ip.parse().expect("Invalid socket address");
let _ = SimpleLogger::init(LevelFilter::Debug, LogConfig::default());
let gateway = match search_gateway(Default::default()).await {
Ok(g) => g,
Err(err) => return println!("Faild to find IGD: {}", err),
};
let pub_ip = match gateway.get_external_ip().await {
Ok(ip) => ip,
Err(err) => return println!("Failed to get external IP: {}", err),
};
println!("Our public IP is {}", pub_ip);
if let Err(e) = gateway
.add_port(PortMappingProtocol::TCP, 1234, ip, 120, "rust-igd-async-example")
.await
{
println!("Failed to add port mapping: {}", e);
}
println!("New port mapping was successfully added.");
if let Err(e) = gateway
.add_port(PortMappingProtocol::TCP, 2345, ip, 120, "rust-igd-async-example")
.await
{
println!("Failed to add port mapping: {}", e);
}
println!("New port mapping was successfully added.");
if gateway.remove_port(PortMappingProtocol::TCP, 2345).await.is_err() {
println!("Port mapping was not successfully removed");
} else {
println!("Port was removed.");
}
}
| main | identifier_name |
aio.rs | //! IGD async API example.
//!
//! It demonstrates how to:
//! * get external IP | //! * add port mappings
//! * remove port mappings
//!
//! If everything works fine, 2 port mappings are added, 1 removed and we're left with single
//! port mapping: External 1234 ---> 4321 Internal
use std::env;
use std::net::SocketAddrV4;
use igd::aio::search_gateway;
use igd::PortMappingProtocol;
use simplelog::{Config as LogConfig, LevelFilter, SimpleLogger};
#[tokio::main]
async fn main() {
let ip = match env::args().nth(1) {
Some(ip) => ip,
None => {
println!("Local socket address is missing!");
println!("This example requires a socket address representing the local machine and the port to bind to as an argument");
println!("Example: target/debug/examples/io 192.168.0.198:4321");
println!("Example: cargo run --features aio --example aio -- 192.168.0.198:4321");
return;
}
};
let ip: SocketAddrV4 = ip.parse().expect("Invalid socket address");
let _ = SimpleLogger::init(LevelFilter::Debug, LogConfig::default());
let gateway = match search_gateway(Default::default()).await {
Ok(g) => g,
Err(err) => return println!("Faild to find IGD: {}", err),
};
let pub_ip = match gateway.get_external_ip().await {
Ok(ip) => ip,
Err(err) => return println!("Failed to get external IP: {}", err),
};
println!("Our public IP is {}", pub_ip);
if let Err(e) = gateway
.add_port(PortMappingProtocol::TCP, 1234, ip, 120, "rust-igd-async-example")
.await
{
println!("Failed to add port mapping: {}", e);
}
println!("New port mapping was successfully added.");
if let Err(e) = gateway
.add_port(PortMappingProtocol::TCP, 2345, ip, 120, "rust-igd-async-example")
.await
{
println!("Failed to add port mapping: {}", e);
}
println!("New port mapping was successfully added.");
if gateway.remove_port(PortMappingProtocol::TCP, 2345).await.is_err() {
println!("Port mapping was not successfully removed");
} else {
println!("Port was removed.");
}
} | random_line_split |
|
env.rs | /*
* Copyright (C) 2018, Nils Asmussen <[email protected]>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* M3 is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details.
*/
use arch;
use base;
use cap::Selector;
use com::SliceSource;
use core::intrinsics;
use dtu::{EP_COUNT, FIRST_FREE_EP};
use env;
use kif::{INVALID_SEL, PEDesc};
use session::Pager;
use util;
use vfs::{FileTable, MountTable};
use vpe;
#[derive(Default, Copy, Clone)]
#[repr(C, packed)]
pub struct EnvData {
base: base::envdata::EnvData,
}
impl EnvData {
pub fn pe_id(&self) -> u64 {
self.base.pe_id
}
pub fn pe_desc(&self) -> PEDesc {
PEDesc::new_from(self.base.pe_desc)
}
pub fn set_pedesc(&mut self, pe: &PEDesc) {
self.base.pe_desc = pe.value();
}
pub fn argc(&self) -> usize {
self.base.argc as usize
}
pub fn set_argc(&mut self, argc: usize) {
self.base.argc = argc as u32;
}
pub fn set_argv(&mut self, argv: usize) {
self.base.argv = argv as u64;
}
pub fn sp(&self) -> usize {
self.base.sp as usize
}
pub fn set_sp(&mut self, sp: usize) {
self.base.sp = sp as u64;
}
pub fn set_entry(&mut self, entry: usize) {
self.base.entry = entry as u64;
}
pub fn heap_size(&self) -> usize {
self.base.heap_size as usize
}
pub fn set_heap_size(&mut self, size: usize) {
self.base.heap_size = size as u64;
} | pub fn has_vpe(&self) -> bool {
self.base.vpe!= 0
}
pub fn vpe(&self) -> &'static mut vpe::VPE {
unsafe {
intrinsics::transmute(self.base.vpe as usize)
}
}
pub fn load_rbufs(&self) -> arch::rbufs::RBufSpace {
arch::rbufs::RBufSpace::new_with(
self.base.rbuf_cur as usize,
self.base.rbuf_end as usize
)
}
pub fn load_pager(&self) -> Option<Pager> {
match self.base.pager_sess {
0 => None,
s => Some(Pager::new_bind(s, self.base.pager_rgate).unwrap()),
}
}
pub fn load_caps_eps(&self) -> (Selector, u64) {
(
// it's initially 0. make sure it's at least the first usable selector
util::max(2 + (EP_COUNT - FIRST_FREE_EP) as Selector, self.base.caps as Selector),
self.base.eps
)
}
pub fn load_mounts(&self) -> MountTable {
if self.base.mounts_len!= 0 {
let slice = unsafe {
util::slice_for(self.base.mounts as *const u64, self.base.mounts_len as usize)
};
MountTable::unserialize(&mut SliceSource::new(slice))
}
else {
MountTable::default()
}
}
pub fn load_fds(&self) -> FileTable {
if self.base.fds_len!= 0 {
let slice = unsafe {
util::slice_for(self.base.fds as *const u64, self.base.fds_len as usize)
};
FileTable::unserialize(&mut SliceSource::new(slice))
}
else {
FileTable::default()
}
}
// --- gem5 specific API ---
pub fn set_vpe(&mut self, vpe: &vpe::VPE) {
self.base.vpe = vpe as *const vpe::VPE as u64;
}
pub fn exit_addr(&self) -> usize {
self.base.exit_addr as usize
}
pub fn has_lambda(&self) -> bool {
self.base.lambda == 1
}
pub fn set_lambda(&mut self, lambda: bool) {
self.base.lambda = lambda as u64;
}
pub fn set_next_sel(&mut self, sel: Selector) {
self.base.caps = sel as u64;
}
pub fn set_eps(&mut self, eps: u64) {
self.base.eps = eps;
}
pub fn set_rbufs(&mut self, rbufs: &arch::rbufs::RBufSpace) {
self.base.rbuf_cur = rbufs.cur as u64;
self.base.rbuf_end = rbufs.end as u64;
}
pub fn set_files(&mut self, off: usize, len: usize) {
self.base.fds = off as u64;
self.base.fds_len = len as u32;
}
pub fn set_mounts(&mut self, off: usize, len: usize) {
self.base.mounts = off as u64;
self.base.mounts_len = len as u32;
}
pub fn set_pager(&mut self, pager: &Pager) {
self.base.pager_sess = pager.sel();
self.base.pager_rgate = match pager.rgate() {
Some(rg) => rg.sel(),
None => INVALID_SEL,
};
}
}
pub fn get() -> &'static mut EnvData {
unsafe {
intrinsics::transmute(0x6000 as usize)
}
}
pub fn closure() -> &'static mut env::Closure {
unsafe {
intrinsics::transmute(0x6000 as usize + util::size_of::<EnvData>())
}
} | random_line_split |
|
env.rs | /*
* Copyright (C) 2018, Nils Asmussen <[email protected]>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* M3 is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details.
*/
use arch;
use base;
use cap::Selector;
use com::SliceSource;
use core::intrinsics;
use dtu::{EP_COUNT, FIRST_FREE_EP};
use env;
use kif::{INVALID_SEL, PEDesc};
use session::Pager;
use util;
use vfs::{FileTable, MountTable};
use vpe;
#[derive(Default, Copy, Clone)]
#[repr(C, packed)]
pub struct EnvData {
base: base::envdata::EnvData,
}
impl EnvData {
pub fn pe_id(&self) -> u64 {
self.base.pe_id
}
pub fn pe_desc(&self) -> PEDesc {
PEDesc::new_from(self.base.pe_desc)
}
pub fn set_pedesc(&mut self, pe: &PEDesc) {
self.base.pe_desc = pe.value();
}
pub fn argc(&self) -> usize {
self.base.argc as usize
}
pub fn set_argc(&mut self, argc: usize) {
self.base.argc = argc as u32;
}
pub fn set_argv(&mut self, argv: usize) {
self.base.argv = argv as u64;
}
pub fn sp(&self) -> usize {
self.base.sp as usize
}
pub fn set_sp(&mut self, sp: usize) {
self.base.sp = sp as u64;
}
pub fn set_entry(&mut self, entry: usize) {
self.base.entry = entry as u64;
}
pub fn heap_size(&self) -> usize {
self.base.heap_size as usize
}
pub fn set_heap_size(&mut self, size: usize) {
self.base.heap_size = size as u64;
}
pub fn has_vpe(&self) -> bool {
self.base.vpe!= 0
}
pub fn vpe(&self) -> &'static mut vpe::VPE {
unsafe {
intrinsics::transmute(self.base.vpe as usize)
}
}
pub fn load_rbufs(&self) -> arch::rbufs::RBufSpace {
arch::rbufs::RBufSpace::new_with(
self.base.rbuf_cur as usize,
self.base.rbuf_end as usize
)
}
pub fn load_pager(&self) -> Option<Pager> {
match self.base.pager_sess {
0 => None,
s => Some(Pager::new_bind(s, self.base.pager_rgate).unwrap()),
}
}
pub fn load_caps_eps(&self) -> (Selector, u64) {
(
// it's initially 0. make sure it's at least the first usable selector
util::max(2 + (EP_COUNT - FIRST_FREE_EP) as Selector, self.base.caps as Selector),
self.base.eps
)
}
pub fn load_mounts(&self) -> MountTable {
if self.base.mounts_len!= 0 {
let slice = unsafe {
util::slice_for(self.base.mounts as *const u64, self.base.mounts_len as usize)
};
MountTable::unserialize(&mut SliceSource::new(slice))
}
else {
MountTable::default()
}
}
pub fn load_fds(&self) -> FileTable {
if self.base.fds_len!= 0 {
let slice = unsafe {
util::slice_for(self.base.fds as *const u64, self.base.fds_len as usize)
};
FileTable::unserialize(&mut SliceSource::new(slice))
}
else {
FileTable::default()
}
}
// --- gem5 specific API ---
pub fn set_vpe(&mut self, vpe: &vpe::VPE) {
self.base.vpe = vpe as *const vpe::VPE as u64;
}
pub fn exit_addr(&self) -> usize {
self.base.exit_addr as usize
}
pub fn has_lambda(&self) -> bool {
self.base.lambda == 1
}
pub fn set_lambda(&mut self, lambda: bool) {
self.base.lambda = lambda as u64;
}
pub fn | (&mut self, sel: Selector) {
self.base.caps = sel as u64;
}
pub fn set_eps(&mut self, eps: u64) {
self.base.eps = eps;
}
pub fn set_rbufs(&mut self, rbufs: &arch::rbufs::RBufSpace) {
self.base.rbuf_cur = rbufs.cur as u64;
self.base.rbuf_end = rbufs.end as u64;
}
pub fn set_files(&mut self, off: usize, len: usize) {
self.base.fds = off as u64;
self.base.fds_len = len as u32;
}
pub fn set_mounts(&mut self, off: usize, len: usize) {
self.base.mounts = off as u64;
self.base.mounts_len = len as u32;
}
pub fn set_pager(&mut self, pager: &Pager) {
self.base.pager_sess = pager.sel();
self.base.pager_rgate = match pager.rgate() {
Some(rg) => rg.sel(),
None => INVALID_SEL,
};
}
}
pub fn get() -> &'static mut EnvData {
unsafe {
intrinsics::transmute(0x6000 as usize)
}
}
pub fn closure() -> &'static mut env::Closure {
unsafe {
intrinsics::transmute(0x6000 as usize + util::size_of::<EnvData>())
}
}
| set_next_sel | identifier_name |
env.rs | /*
* Copyright (C) 2018, Nils Asmussen <[email protected]>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* M3 is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details.
*/
use arch;
use base;
use cap::Selector;
use com::SliceSource;
use core::intrinsics;
use dtu::{EP_COUNT, FIRST_FREE_EP};
use env;
use kif::{INVALID_SEL, PEDesc};
use session::Pager;
use util;
use vfs::{FileTable, MountTable};
use vpe;
#[derive(Default, Copy, Clone)]
#[repr(C, packed)]
pub struct EnvData {
base: base::envdata::EnvData,
}
impl EnvData {
pub fn pe_id(&self) -> u64 {
self.base.pe_id
}
pub fn pe_desc(&self) -> PEDesc {
PEDesc::new_from(self.base.pe_desc)
}
pub fn set_pedesc(&mut self, pe: &PEDesc) {
self.base.pe_desc = pe.value();
}
pub fn argc(&self) -> usize {
self.base.argc as usize
}
pub fn set_argc(&mut self, argc: usize) {
self.base.argc = argc as u32;
}
pub fn set_argv(&mut self, argv: usize) {
self.base.argv = argv as u64;
}
pub fn sp(&self) -> usize {
self.base.sp as usize
}
pub fn set_sp(&mut self, sp: usize) {
self.base.sp = sp as u64;
}
pub fn set_entry(&mut self, entry: usize) {
self.base.entry = entry as u64;
}
pub fn heap_size(&self) -> usize {
self.base.heap_size as usize
}
pub fn set_heap_size(&mut self, size: usize) {
self.base.heap_size = size as u64;
}
pub fn has_vpe(&self) -> bool {
self.base.vpe!= 0
}
pub fn vpe(&self) -> &'static mut vpe::VPE {
unsafe {
intrinsics::transmute(self.base.vpe as usize)
}
}
pub fn load_rbufs(&self) -> arch::rbufs::RBufSpace {
arch::rbufs::RBufSpace::new_with(
self.base.rbuf_cur as usize,
self.base.rbuf_end as usize
)
}
pub fn load_pager(&self) -> Option<Pager> {
match self.base.pager_sess {
0 => None,
s => Some(Pager::new_bind(s, self.base.pager_rgate).unwrap()),
}
}
pub fn load_caps_eps(&self) -> (Selector, u64) |
pub fn load_mounts(&self) -> MountTable {
if self.base.mounts_len!= 0 {
let slice = unsafe {
util::slice_for(self.base.mounts as *const u64, self.base.mounts_len as usize)
};
MountTable::unserialize(&mut SliceSource::new(slice))
}
else {
MountTable::default()
}
}
pub fn load_fds(&self) -> FileTable {
if self.base.fds_len!= 0 {
let slice = unsafe {
util::slice_for(self.base.fds as *const u64, self.base.fds_len as usize)
};
FileTable::unserialize(&mut SliceSource::new(slice))
}
else {
FileTable::default()
}
}
// --- gem5 specific API ---
pub fn set_vpe(&mut self, vpe: &vpe::VPE) {
self.base.vpe = vpe as *const vpe::VPE as u64;
}
pub fn exit_addr(&self) -> usize {
self.base.exit_addr as usize
}
pub fn has_lambda(&self) -> bool {
self.base.lambda == 1
}
pub fn set_lambda(&mut self, lambda: bool) {
self.base.lambda = lambda as u64;
}
pub fn set_next_sel(&mut self, sel: Selector) {
self.base.caps = sel as u64;
}
pub fn set_eps(&mut self, eps: u64) {
self.base.eps = eps;
}
pub fn set_rbufs(&mut self, rbufs: &arch::rbufs::RBufSpace) {
self.base.rbuf_cur = rbufs.cur as u64;
self.base.rbuf_end = rbufs.end as u64;
}
pub fn set_files(&mut self, off: usize, len: usize) {
self.base.fds = off as u64;
self.base.fds_len = len as u32;
}
pub fn set_mounts(&mut self, off: usize, len: usize) {
self.base.mounts = off as u64;
self.base.mounts_len = len as u32;
}
pub fn set_pager(&mut self, pager: &Pager) {
self.base.pager_sess = pager.sel();
self.base.pager_rgate = match pager.rgate() {
Some(rg) => rg.sel(),
None => INVALID_SEL,
};
}
}
pub fn get() -> &'static mut EnvData {
unsafe {
intrinsics::transmute(0x6000 as usize)
}
}
pub fn closure() -> &'static mut env::Closure {
unsafe {
intrinsics::transmute(0x6000 as usize + util::size_of::<EnvData>())
}
}
| {
(
// it's initially 0. make sure it's at least the first usable selector
util::max(2 + (EP_COUNT - FIRST_FREE_EP) as Selector, self.base.caps as Selector),
self.base.eps
)
} | identifier_body |
redirect.rs | use rustless::server::header;
use rustless::server::status;
use rustless::{Nesting};
#[test]
fn | () {
let app = app!(|api| {
api.prefix("api");
api.post("redirect_me/:href", |endpoint| {
endpoint.handle(|client, params| {
client.redirect(params.find(&"href".to_string()).unwrap().as_string().unwrap())
})
});
});
let response = call_app!(app, Post, "http://127.0.0.1:3000/api/redirect_me/google.com").ok().unwrap();
assert_eq!(response.status, status::StatusCode::Found);
let &header::Location(ref location) = response.headers.get::<header::Location>().unwrap();
assert_eq!(location, "google.com")
}
#[test]
fn it_allows_permanent_redirect() {
let app = app!(|api| {
api.prefix("api");
api.post("redirect_me/:href", |endpoint| {
endpoint.handle(|client, params| {
client.permanent_redirect(params.find(&"href".to_string()).unwrap().as_string().unwrap())
})
});
});
let response = call_app!(app, Post, "http://127.0.0.1:3000/api/redirect_me/google.com").ok().unwrap();
assert_eq!(response.status, status::StatusCode::MovedPermanently);
let &header::Location(ref location) = response.headers.get::<header::Location>().unwrap();
assert_eq!(location, "google.com")
} | it_allows_redirect | identifier_name |
redirect.rs | use rustless::server::header;
use rustless::server::status;
use rustless::{Nesting};
#[test]
fn it_allows_redirect() {
let app = app!(|api| {
api.prefix("api");
api.post("redirect_me/:href", |endpoint| {
endpoint.handle(|client, params| {
client.redirect(params.find(&"href".to_string()).unwrap().as_string().unwrap())
})
});
});
let response = call_app!(app, Post, "http://127.0.0.1:3000/api/redirect_me/google.com").ok().unwrap();
assert_eq!(response.status, status::StatusCode::Found);
let &header::Location(ref location) = response.headers.get::<header::Location>().unwrap();
assert_eq!(location, "google.com")
}
#[test]
fn it_allows_permanent_redirect() | {
let app = app!(|api| {
api.prefix("api");
api.post("redirect_me/:href", |endpoint| {
endpoint.handle(|client, params| {
client.permanent_redirect(params.find(&"href".to_string()).unwrap().as_string().unwrap())
})
});
});
let response = call_app!(app, Post, "http://127.0.0.1:3000/api/redirect_me/google.com").ok().unwrap();
assert_eq!(response.status, status::StatusCode::MovedPermanently);
let &header::Location(ref location) = response.headers.get::<header::Location>().unwrap();
assert_eq!(location, "google.com")
} | identifier_body |
|
redirect.rs | use rustless::server::header;
use rustless::server::status;
use rustless::{Nesting};
#[test]
fn it_allows_redirect() {
let app = app!(|api| {
api.prefix("api");
api.post("redirect_me/:href", |endpoint| { | });
});
let response = call_app!(app, Post, "http://127.0.0.1:3000/api/redirect_me/google.com").ok().unwrap();
assert_eq!(response.status, status::StatusCode::Found);
let &header::Location(ref location) = response.headers.get::<header::Location>().unwrap();
assert_eq!(location, "google.com")
}
#[test]
fn it_allows_permanent_redirect() {
let app = app!(|api| {
api.prefix("api");
api.post("redirect_me/:href", |endpoint| {
endpoint.handle(|client, params| {
client.permanent_redirect(params.find(&"href".to_string()).unwrap().as_string().unwrap())
})
});
});
let response = call_app!(app, Post, "http://127.0.0.1:3000/api/redirect_me/google.com").ok().unwrap();
assert_eq!(response.status, status::StatusCode::MovedPermanently);
let &header::Location(ref location) = response.headers.get::<header::Location>().unwrap();
assert_eq!(location, "google.com")
} | endpoint.handle(|client, params| {
client.redirect(params.find(&"href".to_string()).unwrap().as_string().unwrap())
}) | random_line_split |
list.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/. */
//! `list` computed values.
#[cfg(feature = "gecko")]
pub use crate::values::specified::list::ListStyleType;
pub use crate::values::specified::list::{QuotePair, Quotes};
| lazy_static! {
static ref INITIAL_QUOTES: Arc<Box<[QuotePair]>> = Arc::new(
vec![
QuotePair {
opening: "\u{201c}".to_owned().into_boxed_str(),
closing: "\u{201d}".to_owned().into_boxed_str(),
},
QuotePair {
opening: "\u{2018}".to_owned().into_boxed_str(),
closing: "\u{2019}".to_owned().into_boxed_str(),
},
]
.into_boxed_slice()
);
}
impl Quotes {
/// Initial value for `quotes`.
#[inline]
pub fn get_initial_value() -> Quotes {
Quotes(INITIAL_QUOTES.clone())
}
} | use servo_arc::Arc;
| random_line_split |
list.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/. */
//! `list` computed values.
#[cfg(feature = "gecko")]
pub use crate::values::specified::list::ListStyleType;
pub use crate::values::specified::list::{QuotePair, Quotes};
use servo_arc::Arc;
lazy_static! {
static ref INITIAL_QUOTES: Arc<Box<[QuotePair]>> = Arc::new(
vec![
QuotePair {
opening: "\u{201c}".to_owned().into_boxed_str(),
closing: "\u{201d}".to_owned().into_boxed_str(),
},
QuotePair {
opening: "\u{2018}".to_owned().into_boxed_str(),
closing: "\u{2019}".to_owned().into_boxed_str(),
},
]
.into_boxed_slice()
);
}
impl Quotes {
/// Initial value for `quotes`.
#[inline]
pub fn get_initial_value() -> Quotes |
}
| {
Quotes(INITIAL_QUOTES.clone())
} | identifier_body |
list.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/. */
//! `list` computed values.
#[cfg(feature = "gecko")]
pub use crate::values::specified::list::ListStyleType;
pub use crate::values::specified::list::{QuotePair, Quotes};
use servo_arc::Arc;
lazy_static! {
static ref INITIAL_QUOTES: Arc<Box<[QuotePair]>> = Arc::new(
vec![
QuotePair {
opening: "\u{201c}".to_owned().into_boxed_str(),
closing: "\u{201d}".to_owned().into_boxed_str(),
},
QuotePair {
opening: "\u{2018}".to_owned().into_boxed_str(),
closing: "\u{2019}".to_owned().into_boxed_str(),
},
]
.into_boxed_slice()
);
}
impl Quotes {
/// Initial value for `quotes`.
#[inline]
pub fn | () -> Quotes {
Quotes(INITIAL_QUOTES.clone())
}
}
| get_initial_value | identifier_name |
mod.rs | // The MIT License (MIT)
// | // in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//! Native implementation for Mac OSX
pub use self::window::WindowImpl;
pub use self::window_mask::WindowMask;
pub mod window_mask;
pub mod cursor;
pub mod mouse;
pub mod keyboard;
pub mod gl;
pub mod context_settings;
mod window;
mod ffi; | // Copyright (c) 2014 Jeremy Letang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal | random_line_split |
diagnostic.rs | Note);
}
pub fn span_end_note(&self, sp: Span, msg: &str) {
self.handler.custom_emit(&self.cm, EndSpan(sp), msg, Note);
}
pub fn span_help(&self, sp: Span, msg: &str) {
self.handler.emit(Some((&self.cm, sp)), msg, Help);
}
/// Prints out a message with a suggested edit of the code.
///
/// See `diagnostic::RenderSpan::Suggestion` for more information.
pub fn span_suggestion(&self, sp: Span, msg: &str, suggestion: String) {
self.handler.custom_emit(&self.cm, Suggestion(sp, suggestion), msg, Help);
}
pub fn fileline_note(&self, sp: Span, msg: &str) {
self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
}
pub fn fileline_help(&self, sp: Span, msg: &str) {
self.handler.custom_emit(&self.cm, FileLine(sp), msg, Help);
}
pub fn span_bug(&self, sp: Span, msg: &str) ->! {
self.handler.emit(Some((&self.cm, sp)), msg, Bug);
panic!(ExplicitBug);
}
pub fn span_unimpl(&self, sp: Span, msg: &str) ->! {
self.span_bug(sp, &format!("unimplemented {}", msg));
}
pub fn handler<'a>(&'a self) -> &'a Handler {
&self.handler
}
}
/// A handler deals with errors; certain errors
/// (fatal, bug, unimpl) may cause immediate exit,
/// others log errors for later reporting.
pub struct Handler {
err_count: Cell<usize>,
emit: RefCell<Box<Emitter + Send>>,
pub can_emit_warnings: bool
}
impl Handler {
pub fn new(color_config: ColorConfig,
registry: Option<diagnostics::registry::Registry>,
can_emit_warnings: bool) -> Handler {
let emitter = Box::new(EmitterWriter::stderr(color_config, registry));
Handler::with_emitter(can_emit_warnings, emitter)
}
pub fn with_emitter(can_emit_warnings: bool, e: Box<Emitter + Send>) -> Handler {
Handler {
err_count: Cell::new(0),
emit: RefCell::new(e),
can_emit_warnings: can_emit_warnings
}
}
pub fn fatal(&self, msg: &str) ->! {
self.emit.borrow_mut().emit(None, msg, None, Fatal);
panic!(FatalError);
}
pub fn err(&self, msg: &str) {
self.emit.borrow_mut().emit(None, msg, None, Error);
self.bump_err_count();
}
pub fn bump_err_count(&self) {
self.err_count.set(self.err_count.get() + 1);
}
pub fn err_count(&self) -> usize {
self.err_count.get()
}
pub fn has_errors(&self) -> bool {
self.err_count.get() > 0
}
pub fn abort_if_errors(&self) {
let s;
match self.err_count.get() {
0 => return,
1 => s = "aborting due to previous error".to_string(),
_ => {
s = format!("aborting due to {} previous errors",
self.err_count.get());
}
}
self.fatal(&s[..]);
}
pub fn warn(&self, msg: &str) {
self.emit.borrow_mut().emit(None, msg, None, Warning);
}
pub fn note(&self, msg: &str) {
self.emit.borrow_mut().emit(None, msg, None, Note);
}
pub fn help(&self, msg: &str) {
self.emit.borrow_mut().emit(None, msg, None, Help);
}
pub fn bug(&self, msg: &str) ->! {
self.emit.borrow_mut().emit(None, msg, None, Bug);
panic!(ExplicitBug);
}
pub fn unimpl(&self, msg: &str) ->! {
self.bug(&format!("unimplemented {}", msg));
}
pub fn emit(&self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
lvl: Level) {
if lvl == Warning &&!self.can_emit_warnings { return }
self.emit.borrow_mut().emit(cmsp, msg, None, lvl);
}
pub fn emit_with_code(&self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
code: &str,
lvl: Level) {
if lvl == Warning &&!self.can_emit_warnings { return }
self.emit.borrow_mut().emit(cmsp, msg, Some(code), lvl);
}
pub fn custom_emit(&self, cm: &codemap::CodeMap,
sp: RenderSpan, msg: &str, lvl: Level) {
if lvl == Warning &&!self.can_emit_warnings { return }
self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl);
}
}
#[derive(Copy, PartialEq, Clone, Debug)]
pub enum Level {
Bug,
Fatal,
Error,
Warning,
Note,
Help,
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use std::fmt::Display;
match *self {
Bug => "error: internal compiler error".fmt(f),
Fatal | Error => "error".fmt(f),
Warning => "warning".fmt(f),
Note => "note".fmt(f),
Help => "help".fmt(f),
}
}
}
impl Level {
fn color(self) -> term::color::Color {
match self {
Bug | Fatal | Error => term::color::BRIGHT_RED,
Warning => term::color::BRIGHT_YELLOW,
Note => term::color::BRIGHT_GREEN,
Help => term::color::BRIGHT_CYAN,
}
}
}
fn print_maybe_styled(w: &mut EmitterWriter,
msg: &str,
color: term::attr::Attr) -> io::Result<()> {
match w.dst {
Terminal(ref mut t) => {
try!(t.attr(color));
// If `msg` ends in a newline, we need to reset the color before
// the newline. We're making the assumption that we end up writing
// to a `LineBufferedWriter`, which means that emitting the reset
// after the newline ends up buffering the reset until we print
// another line or exit. Buffering the reset is a problem if we're
// sharing the terminal with any other programs (e.g. other rustc
// instances via `make -jN`).
//
// Note that if `msg` contains any internal newlines, this will
// result in the `LineBufferedWriter` flushing twice instead of
// once, which still leaves the opportunity for interleaved output
// to be miscolored. We assume this is rare enough that we don't
// have to worry about it.
if msg.ends_with("\n") {
try!(t.write_all(msg[..msg.len()-1].as_bytes()));
try!(t.reset());
try!(t.write_all(b"\n"));
} else {
try!(t.write_all(msg.as_bytes()));
try!(t.reset());
}
Ok(())
}
Raw(ref mut w) => w.write_all(msg.as_bytes()),
}
}
fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level,
msg: &str, code: Option<&str>) -> io::Result<()> {
if!topic.is_empty() {
try!(write!(&mut dst.dst, "{} ", topic));
}
try!(print_maybe_styled(dst,
&format!("{}: ", lvl.to_string()),
term::attr::ForegroundColor(lvl.color())));
try!(print_maybe_styled(dst,
&format!("{}", msg),
term::attr::Bold));
match code {
Some(code) => {
let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA);
try!(print_maybe_styled(dst, &format!(" [{}]", code.clone()), style));
}
None => ()
}
try!(write!(&mut dst.dst, "\n"));
Ok(())
}
pub struct EmitterWriter {
dst: Destination,
registry: Option<diagnostics::registry::Registry>
}
enum Destination {
Terminal(Box<term::Terminal<WriterWrapper> + Send>),
Raw(Box<Write + Send>),
}
impl EmitterWriter {
pub fn stderr(color_config: ColorConfig,
registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
let stderr = io::stderr();
let use_color = match color_config {
Always => true,
Never => false,
Auto => stderr_isatty(),
};
if use_color {
let dst = match term::stderr() {
Some(t) => Terminal(t),
None => Raw(Box::new(stderr)),
};
EmitterWriter { dst: dst, registry: registry }
} else {
EmitterWriter { dst: Raw(Box::new(stderr)), registry: registry }
}
}
pub fn new(dst: Box<Write + Send>,
registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
EmitterWriter { dst: Raw(dst), registry: registry }
}
}
#[cfg(unix)]
fn stderr_isatty() -> bool {
unsafe { libc::isatty(libc::STDERR_FILENO)!= 0 }
}
#[cfg(windows)]
fn stderr_isatty() -> bool {
const STD_ERROR_HANDLE: libc::DWORD = -12i32 as libc::DWORD;
extern "system" {
fn GetStdHandle(which: libc::DWORD) -> libc::HANDLE;
fn GetConsoleMode(hConsoleHandle: libc::HANDLE,
lpMode: libc::LPDWORD) -> libc::BOOL;
}
unsafe {
let handle = GetStdHandle(STD_ERROR_HANDLE);
let mut out = 0;
GetConsoleMode(handle, &mut out)!= 0
}
}
impl Write for Destination {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
match *self {
Terminal(ref mut t) => t.write(bytes),
Raw(ref mut w) => w.write(bytes),
}
}
fn flush(&mut self) -> io::Result<()> {
match *self {
Terminal(ref mut t) => t.flush(),
Raw(ref mut w) => w.flush(),
}
}
}
impl Emitter for EmitterWriter {
fn emit(&mut self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str, code: Option<&str>, lvl: Level) {
let error = match cmsp {
Some((cm, COMMAND_LINE_SP)) => emit(self, cm,
FileLine(COMMAND_LINE_SP),
msg, code, lvl),
Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, code, lvl),
None => print_diagnostic(self, "", lvl, msg, code),
};
match error {
Ok(()) => {}
Err(e) => panic!("failed to print diagnostics: {:?}", e),
}
}
fn custom_emit(&mut self, cm: &codemap::CodeMap,
sp: RenderSpan, msg: &str, lvl: Level) {
match emit(self, cm, sp, msg, None, lvl) {
Ok(()) => {}
Err(e) => panic!("failed to print diagnostics: {:?}", e),
}
}
}
fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
msg: &str, code: Option<&str>, lvl: Level) -> io::Result<()> {
let sp = rsp.span();
// We cannot check equality directly with COMMAND_LINE_SP
// since PartialEq is manually implemented to ignore the ExpnId
let ss = if sp.expn_id == COMMAND_LINE_EXPN {
"<command line option>".to_string()
} else if let EndSpan(_) = rsp {
let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id};
cm.span_to_string(span_end)
} else {
cm.span_to_string(sp)
};
try!(print_diagnostic(dst, &ss[..], lvl, msg, code));
match rsp {
FullSpan(_) => {
try!(highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp)));
try!(print_macro_backtrace(dst, cm, sp));
}
EndSpan(_) => {
try!(end_highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp)));
try!(print_macro_backtrace(dst, cm, sp));
}
Suggestion(_, ref suggestion) => {
try!(highlight_suggestion(dst, cm, sp, suggestion));
try!(print_macro_backtrace(dst, cm, sp));
}
FileLine(..) => {
// no source text in this case!
}
}
match code {
Some(code) =>
match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) {
Some(_) => {
try!(print_diagnostic(dst, &ss[..], Help,
&format!("run `rustc --explain {}` to see a detailed \
explanation", code), None));
}
None => ()
},
None => (),
}
Ok(())
}
fn highlight_suggestion(err: &mut EmitterWriter,
cm: &codemap::CodeMap,
sp: Span,
suggestion: &str)
-> io::Result<()>
{
let lines = cm.span_to_lines(sp).unwrap();
assert!(!lines.lines.is_empty());
// To build up the result, we want to take the snippet from the first
// line that precedes the span, prepend that with the suggestion, and
// then append the snippet from the last line that trails the span.
let fm = &lines.file;
let first_line = &lines.lines[0];
let prefix = fm.get_line(first_line.line_index)
.map(|l| &l[..first_line.start_col.0])
.unwrap_or("");
let last_line = lines.lines.last().unwrap();
let suffix = fm.get_line(last_line.line_index)
.map(|l| &l[last_line.end_col.0..])
.unwrap_or("");
let complete = format!("{}{}{}", prefix, suggestion, suffix);
// print the suggestion without any line numbers, but leave
// space for them. This helps with lining up with previous
// snippets from the actual error being reported.
let fm = &*lines.file;
let mut lines = complete.lines();
for (line, line_index) in lines.by_ref().take(MAX_LINES).zip(first_line.line_index..) {
let elided_line_num = format!("{}", line_index+1);
try!(write!(&mut err.dst, "{0}:{1:2$} {3}\n",
fm.name, "", elided_line_num.len(), line));
}
// if we elided some lines, add an ellipsis
if lines.next().is_some() {
let elided_line_num = format!("{}", first_line.line_index + MAX_LINES + 1);
try!(write!(&mut err.dst, "{0:1$} {0:2$}...\n",
"", fm.name.len(), elided_line_num.len())); |
fn highlight_lines(err: &mut EmitterWriter,
cm: &codemap::CodeMap,
sp: Span,
lvl: Level,
lines: codemap::FileLinesResult)
-> io::Result<()>
{
let lines = match lines {
Ok(lines) => lines,
Err(_) => {
try!(write!(&mut err.dst, "(internal compiler error: unprintable span)\n"));
return Ok(());
}
};
let fm = &*lines.file;
let line_strings: Option<Vec<&str>> =
lines.lines.iter()
.map(|info| fm.get_line(info.line_index))
.collect();
let line_strings = match line_strings {
None => { return Ok(()); }
Some(line_strings) => line_strings
};
// Display only the first MAX_LINES lines.
let all_lines = lines.lines.len();
let display_lines = cmp::min(all_lines, MAX_LINES);
let display_line_infos = &lines.lines[..display_lines];
let display_line_strings = &line_strings[..display_lines];
// Calculate the widest number to format evenly and fix #11715
assert!(display_line_infos.len() > 0);
let mut max_line_num = display_line_infos[display_line_infos.len() - 1].line_index + 1;
let mut digits = 0;
while max_line_num > 0 {
max_line_num /= 10;
digits += 1;
}
// Print the offending lines
for (line_info, line) in display_line_infos.iter().zip(display_line_strings) {
try!(write!(&mut err.dst, "{}:{:>width$} {}\n",
fm.name,
line_info.line_index + 1,
line,
width=digits));
}
// If we elided something, put an ellipsis.
if display_lines < all_lines {
let last_line_index = display_line_infos.last().unwrap().line_index;
let s = format!("{}:{} ", fm.name, last_line_index + 1);
try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len()));
}
// FIXME (#3260)
// If there's one line at fault we can easily point to the problem
if lines.lines.len() == 1 {
let lo = cm.lookup_char_pos(sp.lo);
let mut digits = 0;
let mut num = (lines.lines[0].line_index + 1) / 10;
// how many digits must be indent past?
while num > 0 { num /= 10; digits += 1; }
let mut s = String::new();
// Skip is the number of characters we need to skip because they are
// part of the 'filename:line'part of the previous line.
let skip = fm.name.chars().count() + digits + 3;
for _ in 0..skip {
s.push(' ');
}
if let Some(orig) = fm.get_line(lines.lines[0].line_index) {
let mut col = skip;
let mut lastc ='';
let mut iter = orig.chars().enumerate();
for (pos, ch) in iter.by_ref() {
lastc = ch;
if pos >= lo.col.to_usize() { break; }
// Whenever a tab occurs on the previous line, we insert one on
// the error-point-squiggly-line as well (instead of a space).
// That way the squiggly line will usually appear in the correct
// position.
match ch {
'\t' => {
col += 8 - col%8;
s.push('\t');
},
_ => {
| }
Ok(())
} | random_line_split |
diagnostic.rs |
}
None => ()
}
try!(write!(&mut dst.dst, "\n"));
Ok(())
}
pub struct EmitterWriter {
dst: Destination,
registry: Option<diagnostics::registry::Registry>
}
enum Destination {
Terminal(Box<term::Terminal<WriterWrapper> + Send>),
Raw(Box<Write + Send>),
}
impl EmitterWriter {
pub fn stderr(color_config: ColorConfig,
registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
let stderr = io::stderr();
let use_color = match color_config {
Always => true,
Never => false,
Auto => stderr_isatty(),
};
if use_color {
let dst = match term::stderr() {
Some(t) => Terminal(t),
None => Raw(Box::new(stderr)),
};
EmitterWriter { dst: dst, registry: registry }
} else {
EmitterWriter { dst: Raw(Box::new(stderr)), registry: registry }
}
}
pub fn new(dst: Box<Write + Send>,
registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
EmitterWriter { dst: Raw(dst), registry: registry }
}
}
#[cfg(unix)]
fn stderr_isatty() -> bool {
unsafe { libc::isatty(libc::STDERR_FILENO)!= 0 }
}
#[cfg(windows)]
fn stderr_isatty() -> bool {
const STD_ERROR_HANDLE: libc::DWORD = -12i32 as libc::DWORD;
extern "system" {
fn GetStdHandle(which: libc::DWORD) -> libc::HANDLE;
fn GetConsoleMode(hConsoleHandle: libc::HANDLE,
lpMode: libc::LPDWORD) -> libc::BOOL;
}
unsafe {
let handle = GetStdHandle(STD_ERROR_HANDLE);
let mut out = 0;
GetConsoleMode(handle, &mut out)!= 0
}
}
impl Write for Destination {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
match *self {
Terminal(ref mut t) => t.write(bytes),
Raw(ref mut w) => w.write(bytes),
}
}
fn flush(&mut self) -> io::Result<()> {
match *self {
Terminal(ref mut t) => t.flush(),
Raw(ref mut w) => w.flush(),
}
}
}
impl Emitter for EmitterWriter {
fn emit(&mut self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str, code: Option<&str>, lvl: Level) {
let error = match cmsp {
Some((cm, COMMAND_LINE_SP)) => emit(self, cm,
FileLine(COMMAND_LINE_SP),
msg, code, lvl),
Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, code, lvl),
None => print_diagnostic(self, "", lvl, msg, code),
};
match error {
Ok(()) => {}
Err(e) => panic!("failed to print diagnostics: {:?}", e),
}
}
fn custom_emit(&mut self, cm: &codemap::CodeMap,
sp: RenderSpan, msg: &str, lvl: Level) {
match emit(self, cm, sp, msg, None, lvl) {
Ok(()) => {}
Err(e) => panic!("failed to print diagnostics: {:?}", e),
}
}
}
fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
msg: &str, code: Option<&str>, lvl: Level) -> io::Result<()> {
let sp = rsp.span();
// We cannot check equality directly with COMMAND_LINE_SP
// since PartialEq is manually implemented to ignore the ExpnId
let ss = if sp.expn_id == COMMAND_LINE_EXPN {
"<command line option>".to_string()
} else if let EndSpan(_) = rsp {
let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id};
cm.span_to_string(span_end)
} else {
cm.span_to_string(sp)
};
try!(print_diagnostic(dst, &ss[..], lvl, msg, code));
match rsp {
FullSpan(_) => {
try!(highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp)));
try!(print_macro_backtrace(dst, cm, sp));
}
EndSpan(_) => {
try!(end_highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp)));
try!(print_macro_backtrace(dst, cm, sp));
}
Suggestion(_, ref suggestion) => {
try!(highlight_suggestion(dst, cm, sp, suggestion));
try!(print_macro_backtrace(dst, cm, sp));
}
FileLine(..) => {
// no source text in this case!
}
}
match code {
Some(code) =>
match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) {
Some(_) => {
try!(print_diagnostic(dst, &ss[..], Help,
&format!("run `rustc --explain {}` to see a detailed \
explanation", code), None));
}
None => ()
},
None => (),
}
Ok(())
}
fn highlight_suggestion(err: &mut EmitterWriter,
cm: &codemap::CodeMap,
sp: Span,
suggestion: &str)
-> io::Result<()>
{
let lines = cm.span_to_lines(sp).unwrap();
assert!(!lines.lines.is_empty());
// To build up the result, we want to take the snippet from the first
// line that precedes the span, prepend that with the suggestion, and
// then append the snippet from the last line that trails the span.
let fm = &lines.file;
let first_line = &lines.lines[0];
let prefix = fm.get_line(first_line.line_index)
.map(|l| &l[..first_line.start_col.0])
.unwrap_or("");
let last_line = lines.lines.last().unwrap();
let suffix = fm.get_line(last_line.line_index)
.map(|l| &l[last_line.end_col.0..])
.unwrap_or("");
let complete = format!("{}{}{}", prefix, suggestion, suffix);
// print the suggestion without any line numbers, but leave
// space for them. This helps with lining up with previous
// snippets from the actual error being reported.
let fm = &*lines.file;
let mut lines = complete.lines();
for (line, line_index) in lines.by_ref().take(MAX_LINES).zip(first_line.line_index..) {
let elided_line_num = format!("{}", line_index+1);
try!(write!(&mut err.dst, "{0}:{1:2$} {3}\n",
fm.name, "", elided_line_num.len(), line));
}
// if we elided some lines, add an ellipsis
if lines.next().is_some() {
let elided_line_num = format!("{}", first_line.line_index + MAX_LINES + 1);
try!(write!(&mut err.dst, "{0:1$} {0:2$}...\n",
"", fm.name.len(), elided_line_num.len()));
}
Ok(())
}
fn highlight_lines(err: &mut EmitterWriter,
cm: &codemap::CodeMap,
sp: Span,
lvl: Level,
lines: codemap::FileLinesResult)
-> io::Result<()>
{
let lines = match lines {
Ok(lines) => lines,
Err(_) => {
try!(write!(&mut err.dst, "(internal compiler error: unprintable span)\n"));
return Ok(());
}
};
let fm = &*lines.file;
let line_strings: Option<Vec<&str>> =
lines.lines.iter()
.map(|info| fm.get_line(info.line_index))
.collect();
let line_strings = match line_strings {
None => { return Ok(()); }
Some(line_strings) => line_strings
};
// Display only the first MAX_LINES lines.
let all_lines = lines.lines.len();
let display_lines = cmp::min(all_lines, MAX_LINES);
let display_line_infos = &lines.lines[..display_lines];
let display_line_strings = &line_strings[..display_lines];
// Calculate the widest number to format evenly and fix #11715
assert!(display_line_infos.len() > 0);
let mut max_line_num = display_line_infos[display_line_infos.len() - 1].line_index + 1;
let mut digits = 0;
while max_line_num > 0 {
max_line_num /= 10;
digits += 1;
}
// Print the offending lines
for (line_info, line) in display_line_infos.iter().zip(display_line_strings) {
try!(write!(&mut err.dst, "{}:{:>width$} {}\n",
fm.name,
line_info.line_index + 1,
line,
width=digits));
}
// If we elided something, put an ellipsis.
if display_lines < all_lines {
let last_line_index = display_line_infos.last().unwrap().line_index;
let s = format!("{}:{} ", fm.name, last_line_index + 1);
try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len()));
}
// FIXME (#3260)
// If there's one line at fault we can easily point to the problem
if lines.lines.len() == 1 {
let lo = cm.lookup_char_pos(sp.lo);
let mut digits = 0;
let mut num = (lines.lines[0].line_index + 1) / 10;
// how many digits must be indent past?
while num > 0 { num /= 10; digits += 1; }
let mut s = String::new();
// Skip is the number of characters we need to skip because they are
// part of the 'filename:line'part of the previous line.
let skip = fm.name.chars().count() + digits + 3;
for _ in 0..skip {
s.push(' ');
}
if let Some(orig) = fm.get_line(lines.lines[0].line_index) {
let mut col = skip;
let mut lastc ='';
let mut iter = orig.chars().enumerate();
for (pos, ch) in iter.by_ref() {
lastc = ch;
if pos >= lo.col.to_usize() { break; }
// Whenever a tab occurs on the previous line, we insert one on
// the error-point-squiggly-line as well (instead of a space).
// That way the squiggly line will usually appear in the correct
// position.
match ch {
'\t' => {
col += 8 - col%8;
s.push('\t');
},
_ => {
col += 1;
s.push(' ');
},
}
}
try!(write!(&mut err.dst, "{}", s));
let mut s = String::from("^");
let count = match lastc {
// Most terminals have a tab stop every eight columns by default
'\t' => 8 - col%8,
_ => 1,
};
col += count;
s.extend(::std::iter::repeat('~').take(count));
let hi = cm.lookup_char_pos(sp.hi);
if hi.col!= lo.col {
for (pos, ch) in iter {
if pos >= hi.col.to_usize() { break; }
let count = match ch {
'\t' => 8 - col%8,
_ => 1,
};
col += count;
s.extend(::std::iter::repeat('~').take(count));
}
}
if s.len() > 1 {
// One extra squiggly is replaced by a "^"
s.pop();
}
try!(print_maybe_styled(err,
&format!("{}\n", s),
term::attr::ForegroundColor(lvl.color())));
}
}
Ok(())
}
/// Here are the differences between this and the normal `highlight_lines`:
/// `end_highlight_lines` will always put arrow on the last byte of the
/// span (instead of the first byte). Also, when the span is too long (more
/// than 6 lines), `end_highlight_lines` will print the first line, then
/// dot dot dot, then last line, whereas `highlight_lines` prints the first
/// six lines.
#[allow(deprecated)]
fn end_highlight_lines(w: &mut EmitterWriter,
cm: &codemap::CodeMap,
sp: Span,
lvl: Level,
lines: codemap::FileLinesResult)
-> io::Result<()> {
let lines = match lines {
Ok(lines) => lines,
Err(_) => {
try!(write!(&mut w.dst, "(internal compiler error: unprintable span)\n"));
return Ok(());
}
};
let fm = &*lines.file;
let lines = &lines.lines[..];
if lines.len() > MAX_LINES {
if let Some(line) = fm.get_line(lines[0].line_index) {
try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
lines[0].line_index + 1, line));
}
try!(write!(&mut w.dst, "...\n"));
let last_line_index = lines[lines.len() - 1].line_index;
if let Some(last_line) = fm.get_line(last_line_index) {
try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
last_line_index + 1, last_line));
}
} else {
for line_info in lines {
if let Some(line) = fm.get_line(line_info.line_index) {
try!(write!(&mut w.dst, "{}:{} {}\n", fm.name,
line_info.line_index + 1, line));
}
}
}
let last_line_start = format!("{}:{} ", fm.name, lines[lines.len()-1].line_index + 1);
let hi = cm.lookup_char_pos(sp.hi);
let skip = last_line_start.chars().count();
let mut s = String::new();
for _ in 0..skip {
s.push(' ');
}
if let Some(orig) = fm.get_line(lines[0].line_index) {
let iter = orig.chars().enumerate();
for (pos, ch) in iter {
// Span seems to use half-opened interval, so subtract 1
if pos >= hi.col.to_usize() - 1 { break; }
// Whenever a tab occurs on the previous line, we insert one on
// the error-point-squiggly-line as well (instead of a space).
// That way the squiggly line will usually appear in the correct
// position.
match ch {
'\t' => s.push('\t'),
_ => s.push(' '),
}
}
}
s.push('^');
s.push('\n');
print_maybe_styled(w,
&s[..],
term::attr::ForegroundColor(lvl.color()))
}
fn print_macro_backtrace(w: &mut EmitterWriter,
cm: &codemap::CodeMap,
sp: Span)
-> io::Result<()> {
let cs = try!(cm.with_expn_info(sp.expn_id, |expn_info| -> io::Result<_> {
match expn_info {
Some(ei) => {
let ss = ei.callee.span.map_or(String::new(),
|span| cm.span_to_string(span));
let (pre, post) = match ei.callee.format {
codemap::MacroAttribute => ("#[", "]"),
codemap::MacroBang => ("", "!"),
codemap::CompilerExpansion => ("", ""),
};
try!(print_diagnostic(w, &ss, Note,
&format!("in expansion of {}{}{}",
pre,
ei.callee.name,
post),
None));
let ss = cm.span_to_string(ei.call_site);
try!(print_diagnostic(w, &ss, Note, "expansion site", None));
Ok(Some(ei.call_site))
}
None => Ok(None)
}
}));
cs.map_or(Ok(()), |call_site| print_macro_backtrace(w, cm, call_site))
}
pub fn expect<T, M>(diag: &SpanHandler, opt: Option<T>, msg: M) -> T where
M: FnOnce() -> String,
{
match opt {
Some(t) => t,
None => diag.handler().bug(&msg()),
}
}
#[cfg(test)]
mod test {
use super::{EmitterWriter, highlight_lines, Level};
use codemap::{mk_sp, CodeMap, BytePos};
use std::sync::{Arc, Mutex};
use std::io::{self, Write};
use std::str::from_utf8;
// Diagnostic doesn't align properly in span where line number increases by one digit
#[test]
fn test_hilight_suggestion_issue_11715() {
struct Sink(Arc<Mutex<Vec<u8>>>);
impl Write for Sink {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
Write::write(&mut *self.0.lock().unwrap(), data)
}
fn flush(&mut self) -> io::Result<()> | { Ok(()) } | identifier_body |
|
diagnostic.rs |
}
pub fn span_end_note(&self, sp: Span, msg: &str) {
self.handler.custom_emit(&self.cm, EndSpan(sp), msg, Note);
}
pub fn span_help(&self, sp: Span, msg: &str) {
self.handler.emit(Some((&self.cm, sp)), msg, Help);
}
/// Prints out a message with a suggested edit of the code.
///
/// See `diagnostic::RenderSpan::Suggestion` for more information.
pub fn span_suggestion(&self, sp: Span, msg: &str, suggestion: String) {
self.handler.custom_emit(&self.cm, Suggestion(sp, suggestion), msg, Help);
}
pub fn fileline_note(&self, sp: Span, msg: &str) {
self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
}
pub fn fileline_help(&self, sp: Span, msg: &str) {
self.handler.custom_emit(&self.cm, FileLine(sp), msg, Help);
}
pub fn span_bug(&self, sp: Span, msg: &str) ->! {
self.handler.emit(Some((&self.cm, sp)), msg, Bug);
panic!(ExplicitBug);
}
pub fn span_unimpl(&self, sp: Span, msg: &str) ->! {
self.span_bug(sp, &format!("unimplemented {}", msg));
}
pub fn handler<'a>(&'a self) -> &'a Handler {
&self.handler
}
}
/// A handler deals with errors; certain errors
/// (fatal, bug, unimpl) may cause immediate exit,
/// others log errors for later reporting.
pub struct Handler {
err_count: Cell<usize>,
emit: RefCell<Box<Emitter + Send>>,
pub can_emit_warnings: bool
}
impl Handler {
pub fn new(color_config: ColorConfig,
registry: Option<diagnostics::registry::Registry>,
can_emit_warnings: bool) -> Handler {
let emitter = Box::new(EmitterWriter::stderr(color_config, registry));
Handler::with_emitter(can_emit_warnings, emitter)
}
pub fn with_emitter(can_emit_warnings: bool, e: Box<Emitter + Send>) -> Handler {
Handler {
err_count: Cell::new(0),
emit: RefCell::new(e),
can_emit_warnings: can_emit_warnings
}
}
pub fn fatal(&self, msg: &str) ->! {
self.emit.borrow_mut().emit(None, msg, None, Fatal);
panic!(FatalError);
}
pub fn err(&self, msg: &str) {
self.emit.borrow_mut().emit(None, msg, None, Error);
self.bump_err_count();
}
pub fn bump_err_count(&self) {
self.err_count.set(self.err_count.get() + 1);
}
pub fn err_count(&self) -> usize {
self.err_count.get()
}
pub fn has_errors(&self) -> bool {
self.err_count.get() > 0
}
pub fn abort_if_errors(&self) {
let s;
match self.err_count.get() {
0 => return,
1 => s = "aborting due to previous error".to_string(),
_ => {
s = format!("aborting due to {} previous errors",
self.err_count.get());
}
}
self.fatal(&s[..]);
}
pub fn warn(&self, msg: &str) {
self.emit.borrow_mut().emit(None, msg, None, Warning);
}
pub fn note(&self, msg: &str) {
self.emit.borrow_mut().emit(None, msg, None, Note);
}
pub fn help(&self, msg: &str) {
self.emit.borrow_mut().emit(None, msg, None, Help);
}
pub fn bug(&self, msg: &str) ->! {
self.emit.borrow_mut().emit(None, msg, None, Bug);
panic!(ExplicitBug);
}
pub fn unimpl(&self, msg: &str) ->! {
self.bug(&format!("unimplemented {}", msg));
}
pub fn emit(&self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
lvl: Level) {
if lvl == Warning &&!self.can_emit_warnings { return }
self.emit.borrow_mut().emit(cmsp, msg, None, lvl);
}
pub fn emit_with_code(&self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
code: &str,
lvl: Level) {
if lvl == Warning &&!self.can_emit_warnings { return }
self.emit.borrow_mut().emit(cmsp, msg, Some(code), lvl);
}
pub fn custom_emit(&self, cm: &codemap::CodeMap,
sp: RenderSpan, msg: &str, lvl: Level) {
if lvl == Warning &&!self.can_emit_warnings { return }
self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl);
}
}
#[derive(Copy, PartialEq, Clone, Debug)]
pub enum Level {
Bug,
Fatal,
Error,
Warning,
Note,
Help,
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use std::fmt::Display;
match *self {
Bug => "error: internal compiler error".fmt(f),
Fatal | Error => "error".fmt(f),
Warning => "warning".fmt(f),
Note => "note".fmt(f),
Help => "help".fmt(f),
}
}
}
impl Level {
fn color(self) -> term::color::Color {
match self {
Bug | Fatal | Error => term::color::BRIGHT_RED,
Warning => term::color::BRIGHT_YELLOW,
Note => term::color::BRIGHT_GREEN,
Help => term::color::BRIGHT_CYAN,
}
}
}
fn print_maybe_styled(w: &mut EmitterWriter,
msg: &str,
color: term::attr::Attr) -> io::Result<()> {
match w.dst {
Terminal(ref mut t) => {
try!(t.attr(color));
// If `msg` ends in a newline, we need to reset the color before
// the newline. We're making the assumption that we end up writing
// to a `LineBufferedWriter`, which means that emitting the reset
// after the newline ends up buffering the reset until we print
// another line or exit. Buffering the reset is a problem if we're
// sharing the terminal with any other programs (e.g. other rustc
// instances via `make -jN`).
//
// Note that if `msg` contains any internal newlines, this will
// result in the `LineBufferedWriter` flushing twice instead of
// once, which still leaves the opportunity for interleaved output
// to be miscolored. We assume this is rare enough that we don't
// have to worry about it.
if msg.ends_with("\n") {
try!(t.write_all(msg[..msg.len()-1].as_bytes()));
try!(t.reset());
try!(t.write_all(b"\n"));
} else {
try!(t.write_all(msg.as_bytes()));
try!(t.reset());
}
Ok(())
}
Raw(ref mut w) => w.write_all(msg.as_bytes()),
}
}
fn | (dst: &mut EmitterWriter, topic: &str, lvl: Level,
msg: &str, code: Option<&str>) -> io::Result<()> {
if!topic.is_empty() {
try!(write!(&mut dst.dst, "{} ", topic));
}
try!(print_maybe_styled(dst,
&format!("{}: ", lvl.to_string()),
term::attr::ForegroundColor(lvl.color())));
try!(print_maybe_styled(dst,
&format!("{}", msg),
term::attr::Bold));
match code {
Some(code) => {
let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA);
try!(print_maybe_styled(dst, &format!(" [{}]", code.clone()), style));
}
None => ()
}
try!(write!(&mut dst.dst, "\n"));
Ok(())
}
pub struct EmitterWriter {
dst: Destination,
registry: Option<diagnostics::registry::Registry>
}
enum Destination {
Terminal(Box<term::Terminal<WriterWrapper> + Send>),
Raw(Box<Write + Send>),
}
impl EmitterWriter {
pub fn stderr(color_config: ColorConfig,
registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
let stderr = io::stderr();
let use_color = match color_config {
Always => true,
Never => false,
Auto => stderr_isatty(),
};
if use_color {
let dst = match term::stderr() {
Some(t) => Terminal(t),
None => Raw(Box::new(stderr)),
};
EmitterWriter { dst: dst, registry: registry }
} else {
EmitterWriter { dst: Raw(Box::new(stderr)), registry: registry }
}
}
pub fn new(dst: Box<Write + Send>,
registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
EmitterWriter { dst: Raw(dst), registry: registry }
}
}
#[cfg(unix)]
fn stderr_isatty() -> bool {
unsafe { libc::isatty(libc::STDERR_FILENO)!= 0 }
}
#[cfg(windows)]
fn stderr_isatty() -> bool {
const STD_ERROR_HANDLE: libc::DWORD = -12i32 as libc::DWORD;
extern "system" {
fn GetStdHandle(which: libc::DWORD) -> libc::HANDLE;
fn GetConsoleMode(hConsoleHandle: libc::HANDLE,
lpMode: libc::LPDWORD) -> libc::BOOL;
}
unsafe {
let handle = GetStdHandle(STD_ERROR_HANDLE);
let mut out = 0;
GetConsoleMode(handle, &mut out)!= 0
}
}
impl Write for Destination {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
match *self {
Terminal(ref mut t) => t.write(bytes),
Raw(ref mut w) => w.write(bytes),
}
}
fn flush(&mut self) -> io::Result<()> {
match *self {
Terminal(ref mut t) => t.flush(),
Raw(ref mut w) => w.flush(),
}
}
}
impl Emitter for EmitterWriter {
fn emit(&mut self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str, code: Option<&str>, lvl: Level) {
let error = match cmsp {
Some((cm, COMMAND_LINE_SP)) => emit(self, cm,
FileLine(COMMAND_LINE_SP),
msg, code, lvl),
Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, code, lvl),
None => print_diagnostic(self, "", lvl, msg, code),
};
match error {
Ok(()) => {}
Err(e) => panic!("failed to print diagnostics: {:?}", e),
}
}
fn custom_emit(&mut self, cm: &codemap::CodeMap,
sp: RenderSpan, msg: &str, lvl: Level) {
match emit(self, cm, sp, msg, None, lvl) {
Ok(()) => {}
Err(e) => panic!("failed to print diagnostics: {:?}", e),
}
}
}
fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
msg: &str, code: Option<&str>, lvl: Level) -> io::Result<()> {
let sp = rsp.span();
// We cannot check equality directly with COMMAND_LINE_SP
// since PartialEq is manually implemented to ignore the ExpnId
let ss = if sp.expn_id == COMMAND_LINE_EXPN {
"<command line option>".to_string()
} else if let EndSpan(_) = rsp {
let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id};
cm.span_to_string(span_end)
} else {
cm.span_to_string(sp)
};
try!(print_diagnostic(dst, &ss[..], lvl, msg, code));
match rsp {
FullSpan(_) => {
try!(highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp)));
try!(print_macro_backtrace(dst, cm, sp));
}
EndSpan(_) => {
try!(end_highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp)));
try!(print_macro_backtrace(dst, cm, sp));
}
Suggestion(_, ref suggestion) => {
try!(highlight_suggestion(dst, cm, sp, suggestion));
try!(print_macro_backtrace(dst, cm, sp));
}
FileLine(..) => {
// no source text in this case!
}
}
match code {
Some(code) =>
match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) {
Some(_) => {
try!(print_diagnostic(dst, &ss[..], Help,
&format!("run `rustc --explain {}` to see a detailed \
explanation", code), None));
}
None => ()
},
None => (),
}
Ok(())
}
fn highlight_suggestion(err: &mut EmitterWriter,
cm: &codemap::CodeMap,
sp: Span,
suggestion: &str)
-> io::Result<()>
{
let lines = cm.span_to_lines(sp).unwrap();
assert!(!lines.lines.is_empty());
// To build up the result, we want to take the snippet from the first
// line that precedes the span, prepend that with the suggestion, and
// then append the snippet from the last line that trails the span.
let fm = &lines.file;
let first_line = &lines.lines[0];
let prefix = fm.get_line(first_line.line_index)
.map(|l| &l[..first_line.start_col.0])
.unwrap_or("");
let last_line = lines.lines.last().unwrap();
let suffix = fm.get_line(last_line.line_index)
.map(|l| &l[last_line.end_col.0..])
.unwrap_or("");
let complete = format!("{}{}{}", prefix, suggestion, suffix);
// print the suggestion without any line numbers, but leave
// space for them. This helps with lining up with previous
// snippets from the actual error being reported.
let fm = &*lines.file;
let mut lines = complete.lines();
for (line, line_index) in lines.by_ref().take(MAX_LINES).zip(first_line.line_index..) {
let elided_line_num = format!("{}", line_index+1);
try!(write!(&mut err.dst, "{0}:{1:2$} {3}\n",
fm.name, "", elided_line_num.len(), line));
}
// if we elided some lines, add an ellipsis
if lines.next().is_some() {
let elided_line_num = format!("{}", first_line.line_index + MAX_LINES + 1);
try!(write!(&mut err.dst, "{0:1$} {0:2$}...\n",
"", fm.name.len(), elided_line_num.len()));
}
Ok(())
}
fn highlight_lines(err: &mut EmitterWriter,
cm: &codemap::CodeMap,
sp: Span,
lvl: Level,
lines: codemap::FileLinesResult)
-> io::Result<()>
{
let lines = match lines {
Ok(lines) => lines,
Err(_) => {
try!(write!(&mut err.dst, "(internal compiler error: unprintable span)\n"));
return Ok(());
}
};
let fm = &*lines.file;
let line_strings: Option<Vec<&str>> =
lines.lines.iter()
.map(|info| fm.get_line(info.line_index))
.collect();
let line_strings = match line_strings {
None => { return Ok(()); }
Some(line_strings) => line_strings
};
// Display only the first MAX_LINES lines.
let all_lines = lines.lines.len();
let display_lines = cmp::min(all_lines, MAX_LINES);
let display_line_infos = &lines.lines[..display_lines];
let display_line_strings = &line_strings[..display_lines];
// Calculate the widest number to format evenly and fix #11715
assert!(display_line_infos.len() > 0);
let mut max_line_num = display_line_infos[display_line_infos.len() - 1].line_index + 1;
let mut digits = 0;
while max_line_num > 0 {
max_line_num /= 10;
digits += 1;
}
// Print the offending lines
for (line_info, line) in display_line_infos.iter().zip(display_line_strings) {
try!(write!(&mut err.dst, "{}:{:>width$} {}\n",
fm.name,
line_info.line_index + 1,
line,
width=digits));
}
// If we elided something, put an ellipsis.
if display_lines < all_lines {
let last_line_index = display_line_infos.last().unwrap().line_index;
let s = format!("{}:{} ", fm.name, last_line_index + 1);
try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len()));
}
// FIXME (#3260)
// If there's one line at fault we can easily point to the problem
if lines.lines.len() == 1 {
let lo = cm.lookup_char_pos(sp.lo);
let mut digits = 0;
let mut num = (lines.lines[0].line_index + 1) / 10;
// how many digits must be indent past?
while num > 0 { num /= 10; digits += 1; }
let mut s = String::new();
// Skip is the number of characters we need to skip because they are
// part of the 'filename:line'part of the previous line.
let skip = fm.name.chars().count() + digits + 3;
for _ in 0..skip {
s.push(' ');
}
if let Some(orig) = fm.get_line(lines.lines[0].line_index) {
let mut col = skip;
let mut lastc ='';
let mut iter = orig.chars().enumerate();
for (pos, ch) in iter.by_ref() {
lastc = ch;
if pos >= lo.col.to_usize() { break; }
// Whenever a tab occurs on the previous line, we insert one on
// the error-point-squiggly-line as well (instead of a space).
// That way the squiggly line will usually appear in the correct
// position.
match ch {
'\t' => {
col += 8 - col%8;
s.push('\t');
},
_ => {
| print_diagnostic | identifier_name |
diagnostic.rs |
}
pub fn span_end_note(&self, sp: Span, msg: &str) {
self.handler.custom_emit(&self.cm, EndSpan(sp), msg, Note);
}
pub fn span_help(&self, sp: Span, msg: &str) {
self.handler.emit(Some((&self.cm, sp)), msg, Help);
}
/// Prints out a message with a suggested edit of the code.
///
/// See `diagnostic::RenderSpan::Suggestion` for more information.
pub fn span_suggestion(&self, sp: Span, msg: &str, suggestion: String) {
self.handler.custom_emit(&self.cm, Suggestion(sp, suggestion), msg, Help);
}
pub fn fileline_note(&self, sp: Span, msg: &str) {
self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
}
pub fn fileline_help(&self, sp: Span, msg: &str) {
self.handler.custom_emit(&self.cm, FileLine(sp), msg, Help);
}
pub fn span_bug(&self, sp: Span, msg: &str) ->! {
self.handler.emit(Some((&self.cm, sp)), msg, Bug);
panic!(ExplicitBug);
}
pub fn span_unimpl(&self, sp: Span, msg: &str) ->! {
self.span_bug(sp, &format!("unimplemented {}", msg));
}
pub fn handler<'a>(&'a self) -> &'a Handler {
&self.handler
}
}
/// A handler deals with errors; certain errors
/// (fatal, bug, unimpl) may cause immediate exit,
/// others log errors for later reporting.
pub struct Handler {
err_count: Cell<usize>,
emit: RefCell<Box<Emitter + Send>>,
pub can_emit_warnings: bool
}
impl Handler {
pub fn new(color_config: ColorConfig,
registry: Option<diagnostics::registry::Registry>,
can_emit_warnings: bool) -> Handler {
let emitter = Box::new(EmitterWriter::stderr(color_config, registry));
Handler::with_emitter(can_emit_warnings, emitter)
}
pub fn with_emitter(can_emit_warnings: bool, e: Box<Emitter + Send>) -> Handler {
Handler {
err_count: Cell::new(0),
emit: RefCell::new(e),
can_emit_warnings: can_emit_warnings
}
}
pub fn fatal(&self, msg: &str) ->! {
self.emit.borrow_mut().emit(None, msg, None, Fatal);
panic!(FatalError);
}
pub fn err(&self, msg: &str) {
self.emit.borrow_mut().emit(None, msg, None, Error);
self.bump_err_count();
}
pub fn bump_err_count(&self) {
self.err_count.set(self.err_count.get() + 1);
}
pub fn err_count(&self) -> usize {
self.err_count.get()
}
pub fn has_errors(&self) -> bool {
self.err_count.get() > 0
}
pub fn abort_if_errors(&self) {
let s;
match self.err_count.get() {
0 => return,
1 => s = "aborting due to previous error".to_string(),
_ => {
s = format!("aborting due to {} previous errors",
self.err_count.get());
}
}
self.fatal(&s[..]);
}
pub fn warn(&self, msg: &str) {
self.emit.borrow_mut().emit(None, msg, None, Warning);
}
pub fn note(&self, msg: &str) {
self.emit.borrow_mut().emit(None, msg, None, Note);
}
pub fn help(&self, msg: &str) {
self.emit.borrow_mut().emit(None, msg, None, Help);
}
pub fn bug(&self, msg: &str) ->! {
self.emit.borrow_mut().emit(None, msg, None, Bug);
panic!(ExplicitBug);
}
pub fn unimpl(&self, msg: &str) ->! {
self.bug(&format!("unimplemented {}", msg));
}
pub fn emit(&self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
lvl: Level) {
if lvl == Warning &&!self.can_emit_warnings { return }
self.emit.borrow_mut().emit(cmsp, msg, None, lvl);
}
pub fn emit_with_code(&self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str,
code: &str,
lvl: Level) {
if lvl == Warning &&!self.can_emit_warnings { return }
self.emit.borrow_mut().emit(cmsp, msg, Some(code), lvl);
}
pub fn custom_emit(&self, cm: &codemap::CodeMap,
sp: RenderSpan, msg: &str, lvl: Level) {
if lvl == Warning &&!self.can_emit_warnings { return }
self.emit.borrow_mut().custom_emit(cm, sp, msg, lvl);
}
}
#[derive(Copy, PartialEq, Clone, Debug)]
pub enum Level {
Bug,
Fatal,
Error,
Warning,
Note,
Help,
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use std::fmt::Display;
match *self {
Bug => "error: internal compiler error".fmt(f),
Fatal | Error => "error".fmt(f),
Warning => "warning".fmt(f),
Note => "note".fmt(f),
Help => "help".fmt(f),
}
}
}
impl Level {
fn color(self) -> term::color::Color {
match self {
Bug | Fatal | Error => term::color::BRIGHT_RED,
Warning => term::color::BRIGHT_YELLOW,
Note => term::color::BRIGHT_GREEN,
Help => term::color::BRIGHT_CYAN,
}
}
}
fn print_maybe_styled(w: &mut EmitterWriter,
msg: &str,
color: term::attr::Attr) -> io::Result<()> {
match w.dst {
Terminal(ref mut t) => {
try!(t.attr(color));
// If `msg` ends in a newline, we need to reset the color before
// the newline. We're making the assumption that we end up writing
// to a `LineBufferedWriter`, which means that emitting the reset
// after the newline ends up buffering the reset until we print
// another line or exit. Buffering the reset is a problem if we're
// sharing the terminal with any other programs (e.g. other rustc
// instances via `make -jN`).
//
// Note that if `msg` contains any internal newlines, this will
// result in the `LineBufferedWriter` flushing twice instead of
// once, which still leaves the opportunity for interleaved output
// to be miscolored. We assume this is rare enough that we don't
// have to worry about it.
if msg.ends_with("\n") {
try!(t.write_all(msg[..msg.len()-1].as_bytes()));
try!(t.reset());
try!(t.write_all(b"\n"));
} else {
try!(t.write_all(msg.as_bytes()));
try!(t.reset());
}
Ok(())
}
Raw(ref mut w) => w.write_all(msg.as_bytes()),
}
}
fn print_diagnostic(dst: &mut EmitterWriter, topic: &str, lvl: Level,
msg: &str, code: Option<&str>) -> io::Result<()> {
if!topic.is_empty() {
try!(write!(&mut dst.dst, "{} ", topic));
}
try!(print_maybe_styled(dst,
&format!("{}: ", lvl.to_string()),
term::attr::ForegroundColor(lvl.color())));
try!(print_maybe_styled(dst,
&format!("{}", msg),
term::attr::Bold));
match code {
Some(code) => {
let style = term::attr::ForegroundColor(term::color::BRIGHT_MAGENTA);
try!(print_maybe_styled(dst, &format!(" [{}]", code.clone()), style));
}
None => ()
}
try!(write!(&mut dst.dst, "\n"));
Ok(())
}
pub struct EmitterWriter {
dst: Destination,
registry: Option<diagnostics::registry::Registry>
}
enum Destination {
Terminal(Box<term::Terminal<WriterWrapper> + Send>),
Raw(Box<Write + Send>),
}
impl EmitterWriter {
pub fn stderr(color_config: ColorConfig,
registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
let stderr = io::stderr();
let use_color = match color_config {
Always => true,
Never => false,
Auto => stderr_isatty(),
};
if use_color {
let dst = match term::stderr() {
Some(t) => Terminal(t),
None => Raw(Box::new(stderr)),
};
EmitterWriter { dst: dst, registry: registry }
} else {
EmitterWriter { dst: Raw(Box::new(stderr)), registry: registry }
}
}
pub fn new(dst: Box<Write + Send>,
registry: Option<diagnostics::registry::Registry>) -> EmitterWriter {
EmitterWriter { dst: Raw(dst), registry: registry }
}
}
#[cfg(unix)]
fn stderr_isatty() -> bool {
unsafe { libc::isatty(libc::STDERR_FILENO)!= 0 }
}
#[cfg(windows)]
fn stderr_isatty() -> bool {
const STD_ERROR_HANDLE: libc::DWORD = -12i32 as libc::DWORD;
extern "system" {
fn GetStdHandle(which: libc::DWORD) -> libc::HANDLE;
fn GetConsoleMode(hConsoleHandle: libc::HANDLE,
lpMode: libc::LPDWORD) -> libc::BOOL;
}
unsafe {
let handle = GetStdHandle(STD_ERROR_HANDLE);
let mut out = 0;
GetConsoleMode(handle, &mut out)!= 0
}
}
impl Write for Destination {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
match *self {
Terminal(ref mut t) => t.write(bytes),
Raw(ref mut w) => w.write(bytes),
}
}
fn flush(&mut self) -> io::Result<()> {
match *self {
Terminal(ref mut t) => t.flush(),
Raw(ref mut w) => w.flush(),
}
}
}
impl Emitter for EmitterWriter {
fn emit(&mut self,
cmsp: Option<(&codemap::CodeMap, Span)>,
msg: &str, code: Option<&str>, lvl: Level) {
let error = match cmsp {
Some((cm, COMMAND_LINE_SP)) => emit(self, cm,
FileLine(COMMAND_LINE_SP),
msg, code, lvl),
Some((cm, sp)) => emit(self, cm, FullSpan(sp), msg, code, lvl),
None => print_diagnostic(self, "", lvl, msg, code),
};
match error {
Ok(()) => {}
Err(e) => panic!("failed to print diagnostics: {:?}", e),
}
}
fn custom_emit(&mut self, cm: &codemap::CodeMap,
sp: RenderSpan, msg: &str, lvl: Level) {
match emit(self, cm, sp, msg, None, lvl) {
Ok(()) => {}
Err(e) => panic!("failed to print diagnostics: {:?}", e),
}
}
}
fn emit(dst: &mut EmitterWriter, cm: &codemap::CodeMap, rsp: RenderSpan,
msg: &str, code: Option<&str>, lvl: Level) -> io::Result<()> {
let sp = rsp.span();
// We cannot check equality directly with COMMAND_LINE_SP
// since PartialEq is manually implemented to ignore the ExpnId
let ss = if sp.expn_id == COMMAND_LINE_EXPN {
"<command line option>".to_string()
} else if let EndSpan(_) = rsp {
let span_end = Span { lo: sp.hi, hi: sp.hi, expn_id: sp.expn_id};
cm.span_to_string(span_end)
} else {
cm.span_to_string(sp)
};
try!(print_diagnostic(dst, &ss[..], lvl, msg, code));
match rsp {
FullSpan(_) => {
try!(highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp)));
try!(print_macro_backtrace(dst, cm, sp));
}
EndSpan(_) => {
try!(end_highlight_lines(dst, cm, sp, lvl, cm.span_to_lines(sp)));
try!(print_macro_backtrace(dst, cm, sp));
}
Suggestion(_, ref suggestion) => {
try!(highlight_suggestion(dst, cm, sp, suggestion));
try!(print_macro_backtrace(dst, cm, sp));
}
FileLine(..) => {
// no source text in this case!
}
}
match code {
Some(code) =>
match dst.registry.as_ref().and_then(|registry| registry.find_description(code)) {
Some(_) => {
try!(print_diagnostic(dst, &ss[..], Help,
&format!("run `rustc --explain {}` to see a detailed \
explanation", code), None));
}
None => ()
},
None => (),
}
Ok(())
}
fn highlight_suggestion(err: &mut EmitterWriter,
cm: &codemap::CodeMap,
sp: Span,
suggestion: &str)
-> io::Result<()>
{
let lines = cm.span_to_lines(sp).unwrap();
assert!(!lines.lines.is_empty());
// To build up the result, we want to take the snippet from the first
// line that precedes the span, prepend that with the suggestion, and
// then append the snippet from the last line that trails the span.
let fm = &lines.file;
let first_line = &lines.lines[0];
let prefix = fm.get_line(first_line.line_index)
.map(|l| &l[..first_line.start_col.0])
.unwrap_or("");
let last_line = lines.lines.last().unwrap();
let suffix = fm.get_line(last_line.line_index)
.map(|l| &l[last_line.end_col.0..])
.unwrap_or("");
let complete = format!("{}{}{}", prefix, suggestion, suffix);
// print the suggestion without any line numbers, but leave
// space for them. This helps with lining up with previous
// snippets from the actual error being reported.
let fm = &*lines.file;
let mut lines = complete.lines();
for (line, line_index) in lines.by_ref().take(MAX_LINES).zip(first_line.line_index..) {
let elided_line_num = format!("{}", line_index+1);
try!(write!(&mut err.dst, "{0}:{1:2$} {3}\n",
fm.name, "", elided_line_num.len(), line));
}
// if we elided some lines, add an ellipsis
if lines.next().is_some() |
Ok(())
}
fn highlight_lines(err: &mut EmitterWriter,
cm: &codemap::CodeMap,
sp: Span,
lvl: Level,
lines: codemap::FileLinesResult)
-> io::Result<()>
{
let lines = match lines {
Ok(lines) => lines,
Err(_) => {
try!(write!(&mut err.dst, "(internal compiler error: unprintable span)\n"));
return Ok(());
}
};
let fm = &*lines.file;
let line_strings: Option<Vec<&str>> =
lines.lines.iter()
.map(|info| fm.get_line(info.line_index))
.collect();
let line_strings = match line_strings {
None => { return Ok(()); }
Some(line_strings) => line_strings
};
// Display only the first MAX_LINES lines.
let all_lines = lines.lines.len();
let display_lines = cmp::min(all_lines, MAX_LINES);
let display_line_infos = &lines.lines[..display_lines];
let display_line_strings = &line_strings[..display_lines];
// Calculate the widest number to format evenly and fix #11715
assert!(display_line_infos.len() > 0);
let mut max_line_num = display_line_infos[display_line_infos.len() - 1].line_index + 1;
let mut digits = 0;
while max_line_num > 0 {
max_line_num /= 10;
digits += 1;
}
// Print the offending lines
for (line_info, line) in display_line_infos.iter().zip(display_line_strings) {
try!(write!(&mut err.dst, "{}:{:>width$} {}\n",
fm.name,
line_info.line_index + 1,
line,
width=digits));
}
// If we elided something, put an ellipsis.
if display_lines < all_lines {
let last_line_index = display_line_infos.last().unwrap().line_index;
let s = format!("{}:{} ", fm.name, last_line_index + 1);
try!(write!(&mut err.dst, "{0:1$}...\n", "", s.len()));
}
// FIXME (#3260)
// If there's one line at fault we can easily point to the problem
if lines.lines.len() == 1 {
let lo = cm.lookup_char_pos(sp.lo);
let mut digits = 0;
let mut num = (lines.lines[0].line_index + 1) / 10;
// how many digits must be indent past?
while num > 0 { num /= 10; digits += 1; }
let mut s = String::new();
// Skip is the number of characters we need to skip because they are
// part of the 'filename:line'part of the previous line.
let skip = fm.name.chars().count() + digits + 3;
for _ in 0..skip {
s.push(' ');
}
if let Some(orig) = fm.get_line(lines.lines[0].line_index) {
let mut col = skip;
let mut lastc ='';
let mut iter = orig.chars().enumerate();
for (pos, ch) in iter.by_ref() {
lastc = ch;
if pos >= lo.col.to_usize() { break; }
// Whenever a tab occurs on the previous line, we insert one on
// the error-point-squiggly-line as well (instead of a space).
// That way the squiggly line will usually appear in the correct
// position.
match ch {
'\t' => {
col += 8 - col%8;
s.push('\t');
},
_ => {
| {
let elided_line_num = format!("{}", first_line.line_index + MAX_LINES + 1);
try!(write!(&mut err.dst, "{0:1$} {0:2$} ...\n",
"", fm.name.len(), elided_line_num.len()));
} | conditional_block |
stemmer.rs | use std::sync::Arc;
use stemmer;
pub struct StemmerTokenStream<TailTokenStream>
where TailTokenStream: TokenStream {
tail: TailTokenStream,
stemmer: Arc<stemmer::Stemmer>,
}
impl<TailTokenStream> TokenStream for StemmerTokenStream<TailTokenStream>
where TailTokenStream: TokenStream {
fn token(&self) -> &Token {
self.tail.token()
}
fn token_mut(&mut self) -> &mut Token {
self.tail.token_mut()
}
fn advance(&mut self) -> bool {
if self.tail.advance() |
else {
false
}
}
}
impl<TailTokenStream> StemmerTokenStream<TailTokenStream>
where TailTokenStream: TokenStream {
fn wrap(stemmer: Arc<stemmer::Stemmer>, tail: TailTokenStream) -> StemmerTokenStream<TailTokenStream> {
StemmerTokenStream {
tail,
stemmer,
}
}
} | {
// self.tail.token_mut().term.make_ascii_lowercase();
let new_str = self.stemmer.stem_str(&self.token().term);
true
} | conditional_block |
stemmer.rs | use std::sync::Arc;
use stemmer;
pub struct StemmerTokenStream<TailTokenStream>
where TailTokenStream: TokenStream {
tail: TailTokenStream,
stemmer: Arc<stemmer::Stemmer>,
}
impl<TailTokenStream> TokenStream for StemmerTokenStream<TailTokenStream>
where TailTokenStream: TokenStream {
fn token(&self) -> &Token {
self.tail.token()
}
fn token_mut(&mut self) -> &mut Token {
self.tail.token_mut()
}
fn advance(&mut self) -> bool {
if self.tail.advance() {
// self.tail.token_mut().term.make_ascii_lowercase();
let new_str = self.stemmer.stem_str(&self.token().term);
true
}
else {
false
}
}
}
impl<TailTokenStream> StemmerTokenStream<TailTokenStream>
where TailTokenStream: TokenStream {
fn wrap(stemmer: Arc<stemmer::Stemmer>, tail: TailTokenStream) -> StemmerTokenStream<TailTokenStream> {
StemmerTokenStream {
tail,
stemmer,
}
} | } | random_line_split |
|
stemmer.rs | use std::sync::Arc;
use stemmer;
pub struct StemmerTokenStream<TailTokenStream>
where TailTokenStream: TokenStream {
tail: TailTokenStream,
stemmer: Arc<stemmer::Stemmer>,
}
impl<TailTokenStream> TokenStream for StemmerTokenStream<TailTokenStream>
where TailTokenStream: TokenStream {
fn token(&self) -> &Token |
fn token_mut(&mut self) -> &mut Token {
self.tail.token_mut()
}
fn advance(&mut self) -> bool {
if self.tail.advance() {
// self.tail.token_mut().term.make_ascii_lowercase();
let new_str = self.stemmer.stem_str(&self.token().term);
true
}
else {
false
}
}
}
impl<TailTokenStream> StemmerTokenStream<TailTokenStream>
where TailTokenStream: TokenStream {
fn wrap(stemmer: Arc<stemmer::Stemmer>, tail: TailTokenStream) -> StemmerTokenStream<TailTokenStream> {
StemmerTokenStream {
tail,
stemmer,
}
}
} | {
self.tail.token()
} | identifier_body |
stemmer.rs | use std::sync::Arc;
use stemmer;
pub struct | <TailTokenStream>
where TailTokenStream: TokenStream {
tail: TailTokenStream,
stemmer: Arc<stemmer::Stemmer>,
}
impl<TailTokenStream> TokenStream for StemmerTokenStream<TailTokenStream>
where TailTokenStream: TokenStream {
fn token(&self) -> &Token {
self.tail.token()
}
fn token_mut(&mut self) -> &mut Token {
self.tail.token_mut()
}
fn advance(&mut self) -> bool {
if self.tail.advance() {
// self.tail.token_mut().term.make_ascii_lowercase();
let new_str = self.stemmer.stem_str(&self.token().term);
true
}
else {
false
}
}
}
impl<TailTokenStream> StemmerTokenStream<TailTokenStream>
where TailTokenStream: TokenStream {
fn wrap(stemmer: Arc<stemmer::Stemmer>, tail: TailTokenStream) -> StemmerTokenStream<TailTokenStream> {
StemmerTokenStream {
tail,
stemmer,
}
}
} | StemmerTokenStream | identifier_name |
context.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use language_tags::LanguageTag;
use std::fmt;
use {Args, Message};
/// Contextual configuration data.
#[derive(Clone, Debug)]
pub struct Context {
/// The language being localized for.
pub language_tag: LanguageTag,
/// The value to use in a `PlaceholderFormat`.
pub placeholder_value: Option<i64>,
}
impl Context {
/// Create a new instance of `Context`.
pub fn new(language: LanguageTag, placeholder_value: Option<i64>) -> Self {
Context {
language_tag: language,
placeholder_value: placeholder_value,
}
}
/// Format a message, returning a string.
pub fn | <'f>(&self, message: &Message, args: Option<&Args<'f>>) -> String {
let mut output = String::new();
let _ = message.write_message(self, &mut output, args);
output
}
/// Write a message to a stream.
pub fn write<'f>(
&self,
message: &Message,
stream: &mut fmt::Write,
args: Option<&Args<'f>>,
) -> fmt::Result {
message.write_message(self, stream, args)
}
}
impl Default for Context {
fn default() -> Self {
Context {
language_tag: Default::default(),
placeholder_value: None,
}
}
}
| format | identifier_name |
context.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use language_tags::LanguageTag;
use std::fmt;
use {Args, Message};
/// Contextual configuration data.
#[derive(Clone, Debug)]
pub struct Context {
/// The language being localized for.
pub language_tag: LanguageTag,
/// The value to use in a `PlaceholderFormat`.
pub placeholder_value: Option<i64>,
}
impl Context {
/// Create a new instance of `Context`.
pub fn new(language: LanguageTag, placeholder_value: Option<i64>) -> Self {
Context {
language_tag: language,
placeholder_value: placeholder_value,
}
}
/// Format a message, returning a string.
pub fn format<'f>(&self, message: &Message, args: Option<&Args<'f>>) -> String {
let mut output = String::new();
let _ = message.write_message(self, &mut output, args);
output
}
/// Write a message to a stream.
pub fn write<'f>(
&self,
message: &Message,
stream: &mut fmt::Write,
args: Option<&Args<'f>>,
) -> fmt::Result |
}
impl Default for Context {
fn default() -> Self {
Context {
language_tag: Default::default(),
placeholder_value: None,
}
}
}
| {
message.write_message(self, stream, args)
} | identifier_body |
context.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use language_tags::LanguageTag;
use std::fmt;
use {Args, Message};
/// Contextual configuration data.
#[derive(Clone, Debug)]
pub struct Context {
/// The language being localized for.
pub language_tag: LanguageTag,
/// The value to use in a `PlaceholderFormat`.
pub placeholder_value: Option<i64>,
}
impl Context {
/// Create a new instance of `Context`.
pub fn new(language: LanguageTag, placeholder_value: Option<i64>) -> Self {
Context {
language_tag: language,
placeholder_value: placeholder_value,
}
}
/// Format a message, returning a string.
pub fn format<'f>(&self, message: &Message, args: Option<&Args<'f>>) -> String {
let mut output = String::new();
let _ = message.write_message(self, &mut output, args);
output |
/// Write a message to a stream.
pub fn write<'f>(
&self,
message: &Message,
stream: &mut fmt::Write,
args: Option<&Args<'f>>,
) -> fmt::Result {
message.write_message(self, stream, args)
}
}
impl Default for Context {
fn default() -> Self {
Context {
language_tag: Default::default(),
placeholder_value: None,
}
}
} | } | random_line_split |
hint.rs | use std::collections::HashMap;
pub type FieldIndex = usize;
/// Hints given when reading parcels.
#[derive(Clone, Debug, PartialEq)]
pub struct Hints {
pub current_field_index: Option<FieldIndex>,
/// The fields for which a length prefix
/// was already present earlier in the layout.
pub known_field_lengths: HashMap<FieldIndex, FieldLength>,
}
/// Information about the length of a field.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct FieldLength {
pub length: usize,
pub kind: LengthPrefixKind,
}
/// Specifies what kind of data the length prefix captures.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum LengthPrefixKind {
/// The length prefix stores the total number of bytes making up another field.
Bytes,
/// The length prefix stores the total number of elements inside another field.
Elements,
}
impl Default for Hints {
fn default() -> Self {
Hints {
current_field_index: None,
known_field_lengths: HashMap::new(),
}
}
}
impl Hints {
/// Gets the length of the field currently being
/// read, if known.
pub fn current_field_length(&self) -> Option<FieldLength> {
self.current_field_index.and_then(|index| self.known_field_lengths.get(&index)).cloned()
}
}
/// Helpers for the `protocol-derive` crate.
mod protocol_derive_helpers {
use super::*;
impl Hints {
// Sets hints indicating a new set of fields are beginning.
#[doc(hidden)]
pub fn begin_fields(&mut self) |
// Updates the hints to indicate a field was just read.
#[doc(hidden)]
pub fn next_field(&mut self) {
*self.current_field_index.as_mut()
.expect("cannot increment next field when not in a struct")+= 1;
}
// Sets the length of a variable-sized field by its 0-based index.
#[doc(hidden)]
pub fn set_field_length(&mut self,
field_index: FieldIndex,
length: usize,
kind: LengthPrefixKind) {
self.known_field_lengths.insert(field_index, FieldLength { kind, length });
}
}
}
| {
self.current_field_index = Some(0);
} | identifier_body |
hint.rs | use std::collections::HashMap;
pub type FieldIndex = usize;
/// Hints given when reading parcels.
#[derive(Clone, Debug, PartialEq)]
pub struct Hints {
pub current_field_index: Option<FieldIndex>,
/// The fields for which a length prefix
/// was already present earlier in the layout.
pub known_field_lengths: HashMap<FieldIndex, FieldLength>,
}
/// Information about the length of a field.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct FieldLength {
pub length: usize,
pub kind: LengthPrefixKind,
}
/// Specifies what kind of data the length prefix captures.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum LengthPrefixKind {
/// The length prefix stores the total number of bytes making up another field. |
impl Default for Hints {
fn default() -> Self {
Hints {
current_field_index: None,
known_field_lengths: HashMap::new(),
}
}
}
impl Hints {
/// Gets the length of the field currently being
/// read, if known.
pub fn current_field_length(&self) -> Option<FieldLength> {
self.current_field_index.and_then(|index| self.known_field_lengths.get(&index)).cloned()
}
}
/// Helpers for the `protocol-derive` crate.
mod protocol_derive_helpers {
use super::*;
impl Hints {
// Sets hints indicating a new set of fields are beginning.
#[doc(hidden)]
pub fn begin_fields(&mut self) {
self.current_field_index = Some(0);
}
// Updates the hints to indicate a field was just read.
#[doc(hidden)]
pub fn next_field(&mut self) {
*self.current_field_index.as_mut()
.expect("cannot increment next field when not in a struct")+= 1;
}
// Sets the length of a variable-sized field by its 0-based index.
#[doc(hidden)]
pub fn set_field_length(&mut self,
field_index: FieldIndex,
length: usize,
kind: LengthPrefixKind) {
self.known_field_lengths.insert(field_index, FieldLength { kind, length });
}
}
} | Bytes,
/// The length prefix stores the total number of elements inside another field.
Elements,
}
| random_line_split |
hint.rs | use std::collections::HashMap;
pub type FieldIndex = usize;
/// Hints given when reading parcels.
#[derive(Clone, Debug, PartialEq)]
pub struct Hints {
pub current_field_index: Option<FieldIndex>,
/// The fields for which a length prefix
/// was already present earlier in the layout.
pub known_field_lengths: HashMap<FieldIndex, FieldLength>,
}
/// Information about the length of a field.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct FieldLength {
pub length: usize,
pub kind: LengthPrefixKind,
}
/// Specifies what kind of data the length prefix captures.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum | {
/// The length prefix stores the total number of bytes making up another field.
Bytes,
/// The length prefix stores the total number of elements inside another field.
Elements,
}
impl Default for Hints {
fn default() -> Self {
Hints {
current_field_index: None,
known_field_lengths: HashMap::new(),
}
}
}
impl Hints {
/// Gets the length of the field currently being
/// read, if known.
pub fn current_field_length(&self) -> Option<FieldLength> {
self.current_field_index.and_then(|index| self.known_field_lengths.get(&index)).cloned()
}
}
/// Helpers for the `protocol-derive` crate.
mod protocol_derive_helpers {
use super::*;
impl Hints {
// Sets hints indicating a new set of fields are beginning.
#[doc(hidden)]
pub fn begin_fields(&mut self) {
self.current_field_index = Some(0);
}
// Updates the hints to indicate a field was just read.
#[doc(hidden)]
pub fn next_field(&mut self) {
*self.current_field_index.as_mut()
.expect("cannot increment next field when not in a struct")+= 1;
}
// Sets the length of a variable-sized field by its 0-based index.
#[doc(hidden)]
pub fn set_field_length(&mut self,
field_index: FieldIndex,
length: usize,
kind: LengthPrefixKind) {
self.known_field_lengths.insert(field_index, FieldLength { kind, length });
}
}
}
| LengthPrefixKind | identifier_name |
refcounted.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task for asynchronous events). Akin to Gecko's
//! nsMainThreadPtrHandle, this uses thread-safe reference counting and ensures
//! that the actual SpiderMonkey GC integration occurs on the script task via
//! message passing. Ownership of a `Trusted<T>` object means the DOM object of
//! type T to which it points remains alive. Any other behaviour is undefined.
//! To guarantee the lifetime of a DOM object when performing asynchronous operations,
//! obtain a `Trusted<T>` from that object and pass it along with each operation.
//! A usable pointer to the original DOM object can be obtained on the script task
//! from a `Trusted<T>` via the `to_temporary` method.
//!
//! The implementation of Trusted<T> is as follows:
//! A hashtable resides in the script task, keyed on the pointer to the Rust DOM object.
//! The values in this hashtable are atomic reference counts. When a Trusted<T> object is
//! created or cloned, this count is increased. When a Trusted<T> is dropped, the count
//! decreases. If the count hits zero, a message is dispatched to the script task to remove
//! the entry from the hashmap if the count is still zero. The JS reflector for the DOM object
//! is rooted when a hashmap entry is first created, and unrooted when the hashmap entry
//! is removed.
use dom::bindings::js::Root;
use dom::bindings::utils::{Reflector, Reflectable};
use dom::bindings::trace::trace_reflector;
use script_task::{ScriptMsg, ScriptChan};
use js::jsapi::{JSContext, JSTracer};
use libc;
use std::cell::RefCell;
use std::collections::hash_map::HashMap;
use std::collections::hash_map::Entry::{Vacant, Occupied};
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
use core::nonzero::NonZero;
#[allow(missing_docs)] // FIXME
mod dummy { // Attributes don’t apply through the macro.
use std::rc::Rc;
use std::cell::RefCell;
use super::LiveDOMReferences;
thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> =
Rc::new(RefCell::new(None)));
}
pub use self::dummy::LIVE_REFERENCES;
/// A pointer to a Rust DOM object that needs to be destroyed.
pub struct TrustedReference(*const libc::c_void);
unsafe impl Send for TrustedReference {}
/// A safe wrapper around a raw pointer to a DOM object that can be
/// shared among tasks for use in asynchronous operations. The underlying
/// DOM object is guaranteed to live at least as long as the last outstanding
/// `Trusted<T>` instance.
#[allow_unrooted_interior]
pub struct Trusted<T: Reflectable> {
/// A pointer to the Rust DOM object of type T, but void to allow
/// sending `Trusted<T>` between tasks, regardless of T's sendability.
ptr: *const libc::c_void,
refcount: Arc<Mutex<usize>>,
script_chan: Box<ScriptChan + Send>,
owner_thread: *const libc::c_void,
phantom: PhantomData<T>,
}
unsafe impl<T: Reflectable> Send for Trusted<T> {}
impl<T: Reflectable> Trusted<T> {
/// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will
/// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's
/// lifetime.
pub fn new(_cx: *mut JSContext, ptr: &T, script_chan: Box<ScriptChan + Send>) -> Trusted<T> {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let refcount = live_references.addref(&*ptr as *const T);
Trusted {
ptr: &*ptr as *const T as *const libc::c_void,
refcount: refcount,
script_chan: script_chan.clone(),
owner_thread: (&*live_references) as *const _ as *const libc::c_void,
phantom: PhantomData,
}
})
}
/// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on
/// a different thread than the original value from which this `Trusted<T>` was
/// obtained.
pub fn root(&self) -> Root<T> {
assert!(LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
self.owner_thread == (&*live_references) as *const _ as *const libc::c_void
}));
unsafe {
Root::new(NonZero::new(self.ptr as *const T))
}
}
}
impl<T: Reflectable> Clone for Trusted<T> {
fn clone(&self) -> Trusted<T> {
{
let mut refcount = self.refcount.lock().unwrap();
*refcount += 1;
}
Trusted {
ptr: self.ptr,
refcount: self.refcount.clone(),
script_chan: self.script_chan.clone(),
owner_thread: self.owner_thread,
phantom: PhantomData,
}
}
}
impl<T: Reflectable> Drop for Trusted<T> {
fn drop(&mut self) {
let mut refcount = self.refcount.lock().unwrap();
assert!(*refcount > 0);
*refcount -= 1;
if *refcount == 0 {
// It's possible this send will fail if the script task
// has already exited. There's not much we can do at this
// point though.
let msg = ScriptMsg::RefcountCleanup(TrustedReference(self.ptr));
let _ = self.script_chan.send(msg);
}
}
}
/// The set of live, pinned DOM objects that are currently prevented
/// from being garbage collected due to outstanding references.
pub struct LiveDOMReferences {
// keyed on pointer to Rust DOM object
table: RefCell<HashMap<*const libc::c_void, Arc<Mutex<usize>>>>
}
impl LiveDOMReferences {
/// Set up the task-local data required for storing the outstanding DOM references.
pub fn initialize() {
LIVE_REFERENCES.with(|ref r| {
*r.borrow_mut() = Some(LiveDOMReferences {
table: RefCell::new(HashMap::new()),
})
});
}
fn addref<T: Reflectable>(&self, ptr: *const T) -> Arc<Mutex<usize>> {
let mut table = self.table.borrow_mut();
match table.entry(ptr as *const libc::c_void) {
Occupied(mut entry) => {
let refcount = entry.get_mut();
*refcount.lock().unwrap() += 1;
refcount.clone()
}
Vacant(entry) => {
let refcount = Arc::new(Mutex::new(1));
entry.insert(refcount.clone());
refcount
}
}
}
/// Unpin the given DOM object if its refcount is 0.
pub fn cleanup(raw_reflectable: TrustedReference) {
| info!("attempt to cleanup an unrecognized reflector");
}
}
})
}
}
/// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES
pub unsafe extern fn trace_refcounted_objects(tracer: *mut JSTracer, _data: *mut libc::c_void) {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let table = live_references.table.borrow();
for obj in table.keys() {
let reflectable = &*(*obj as *const Reflector);
trace_reflector(tracer, "LIVE_REFERENCES", reflectable);
}
});
}
| let TrustedReference(raw_reflectable) = raw_reflectable;
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let mut table = live_references.table.borrow_mut();
match table.entry(raw_reflectable) {
Occupied(entry) => {
if *entry.get().lock().unwrap() != 0 {
// there could have been a new reference taken since
// this message was dispatched.
return;
}
let _ = entry.remove();
}
Vacant(_) => {
// there could be a cleanup message dispatched, then a new
// pinned reference obtained and released before the message
// is processed, at which point there would be no matching
// hashtable entry. | identifier_body |
refcounted.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task for asynchronous events). Akin to Gecko's
//! nsMainThreadPtrHandle, this uses thread-safe reference counting and ensures
//! that the actual SpiderMonkey GC integration occurs on the script task via
//! message passing. Ownership of a `Trusted<T>` object means the DOM object of
//! type T to which it points remains alive. Any other behaviour is undefined.
//! To guarantee the lifetime of a DOM object when performing asynchronous operations,
//! obtain a `Trusted<T>` from that object and pass it along with each operation.
//! A usable pointer to the original DOM object can be obtained on the script task
//! from a `Trusted<T>` via the `to_temporary` method.
//!
//! The implementation of Trusted<T> is as follows:
//! A hashtable resides in the script task, keyed on the pointer to the Rust DOM object.
//! The values in this hashtable are atomic reference counts. When a Trusted<T> object is
//! created or cloned, this count is increased. When a Trusted<T> is dropped, the count
//! decreases. If the count hits zero, a message is dispatched to the script task to remove
//! the entry from the hashmap if the count is still zero. The JS reflector for the DOM object
//! is rooted when a hashmap entry is first created, and unrooted when the hashmap entry
//! is removed.
use dom::bindings::js::Root;
use dom::bindings::utils::{Reflector, Reflectable};
use dom::bindings::trace::trace_reflector;
use script_task::{ScriptMsg, ScriptChan};
use js::jsapi::{JSContext, JSTracer};
use libc;
use std::cell::RefCell;
use std::collections::hash_map::HashMap;
use std::collections::hash_map::Entry::{Vacant, Occupied};
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
use core::nonzero::NonZero;
#[allow(missing_docs)] // FIXME
mod dummy { // Attributes don’t apply through the macro. | }
pub use self::dummy::LIVE_REFERENCES;
/// A pointer to a Rust DOM object that needs to be destroyed.
pub struct TrustedReference(*const libc::c_void);
unsafe impl Send for TrustedReference {}
/// A safe wrapper around a raw pointer to a DOM object that can be
/// shared among tasks for use in asynchronous operations. The underlying
/// DOM object is guaranteed to live at least as long as the last outstanding
/// `Trusted<T>` instance.
#[allow_unrooted_interior]
pub struct Trusted<T: Reflectable> {
/// A pointer to the Rust DOM object of type T, but void to allow
/// sending `Trusted<T>` between tasks, regardless of T's sendability.
ptr: *const libc::c_void,
refcount: Arc<Mutex<usize>>,
script_chan: Box<ScriptChan + Send>,
owner_thread: *const libc::c_void,
phantom: PhantomData<T>,
}
unsafe impl<T: Reflectable> Send for Trusted<T> {}
impl<T: Reflectable> Trusted<T> {
/// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will
/// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's
/// lifetime.
pub fn new(_cx: *mut JSContext, ptr: &T, script_chan: Box<ScriptChan + Send>) -> Trusted<T> {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let refcount = live_references.addref(&*ptr as *const T);
Trusted {
ptr: &*ptr as *const T as *const libc::c_void,
refcount: refcount,
script_chan: script_chan.clone(),
owner_thread: (&*live_references) as *const _ as *const libc::c_void,
phantom: PhantomData,
}
})
}
/// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on
/// a different thread than the original value from which this `Trusted<T>` was
/// obtained.
pub fn root(&self) -> Root<T> {
assert!(LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
self.owner_thread == (&*live_references) as *const _ as *const libc::c_void
}));
unsafe {
Root::new(NonZero::new(self.ptr as *const T))
}
}
}
impl<T: Reflectable> Clone for Trusted<T> {
fn clone(&self) -> Trusted<T> {
{
let mut refcount = self.refcount.lock().unwrap();
*refcount += 1;
}
Trusted {
ptr: self.ptr,
refcount: self.refcount.clone(),
script_chan: self.script_chan.clone(),
owner_thread: self.owner_thread,
phantom: PhantomData,
}
}
}
impl<T: Reflectable> Drop for Trusted<T> {
fn drop(&mut self) {
let mut refcount = self.refcount.lock().unwrap();
assert!(*refcount > 0);
*refcount -= 1;
if *refcount == 0 {
// It's possible this send will fail if the script task
// has already exited. There's not much we can do at this
// point though.
let msg = ScriptMsg::RefcountCleanup(TrustedReference(self.ptr));
let _ = self.script_chan.send(msg);
}
}
}
/// The set of live, pinned DOM objects that are currently prevented
/// from being garbage collected due to outstanding references.
pub struct LiveDOMReferences {
// keyed on pointer to Rust DOM object
table: RefCell<HashMap<*const libc::c_void, Arc<Mutex<usize>>>>
}
impl LiveDOMReferences {
/// Set up the task-local data required for storing the outstanding DOM references.
pub fn initialize() {
LIVE_REFERENCES.with(|ref r| {
*r.borrow_mut() = Some(LiveDOMReferences {
table: RefCell::new(HashMap::new()),
})
});
}
fn addref<T: Reflectable>(&self, ptr: *const T) -> Arc<Mutex<usize>> {
let mut table = self.table.borrow_mut();
match table.entry(ptr as *const libc::c_void) {
Occupied(mut entry) => {
let refcount = entry.get_mut();
*refcount.lock().unwrap() += 1;
refcount.clone()
}
Vacant(entry) => {
let refcount = Arc::new(Mutex::new(1));
entry.insert(refcount.clone());
refcount
}
}
}
/// Unpin the given DOM object if its refcount is 0.
pub fn cleanup(raw_reflectable: TrustedReference) {
let TrustedReference(raw_reflectable) = raw_reflectable;
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let mut table = live_references.table.borrow_mut();
match table.entry(raw_reflectable) {
Occupied(entry) => {
if *entry.get().lock().unwrap()!= 0 {
// there could have been a new reference taken since
// this message was dispatched.
return;
}
let _ = entry.remove();
}
Vacant(_) => {
// there could be a cleanup message dispatched, then a new
// pinned reference obtained and released before the message
// is processed, at which point there would be no matching
// hashtable entry.
info!("attempt to cleanup an unrecognized reflector");
}
}
})
}
}
/// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES
pub unsafe extern fn trace_refcounted_objects(tracer: *mut JSTracer, _data: *mut libc::c_void) {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let table = live_references.table.borrow();
for obj in table.keys() {
let reflectable = &*(*obj as *const Reflector);
trace_reflector(tracer, "LIVE_REFERENCES", reflectable);
}
});
} | use std::rc::Rc;
use std::cell::RefCell;
use super::LiveDOMReferences;
thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> =
Rc::new(RefCell::new(None))); | random_line_split |
refcounted.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task for asynchronous events). Akin to Gecko's
//! nsMainThreadPtrHandle, this uses thread-safe reference counting and ensures
//! that the actual SpiderMonkey GC integration occurs on the script task via
//! message passing. Ownership of a `Trusted<T>` object means the DOM object of
//! type T to which it points remains alive. Any other behaviour is undefined.
//! To guarantee the lifetime of a DOM object when performing asynchronous operations,
//! obtain a `Trusted<T>` from that object and pass it along with each operation.
//! A usable pointer to the original DOM object can be obtained on the script task
//! from a `Trusted<T>` via the `to_temporary` method.
//!
//! The implementation of Trusted<T> is as follows:
//! A hashtable resides in the script task, keyed on the pointer to the Rust DOM object.
//! The values in this hashtable are atomic reference counts. When a Trusted<T> object is
//! created or cloned, this count is increased. When a Trusted<T> is dropped, the count
//! decreases. If the count hits zero, a message is dispatched to the script task to remove
//! the entry from the hashmap if the count is still zero. The JS reflector for the DOM object
//! is rooted when a hashmap entry is first created, and unrooted when the hashmap entry
//! is removed.
use dom::bindings::js::Root;
use dom::bindings::utils::{Reflector, Reflectable};
use dom::bindings::trace::trace_reflector;
use script_task::{ScriptMsg, ScriptChan};
use js::jsapi::{JSContext, JSTracer};
use libc;
use std::cell::RefCell;
use std::collections::hash_map::HashMap;
use std::collections::hash_map::Entry::{Vacant, Occupied};
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
use core::nonzero::NonZero;
#[allow(missing_docs)] // FIXME
mod dummy { // Attributes don’t apply through the macro.
use std::rc::Rc;
use std::cell::RefCell;
use super::LiveDOMReferences;
thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> =
Rc::new(RefCell::new(None)));
}
pub use self::dummy::LIVE_REFERENCES;
/// A pointer to a Rust DOM object that needs to be destroyed.
pub struct Tr | const libc::c_void);
unsafe impl Send for TrustedReference {}
/// A safe wrapper around a raw pointer to a DOM object that can be
/// shared among tasks for use in asynchronous operations. The underlying
/// DOM object is guaranteed to live at least as long as the last outstanding
/// `Trusted<T>` instance.
#[allow_unrooted_interior]
pub struct Trusted<T: Reflectable> {
/// A pointer to the Rust DOM object of type T, but void to allow
/// sending `Trusted<T>` between tasks, regardless of T's sendability.
ptr: *const libc::c_void,
refcount: Arc<Mutex<usize>>,
script_chan: Box<ScriptChan + Send>,
owner_thread: *const libc::c_void,
phantom: PhantomData<T>,
}
unsafe impl<T: Reflectable> Send for Trusted<T> {}
impl<T: Reflectable> Trusted<T> {
/// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will
/// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's
/// lifetime.
pub fn new(_cx: *mut JSContext, ptr: &T, script_chan: Box<ScriptChan + Send>) -> Trusted<T> {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let refcount = live_references.addref(&*ptr as *const T);
Trusted {
ptr: &*ptr as *const T as *const libc::c_void,
refcount: refcount,
script_chan: script_chan.clone(),
owner_thread: (&*live_references) as *const _ as *const libc::c_void,
phantom: PhantomData,
}
})
}
/// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on
/// a different thread than the original value from which this `Trusted<T>` was
/// obtained.
pub fn root(&self) -> Root<T> {
assert!(LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
self.owner_thread == (&*live_references) as *const _ as *const libc::c_void
}));
unsafe {
Root::new(NonZero::new(self.ptr as *const T))
}
}
}
impl<T: Reflectable> Clone for Trusted<T> {
fn clone(&self) -> Trusted<T> {
{
let mut refcount = self.refcount.lock().unwrap();
*refcount += 1;
}
Trusted {
ptr: self.ptr,
refcount: self.refcount.clone(),
script_chan: self.script_chan.clone(),
owner_thread: self.owner_thread,
phantom: PhantomData,
}
}
}
impl<T: Reflectable> Drop for Trusted<T> {
fn drop(&mut self) {
let mut refcount = self.refcount.lock().unwrap();
assert!(*refcount > 0);
*refcount -= 1;
if *refcount == 0 {
// It's possible this send will fail if the script task
// has already exited. There's not much we can do at this
// point though.
let msg = ScriptMsg::RefcountCleanup(TrustedReference(self.ptr));
let _ = self.script_chan.send(msg);
}
}
}
/// The set of live, pinned DOM objects that are currently prevented
/// from being garbage collected due to outstanding references.
pub struct LiveDOMReferences {
// keyed on pointer to Rust DOM object
table: RefCell<HashMap<*const libc::c_void, Arc<Mutex<usize>>>>
}
impl LiveDOMReferences {
/// Set up the task-local data required for storing the outstanding DOM references.
pub fn initialize() {
LIVE_REFERENCES.with(|ref r| {
*r.borrow_mut() = Some(LiveDOMReferences {
table: RefCell::new(HashMap::new()),
})
});
}
fn addref<T: Reflectable>(&self, ptr: *const T) -> Arc<Mutex<usize>> {
let mut table = self.table.borrow_mut();
match table.entry(ptr as *const libc::c_void) {
Occupied(mut entry) => {
let refcount = entry.get_mut();
*refcount.lock().unwrap() += 1;
refcount.clone()
}
Vacant(entry) => {
let refcount = Arc::new(Mutex::new(1));
entry.insert(refcount.clone());
refcount
}
}
}
/// Unpin the given DOM object if its refcount is 0.
pub fn cleanup(raw_reflectable: TrustedReference) {
let TrustedReference(raw_reflectable) = raw_reflectable;
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let mut table = live_references.table.borrow_mut();
match table.entry(raw_reflectable) {
Occupied(entry) => {
if *entry.get().lock().unwrap()!= 0 {
// there could have been a new reference taken since
// this message was dispatched.
return;
}
let _ = entry.remove();
}
Vacant(_) => {
// there could be a cleanup message dispatched, then a new
// pinned reference obtained and released before the message
// is processed, at which point there would be no matching
// hashtable entry.
info!("attempt to cleanup an unrecognized reflector");
}
}
})
}
}
/// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES
pub unsafe extern fn trace_refcounted_objects(tracer: *mut JSTracer, _data: *mut libc::c_void) {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let table = live_references.table.borrow();
for obj in table.keys() {
let reflectable = &*(*obj as *const Reflector);
trace_reflector(tracer, "LIVE_REFERENCES", reflectable);
}
});
}
| ustedReference(* | identifier_name |
plugins.rs | use crate::{
config::{self},
prelude::*,
};
use neon::{prelude::*, result::Throw};
use std::str::FromStr;
use stencila::{
config::Config,
tokio::sync::MutexGuard,
};
use plugins::{self, Plugin, PluginInstallation, Plugins, PLUGINS};
/// Lock the global plugins store
pub fn lock(cx: &mut FunctionContext) -> NeonResult<MutexGuard<'static, Plugins>> {
match PLUGINS.try_lock() {
Ok(guard) => Ok(guard),
Err(error) => cx.throw_error(format!(
"When attempting to lock plugins: {}",
error.to_string()
)),
}
}
/// Get plugin schema
pub fn schema(cx: FunctionContext) -> JsResult<JsString> {
let schema = Plugin::schema();
to_json_or_throw(cx, schema)
}
/// List plugins
pub fn list(mut cx: FunctionContext) -> JsResult<JsString> |
/// Install a plugin
pub fn install(mut cx: FunctionContext) -> JsResult<JsString> {
let spec = &cx.argument::<JsString>(0)?.value(&mut cx);
let config = &config::lock(&mut cx)?;
let installs = &installations(&mut cx, 1, config)?;
let aliases = &config.plugins.aliases;
let plugins = &mut *lock(&mut cx)?;
match RUNTIME.block_on(async { Plugin::install(spec, installs, aliases, plugins, None).await })
{
Ok(_) => to_json(cx, plugins.list_plugins(aliases)),
Err(error) => cx.throw_error(error.to_string()),
}
}
/// Uninstall a plugin
pub fn uninstall(mut cx: FunctionContext) -> JsResult<JsString> {
let alias = &cx.argument::<JsString>(0)?.value(&mut cx);
let aliases = &config::lock(&mut cx)?.plugins.aliases;
let plugins = &mut *lock(&mut cx)?;
match Plugin::uninstall(alias, aliases, plugins) {
Ok(_) => to_json(cx, plugins.list_plugins(aliases)),
Err(error) => cx.throw_error(error.to_string()),
}
}
/// Upgrade a plugin
pub fn upgrade(mut cx: FunctionContext) -> JsResult<JsString> {
let spec = &cx.argument::<JsString>(0)?.value(&mut cx);
let config = &config::lock(&mut cx)?;
let installs = &config.plugins.installations;
let aliases = &config.plugins.aliases;
let plugins = &mut *lock(&mut cx)?;
match RUNTIME.block_on(async { Plugin::upgrade(spec, installs, aliases, plugins).await }) {
Ok(_) => to_json(cx, plugins.list_plugins(aliases)),
Err(error) => cx.throw_error(error.to_string()),
}
}
/// Refresh plugins
pub fn refresh(mut cx: FunctionContext) -> JsResult<JsString> {
let arg = cx.argument::<JsArray>(0)?.to_vec(&mut cx)?;
let list = arg
.iter()
.map(|item| {
item.to_string(&mut cx)
.expect("Unable to convert to string")
.value(&mut cx)
})
.collect();
let config = &config::lock(&mut cx)?;
let aliases = &config.plugins.aliases;
let plugins = &mut *lock(&mut cx)?;
match RUNTIME.block_on(async { Plugin::refresh_list(list, aliases, plugins).await }) {
Ok(_) => to_json(cx, plugins.list_plugins(aliases)),
Err(error) => cx.throw_error(error.to_string()),
}
}
/// Get the `installations` argument, falling back to the array in `config.plugins.installations`
pub fn installations(
cx: &mut FunctionContext,
position: i32,
config: &Config,
) -> Result<Vec<PluginInstallation>, Throw> {
let arg = cx.argument::<JsArray>(position)?.to_vec(cx)?;
if arg.is_empty() {
Ok(config.plugins.installations.clone())
} else {
let mut installations = Vec::new();
for value in arg {
let str = value.to_string(cx)?.value(cx);
let installation = match plugins::PluginInstallation::from_str(&str) {
Ok(value) => value,
Err(error) => return cx.throw_error(error.to_string()),
};
installations.push(installation)
}
Ok(installations)
}
}
| {
let aliases = &config::lock(&mut cx)?.plugins.aliases;
let plugins = &*lock(&mut cx)?;
to_json(cx, plugins.list_plugins(aliases))
} | identifier_body |
plugins.rs | use crate::{
config::{self},
prelude::*,
};
use neon::{prelude::*, result::Throw};
use std::str::FromStr;
use stencila::{
config::Config,
tokio::sync::MutexGuard,
};
use plugins::{self, Plugin, PluginInstallation, Plugins, PLUGINS};
/// Lock the global plugins store
pub fn lock(cx: &mut FunctionContext) -> NeonResult<MutexGuard<'static, Plugins>> {
match PLUGINS.try_lock() {
Ok(guard) => Ok(guard),
Err(error) => cx.throw_error(format!(
"When attempting to lock plugins: {}",
error.to_string()
)),
}
}
/// Get plugin schema
pub fn schema(cx: FunctionContext) -> JsResult<JsString> {
let schema = Plugin::schema();
to_json_or_throw(cx, schema)
}
/// List plugins
pub fn list(mut cx: FunctionContext) -> JsResult<JsString> {
let aliases = &config::lock(&mut cx)?.plugins.aliases;
let plugins = &*lock(&mut cx)?;
to_json(cx, plugins.list_plugins(aliases))
}
/// Install a plugin
pub fn install(mut cx: FunctionContext) -> JsResult<JsString> {
let spec = &cx.argument::<JsString>(0)?.value(&mut cx);
let config = &config::lock(&mut cx)?;
let installs = &installations(&mut cx, 1, config)?;
let aliases = &config.plugins.aliases;
let plugins = &mut *lock(&mut cx)?;
match RUNTIME.block_on(async { Plugin::install(spec, installs, aliases, plugins, None).await })
{
Ok(_) => to_json(cx, plugins.list_plugins(aliases)),
Err(error) => cx.throw_error(error.to_string()),
}
}
/// Uninstall a plugin
pub fn uninstall(mut cx: FunctionContext) -> JsResult<JsString> {
let alias = &cx.argument::<JsString>(0)?.value(&mut cx);
let aliases = &config::lock(&mut cx)?.plugins.aliases;
let plugins = &mut *lock(&mut cx)?;
match Plugin::uninstall(alias, aliases, plugins) {
Ok(_) => to_json(cx, plugins.list_plugins(aliases)),
Err(error) => cx.throw_error(error.to_string()),
}
}
/// Upgrade a plugin
pub fn upgrade(mut cx: FunctionContext) -> JsResult<JsString> {
let spec = &cx.argument::<JsString>(0)?.value(&mut cx);
let config = &config::lock(&mut cx)?;
let installs = &config.plugins.installations;
let aliases = &config.plugins.aliases;
let plugins = &mut *lock(&mut cx)?;
match RUNTIME.block_on(async { Plugin::upgrade(spec, installs, aliases, plugins).await }) {
Ok(_) => to_json(cx, plugins.list_plugins(aliases)),
Err(error) => cx.throw_error(error.to_string()),
}
}
/// Refresh plugins
pub fn refresh(mut cx: FunctionContext) -> JsResult<JsString> {
let arg = cx.argument::<JsArray>(0)?.to_vec(&mut cx)?;
let list = arg
.iter()
.map(|item| {
item.to_string(&mut cx)
.expect("Unable to convert to string")
.value(&mut cx)
})
.collect();
let config = &config::lock(&mut cx)?;
let aliases = &config.plugins.aliases;
let plugins = &mut *lock(&mut cx)?;
match RUNTIME.block_on(async { Plugin::refresh_list(list, aliases, plugins).await }) {
Ok(_) => to_json(cx, plugins.list_plugins(aliases)),
Err(error) => cx.throw_error(error.to_string()),
}
}
/// Get the `installations` argument, falling back to the array in `config.plugins.installations`
pub fn | (
cx: &mut FunctionContext,
position: i32,
config: &Config,
) -> Result<Vec<PluginInstallation>, Throw> {
let arg = cx.argument::<JsArray>(position)?.to_vec(cx)?;
if arg.is_empty() {
Ok(config.plugins.installations.clone())
} else {
let mut installations = Vec::new();
for value in arg {
let str = value.to_string(cx)?.value(cx);
let installation = match plugins::PluginInstallation::from_str(&str) {
Ok(value) => value,
Err(error) => return cx.throw_error(error.to_string()),
};
installations.push(installation)
}
Ok(installations)
}
}
| installations | identifier_name |
plugins.rs | use crate::{
config::{self},
prelude::*,
};
use neon::{prelude::*, result::Throw};
use std::str::FromStr;
use stencila::{
config::Config,
tokio::sync::MutexGuard,
};
use plugins::{self, Plugin, PluginInstallation, Plugins, PLUGINS};
/// Lock the global plugins store
pub fn lock(cx: &mut FunctionContext) -> NeonResult<MutexGuard<'static, Plugins>> {
match PLUGINS.try_lock() {
Ok(guard) => Ok(guard),
Err(error) => cx.throw_error(format!(
"When attempting to lock plugins: {}",
error.to_string()
)),
}
}
/// Get plugin schema
pub fn schema(cx: FunctionContext) -> JsResult<JsString> {
let schema = Plugin::schema();
to_json_or_throw(cx, schema)
}
/// List plugins
pub fn list(mut cx: FunctionContext) -> JsResult<JsString> {
let aliases = &config::lock(&mut cx)?.plugins.aliases;
let plugins = &*lock(&mut cx)?;
to_json(cx, plugins.list_plugins(aliases))
}
/// Install a plugin
pub fn install(mut cx: FunctionContext) -> JsResult<JsString> {
let spec = &cx.argument::<JsString>(0)?.value(&mut cx);
let config = &config::lock(&mut cx)?;
let installs = &installations(&mut cx, 1, config)?;
let aliases = &config.plugins.aliases;
let plugins = &mut *lock(&mut cx)?;
match RUNTIME.block_on(async { Plugin::install(spec, installs, aliases, plugins, None).await }) | {
Ok(_) => to_json(cx, plugins.list_plugins(aliases)),
Err(error) => cx.throw_error(error.to_string()),
}
}
/// Uninstall a plugin
pub fn uninstall(mut cx: FunctionContext) -> JsResult<JsString> {
let alias = &cx.argument::<JsString>(0)?.value(&mut cx);
let aliases = &config::lock(&mut cx)?.plugins.aliases;
let plugins = &mut *lock(&mut cx)?;
match Plugin::uninstall(alias, aliases, plugins) {
Ok(_) => to_json(cx, plugins.list_plugins(aliases)),
Err(error) => cx.throw_error(error.to_string()),
}
}
/// Upgrade a plugin
pub fn upgrade(mut cx: FunctionContext) -> JsResult<JsString> {
let spec = &cx.argument::<JsString>(0)?.value(&mut cx);
let config = &config::lock(&mut cx)?;
let installs = &config.plugins.installations;
let aliases = &config.plugins.aliases;
let plugins = &mut *lock(&mut cx)?;
match RUNTIME.block_on(async { Plugin::upgrade(spec, installs, aliases, plugins).await }) {
Ok(_) => to_json(cx, plugins.list_plugins(aliases)),
Err(error) => cx.throw_error(error.to_string()),
}
}
/// Refresh plugins
pub fn refresh(mut cx: FunctionContext) -> JsResult<JsString> {
let arg = cx.argument::<JsArray>(0)?.to_vec(&mut cx)?;
let list = arg
.iter()
.map(|item| {
item.to_string(&mut cx)
.expect("Unable to convert to string")
.value(&mut cx)
})
.collect();
let config = &config::lock(&mut cx)?;
let aliases = &config.plugins.aliases;
let plugins = &mut *lock(&mut cx)?;
match RUNTIME.block_on(async { Plugin::refresh_list(list, aliases, plugins).await }) {
Ok(_) => to_json(cx, plugins.list_plugins(aliases)),
Err(error) => cx.throw_error(error.to_string()),
}
}
/// Get the `installations` argument, falling back to the array in `config.plugins.installations`
pub fn installations(
cx: &mut FunctionContext,
position: i32,
config: &Config,
) -> Result<Vec<PluginInstallation>, Throw> {
let arg = cx.argument::<JsArray>(position)?.to_vec(cx)?;
if arg.is_empty() {
Ok(config.plugins.installations.clone())
} else {
let mut installations = Vec::new();
for value in arg {
let str = value.to_string(cx)?.value(cx);
let installation = match plugins::PluginInstallation::from_str(&str) {
Ok(value) => value,
Err(error) => return cx.throw_error(error.to_string()),
};
installations.push(installation)
}
Ok(installations)
}
} | random_line_split |
|
mod.rs | // Copyright 2012-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.
//! OS-specific functionality
#![stable(feature = "os", since = "1.0.0")] | #[cfg(windows)] pub use sys::ext as windows;
#[cfg(target_os = "android")] pub mod android;
#[cfg(target_os = "bitrig")] pub mod bitrig;
#[cfg(target_os = "dragonfly")] pub mod dragonfly;
#[cfg(target_os = "freebsd")] pub mod freebsd;
#[cfg(target_os = "ios")] pub mod ios;
#[cfg(target_os = "linux")] pub mod linux;
#[cfg(target_os = "redox")] pub mod redox;
#[cfg(target_os = "macos")] pub mod macos;
#[cfg(target_os = "nacl")] pub mod nacl;
#[cfg(target_os = "netbsd")] pub mod netbsd;
#[cfg(target_os = "openbsd")] pub mod openbsd;
pub mod raw; | #![allow(missing_docs, bad_style)]
#[cfg(unix)] pub use sys::ext as unix; | random_line_split |
persistent_list.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A persistent, thread-safe singly-linked list.
use std::mem;
use std::sync::Arc;
pub struct PersistentList<T> {
head: PersistentListLink<T>,
length: usize,
}
struct PersistentListEntry<T> {
value: T,
next: PersistentListLink<T>,
}
type PersistentListLink<T> = Option<Arc<PersistentListEntry<T>>>;
impl<T> PersistentList<T> where T: Send + Sync {
#[inline]
pub fn new() -> PersistentList<T> {
PersistentList {
head: None,
length: 0,
}
}
#[inline]
pub fn len(&self) -> usize {
self.length
}
#[inline]
pub fn front(&self) -> Option<&T> {
self.head.as_ref().map(|head| &head.value)
}
#[inline]
pub fn prepend_elem(&self, value: T) -> PersistentList<T> {
PersistentList {
head: Some(Arc::new(PersistentListEntry {
value: value,
next: self.head.clone(),
})),
length: self.length + 1,
}
}
#[inline]
pub fn iter<'a>(&'a self) -> PersistentListIterator<'a,T> {
// This could clone (and would not need the lifetime if it did), but then it would incur
// atomic operations on every call to `.next()`. Bad.
PersistentListIterator {
entry: self.head.as_ref().map(|head| &**head),
}
}
}
impl<T> Clone for PersistentList<T> where T: Send + Sync {
fn | (&self) -> PersistentList<T> {
// This establishes the persistent nature of this list: we can clone a list by just cloning
// its head.
PersistentList {
head: self.head.clone(),
length: self.length,
}
}
}
pub struct PersistentListIterator<'a,T> where T: 'a + Send + Sync {
entry: Option<&'a PersistentListEntry<T>>,
}
impl<'a,T> Iterator for PersistentListIterator<'a,T> where T: Send + Sync +'static {
type Item = &'a T;
#[inline]
fn next(&mut self) -> Option<&'a T> {
let entry = match self.entry {
None => return None,
Some(entry) => {
// This `transmute` is necessary to ensure that the lifetimes of the next entry and
// this entry match up; the compiler doesn't know this, but we do because of the
// reference counting behavior of `Arc`.
unsafe {
mem::transmute::<&'a PersistentListEntry<T>,
&'static PersistentListEntry<T>>(entry)
}
}
};
let value = &entry.value;
self.entry = match entry.next {
None => None,
Some(ref entry) => Some(&**entry),
};
Some(value)
}
}
| clone | identifier_name |
persistent_list.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A persistent, thread-safe singly-linked list. |
use std::mem;
use std::sync::Arc;
pub struct PersistentList<T> {
head: PersistentListLink<T>,
length: usize,
}
struct PersistentListEntry<T> {
value: T,
next: PersistentListLink<T>,
}
type PersistentListLink<T> = Option<Arc<PersistentListEntry<T>>>;
impl<T> PersistentList<T> where T: Send + Sync {
#[inline]
pub fn new() -> PersistentList<T> {
PersistentList {
head: None,
length: 0,
}
}
#[inline]
pub fn len(&self) -> usize {
self.length
}
#[inline]
pub fn front(&self) -> Option<&T> {
self.head.as_ref().map(|head| &head.value)
}
#[inline]
pub fn prepend_elem(&self, value: T) -> PersistentList<T> {
PersistentList {
head: Some(Arc::new(PersistentListEntry {
value: value,
next: self.head.clone(),
})),
length: self.length + 1,
}
}
#[inline]
pub fn iter<'a>(&'a self) -> PersistentListIterator<'a,T> {
// This could clone (and would not need the lifetime if it did), but then it would incur
// atomic operations on every call to `.next()`. Bad.
PersistentListIterator {
entry: self.head.as_ref().map(|head| &**head),
}
}
}
impl<T> Clone for PersistentList<T> where T: Send + Sync {
fn clone(&self) -> PersistentList<T> {
// This establishes the persistent nature of this list: we can clone a list by just cloning
// its head.
PersistentList {
head: self.head.clone(),
length: self.length,
}
}
}
pub struct PersistentListIterator<'a,T> where T: 'a + Send + Sync {
entry: Option<&'a PersistentListEntry<T>>,
}
impl<'a,T> Iterator for PersistentListIterator<'a,T> where T: Send + Sync +'static {
type Item = &'a T;
#[inline]
fn next(&mut self) -> Option<&'a T> {
let entry = match self.entry {
None => return None,
Some(entry) => {
// This `transmute` is necessary to ensure that the lifetimes of the next entry and
// this entry match up; the compiler doesn't know this, but we do because of the
// reference counting behavior of `Arc`.
unsafe {
mem::transmute::<&'a PersistentListEntry<T>,
&'static PersistentListEntry<T>>(entry)
}
}
};
let value = &entry.value;
self.entry = match entry.next {
None => None,
Some(ref entry) => Some(&**entry),
};
Some(value)
}
} | random_line_split |
|
map.rs | #![allow(dead_code)]
#[derive(Debug)] enum | { Apple, Carrot, Potato }
#[derive(Debug)] struct Peeled(Food);
#[derive(Debug)] struct Chopped(Food);
#[derive(Debug)] struct Cooked(Food);
// 削水果皮。如果没有水果,就返回 `None`。
// 否则返回削好皮的水果。
fn peel(food: Option<Food>) -> Option<Peeled> {
match food {
Some(food) => Some(Peeled(food)),
None => None,
}
}
// 和上面一样,我们要在切水果之前确认水果是否已经削皮。
fn chop(peeled: Option<Peeled>) -> Option<Chopped> {
match peeled {
Some(Peeled(food)) => Some(Chopped(food)),
None => None,
}
}
// 和前面的检查类似,但是使用 `map()` 来替代 `match`。
fn cook(chopped: Option<Chopped>) -> Option<Cooked> {
chopped.map(|Chopped(food)| Cooked(food))
}
// 另外一种实现,我们可以链式调用 `map()` 来简化上述的流程。
fn process(food: Option<Food>) -> Option<Cooked> {
food.map(|f| Peeled(f))
.map(|Peeled(f)| Chopped(f))
.map(|Chopped(f)| Cooked(f))
}
// 在尝试吃水果之前确认水果是否存在是非常重要的!
fn eat(food: Option<Cooked>) {
match food {
Some(food) => println!("Mmm. I love {:?}", food),
None => println!("Oh no! It wasn't edible."),
}
}
fn main() {
let apple = Some(Food::Apple);
let carrot = Some(Food::Carrot);
let potato = None;
let cooked_apple = cook(chop(peel(apple)));
let cooked_carrot = cook(chop(peel(carrot)));
// 现在让我们试试更简便的方式 `process()`。
// (原文:Let's try the simpler looking `process()` now.)
// (翻译疑问:looking 是什么意思呢?望指教。)
let cooked_potato = process(potato);
eat(cooked_apple);
eat(cooked_carrot);
eat(cooked_potato);
}
| Food | identifier_name |
map.rs | #![allow(dead_code)]
#[derive(Debug)] enum Food { Apple, Carrot, Potato }
#[derive(Debug)] struct Peeled(Food);
#[derive(Debug)] struct Chopped(Food);
#[derive(Debug)] struct Cooked(Food);
// 削水果皮。如果没有水果,就返回 `None`。
// 否则返回削好皮的水果。
fn peel(food: Option<Food>) -> Option<Peeled> {
match food {
Some(food) => Some(Peeled(food)),
None => None,
}
}
| Some(Peeled(food)) => Some(Chopped(food)),
None => None,
}
}
// 和前面的检查类似,但是使用 `map()` 来替代 `match`。
fn cook(chopped: Option<Chopped>) -> Option<Cooked> {
chopped.map(|Chopped(food)| Cooked(food))
}
// 另外一种实现,我们可以链式调用 `map()` 来简化上述的流程。
fn process(food: Option<Food>) -> Option<Cooked> {
food.map(|f| Peeled(f))
.map(|Peeled(f)| Chopped(f))
.map(|Chopped(f)| Cooked(f))
}
// 在尝试吃水果之前确认水果是否存在是非常重要的!
fn eat(food: Option<Cooked>) {
match food {
Some(food) => println!("Mmm. I love {:?}", food),
None => println!("Oh no! It wasn't edible."),
}
}
fn main() {
let apple = Some(Food::Apple);
let carrot = Some(Food::Carrot);
let potato = None;
let cooked_apple = cook(chop(peel(apple)));
let cooked_carrot = cook(chop(peel(carrot)));
// 现在让我们试试更简便的方式 `process()`。
// (原文:Let's try the simpler looking `process()` now.)
// (翻译疑问:looking 是什么意思呢?望指教。)
let cooked_potato = process(potato);
eat(cooked_apple);
eat(cooked_carrot);
eat(cooked_potato);
} | // 和上面一样,我们要在切水果之前确认水果是否已经削皮。
fn chop(peeled: Option<Peeled>) -> Option<Chopped> {
match peeled { | random_line_split |
drawing.rs | /*
* Copyright (c) 2018 Boucher, Antoni <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use std::f64::consts::PI;
use gdk::{EventMask, RGBA};
use gtk::{
DrawingArea,
Inhibit,
prelude::BoxExt,
prelude::OrientableExt,
prelude::WidgetExt,
prelude::WidgetExtManual,
};
use gtk::Orientation::Vertical;
use rand::Rng;
use relm_derive::Msg;
use relm::{
DrawHandler,
Relm,
Widget,
interval,
};
use relm_derive::widget;
use self::Msg::*;
const SIZE: f64 = 15.0;
struct Circle {
x: f64,
y: f64,
color: RGBA,
vx: f64,
vy: f64,
}
impl Circle {
fn generate() -> Self { | x: gen.gen_range(20.0, 500.0),
y: gen.gen_range(20.0, 500.0),
color: RGBA::new(
gen.gen_range(0.0, 1.0),
gen.gen_range(0.0, 1.0),
gen.gen_range(0.0, 1.0),
1.0,
),
vx: gen.gen_range(1.0, 5.0),
vy: gen.gen_range(1.0, 5.0),
}
}
}
pub struct Model {
draw_handler: DrawHandler<DrawingArea>,
circles: Vec<Circle>,
cursor_pos: (f64, f64),
}
#[derive(Msg)]
pub enum Msg {
Generate,
Move,
MoveCursor((f64, f64)),
Quit,
UpdateDrawBuffer,
}
#[widget]
impl Widget for Win {
fn init_view(&mut self) {
self.model.draw_handler.init(&self.widgets.drawing_area);
self.widgets.drawing_area.add_events(EventMask::POINTER_MOTION_MASK);
}
fn model() -> Model {
Model {
draw_handler: DrawHandler::new().expect("draw handler"),
circles: vec![Circle::generate()],
cursor_pos: (-1000.0, -1000.0),
}
}
fn subscriptions(&mut self, relm: &Relm<Self>) {
interval(relm.stream(), 1000, || Generate);
interval(relm.stream(), 16, || Move);
}
fn update(&mut self, event: Msg) {
match event {
Generate => self.model.circles.push(Circle::generate()),
Move => {
let allocation = self.widgets.drawing_area.allocation();
for circle in &mut self.model.circles {
if (circle.x + circle.vx + SIZE / 2.0 < allocation.width() as f64)
&& (circle.x + circle.vx - SIZE / 2.0 > 0.0)
{
circle.x += circle.vx;
}
else {
circle.vx *= -1.0;
}
if (circle.y + circle.vy + SIZE / 2.0 < allocation.height() as f64)
&& (circle.y + circle.vy - SIZE / 2.0 > 0.0)
{
circle.y += circle.vy;
}
else {
circle.vy *= -1.0;
}
}
},
MoveCursor(pos) => self.model.cursor_pos = pos,
Quit => gtk::main_quit(),
UpdateDrawBuffer => {
let context = self.model.draw_handler.get_context().unwrap();
context.set_source_rgb(1.0, 1.0, 1.0);
context.paint().unwrap();
for circle in &self.model.circles {
context.set_source_rgb(
circle.color.red(),
circle.color.green(),
circle.color.blue(),
);
context.arc(circle.x, circle.y, SIZE, 0.0, 2.0 * PI);
context.fill().unwrap();
}
context.set_source_rgb(0.1, 0.2, 0.3);
context.rectangle(self.model.cursor_pos.0 - SIZE / 2.0, self.model.cursor_pos.1 - SIZE / 2.0, SIZE,
SIZE);
context.fill().unwrap();
},
}
}
view! {
gtk::Window {
gtk::Box {
orientation: Vertical,
#[name="drawing_area"]
gtk::DrawingArea {
child: {
expand: true,
},
draw(_, _) => (UpdateDrawBuffer, Inhibit(false)),
motion_notify_event(_, event) => (MoveCursor(event.position()), Inhibit(false))
},
},
delete_event(_, _) => (Quit, Inhibit(false)),
}
}
}
fn main() {
Win::run(()).unwrap();
} | let mut gen = rand::thread_rng();
Circle { | random_line_split |
drawing.rs | /*
* Copyright (c) 2018 Boucher, Antoni <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use std::f64::consts::PI;
use gdk::{EventMask, RGBA};
use gtk::{
DrawingArea,
Inhibit,
prelude::BoxExt,
prelude::OrientableExt,
prelude::WidgetExt,
prelude::WidgetExtManual,
};
use gtk::Orientation::Vertical;
use rand::Rng;
use relm_derive::Msg;
use relm::{
DrawHandler,
Relm,
Widget,
interval,
};
use relm_derive::widget;
use self::Msg::*;
const SIZE: f64 = 15.0;
struct Circle {
x: f64,
y: f64,
color: RGBA,
vx: f64,
vy: f64,
}
impl Circle {
fn generate() -> Self {
let mut gen = rand::thread_rng();
Circle {
x: gen.gen_range(20.0, 500.0),
y: gen.gen_range(20.0, 500.0),
color: RGBA::new(
gen.gen_range(0.0, 1.0),
gen.gen_range(0.0, 1.0),
gen.gen_range(0.0, 1.0),
1.0,
),
vx: gen.gen_range(1.0, 5.0),
vy: gen.gen_range(1.0, 5.0),
}
}
}
pub struct Model {
draw_handler: DrawHandler<DrawingArea>,
circles: Vec<Circle>,
cursor_pos: (f64, f64),
}
#[derive(Msg)]
pub enum Msg {
Generate,
Move,
MoveCursor((f64, f64)),
Quit,
UpdateDrawBuffer,
}
#[widget]
impl Widget for Win {
fn init_view(&mut self) {
self.model.draw_handler.init(&self.widgets.drawing_area);
self.widgets.drawing_area.add_events(EventMask::POINTER_MOTION_MASK);
}
fn model() -> Model {
Model {
draw_handler: DrawHandler::new().expect("draw handler"),
circles: vec![Circle::generate()],
cursor_pos: (-1000.0, -1000.0),
}
}
fn subscriptions(&mut self, relm: &Relm<Self>) {
interval(relm.stream(), 1000, || Generate);
interval(relm.stream(), 16, || Move);
}
fn update(&mut self, event: Msg) {
match event {
Generate => self.model.circles.push(Circle::generate()),
Move => {
let allocation = self.widgets.drawing_area.allocation();
for circle in &mut self.model.circles {
if (circle.x + circle.vx + SIZE / 2.0 < allocation.width() as f64)
&& (circle.x + circle.vx - SIZE / 2.0 > 0.0)
{
circle.x += circle.vx;
}
else {
circle.vx *= -1.0;
}
if (circle.y + circle.vy + SIZE / 2.0 < allocation.height() as f64)
&& (circle.y + circle.vy - SIZE / 2.0 > 0.0)
{
circle.y += circle.vy;
}
else {
circle.vy *= -1.0;
}
}
},
MoveCursor(pos) => self.model.cursor_pos = pos,
Quit => gtk::main_quit(),
UpdateDrawBuffer => {
let context = self.model.draw_handler.get_context().unwrap();
context.set_source_rgb(1.0, 1.0, 1.0);
context.paint().unwrap();
for circle in &self.model.circles {
context.set_source_rgb(
circle.color.red(),
circle.color.green(),
circle.color.blue(),
);
context.arc(circle.x, circle.y, SIZE, 0.0, 2.0 * PI);
context.fill().unwrap();
}
context.set_source_rgb(0.1, 0.2, 0.3);
context.rectangle(self.model.cursor_pos.0 - SIZE / 2.0, self.model.cursor_pos.1 - SIZE / 2.0, SIZE,
SIZE);
context.fill().unwrap();
},
}
}
view! {
gtk::Window {
gtk::Box {
orientation: Vertical,
#[name="drawing_area"]
gtk::DrawingArea {
child: {
expand: true,
},
draw(_, _) => (UpdateDrawBuffer, Inhibit(false)),
motion_notify_event(_, event) => (MoveCursor(event.position()), Inhibit(false))
},
},
delete_event(_, _) => (Quit, Inhibit(false)),
}
}
}
fn | () {
Win::run(()).unwrap();
}
| main | identifier_name |
finally.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
The Finally trait provides a method, `finally` on
stack closures that emulates Java-style try/finally blocks.
# Example
```
(|| {
...
}).finally(|| {
always_run_this();
})
```
*/
use ops::Drop;
#[cfg(test)] use task::failing;
pub trait Finally<T> {
fn finally(&self, dtor: ||) -> T;
}
macro_rules! finally_fn {
($fnty:ty) => {
impl<T> Finally<T> for $fnty {
fn finally(&self, dtor: ||) -> T {
let _d = Finallyalizer {
dtor: dtor
};
(*self)()
}
}
}
}
impl<'a,T> Finally<T> for 'a || -> T {
fn finally(&self, dtor: ||) -> T {
let _d = Finallyalizer {
dtor: dtor
};
(*self)()
}
}
finally_fn!(extern "Rust" fn() -> T)
struct Finallyalizer<'a> {
dtor: 'a ||
}
#[unsafe_destructor]
impl<'a> Drop for Finallyalizer<'a> {
fn drop(&mut self) {
(self.dtor)();
}
}
#[test]
fn test_success() {
let mut i = 0;
(|| {
i = 10;
}).finally(|| {
assert!(!failing());
assert_eq!(i, 10);
i = 20;
});
assert_eq!(i, 20);
}
#[test]
#[should_fail]
fn | () {
let mut i = 0;
(|| {
i = 10;
fail!();
}).finally(|| {
assert!(failing());
assert_eq!(i, 10);
})
}
#[test]
fn test_retval() {
let closure: || -> int = || 10;
let i = closure.finally(|| { });
assert_eq!(i, 10);
}
#[test]
fn test_compact() {
fn do_some_fallible_work() {}
fn but_always_run_this_function() { }
do_some_fallible_work.finally(
but_always_run_this_function);
}
| test_fail | identifier_name |
finally.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
The Finally trait provides a method, `finally` on
stack closures that emulates Java-style try/finally blocks.
# Example
```
(|| {
...
}).finally(|| {
always_run_this();
})
```
*/
use ops::Drop;
#[cfg(test)] use task::failing;
pub trait Finally<T> {
fn finally(&self, dtor: ||) -> T;
}
macro_rules! finally_fn {
($fnty:ty) => {
impl<T> Finally<T> for $fnty {
fn finally(&self, dtor: ||) -> T {
let _d = Finallyalizer {
dtor: dtor
};
(*self)()
}
}
}
}
impl<'a,T> Finally<T> for 'a || -> T {
fn finally(&self, dtor: ||) -> T {
let _d = Finallyalizer {
dtor: dtor
};
(*self)()
}
}
finally_fn!(extern "Rust" fn() -> T)
struct Finallyalizer<'a> {
dtor: 'a ||
}
#[unsafe_destructor]
impl<'a> Drop for Finallyalizer<'a> {
fn drop(&mut self) |
}
#[test]
fn test_success() {
let mut i = 0;
(|| {
i = 10;
}).finally(|| {
assert!(!failing());
assert_eq!(i, 10);
i = 20;
});
assert_eq!(i, 20);
}
#[test]
#[should_fail]
fn test_fail() {
let mut i = 0;
(|| {
i = 10;
fail!();
}).finally(|| {
assert!(failing());
assert_eq!(i, 10);
})
}
#[test]
fn test_retval() {
let closure: || -> int = || 10;
let i = closure.finally(|| { });
assert_eq!(i, 10);
}
#[test]
fn test_compact() {
fn do_some_fallible_work() {}
fn but_always_run_this_function() { }
do_some_fallible_work.finally(
but_always_run_this_function);
}
| {
(self.dtor)();
} | identifier_body |
finally.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
The Finally trait provides a method, `finally` on
stack closures that emulates Java-style try/finally blocks.
# Example
```
(|| {
...
}).finally(|| {
always_run_this();
})
```
*/
use ops::Drop;
#[cfg(test)] use task::failing;
pub trait Finally<T> {
fn finally(&self, dtor: ||) -> T;
}
macro_rules! finally_fn {
($fnty:ty) => {
impl<T> Finally<T> for $fnty {
fn finally(&self, dtor: ||) -> T {
let _d = Finallyalizer {
dtor: dtor
};
(*self)() | }
impl<'a,T> Finally<T> for 'a || -> T {
fn finally(&self, dtor: ||) -> T {
let _d = Finallyalizer {
dtor: dtor
};
(*self)()
}
}
finally_fn!(extern "Rust" fn() -> T)
struct Finallyalizer<'a> {
dtor: 'a ||
}
#[unsafe_destructor]
impl<'a> Drop for Finallyalizer<'a> {
fn drop(&mut self) {
(self.dtor)();
}
}
#[test]
fn test_success() {
let mut i = 0;
(|| {
i = 10;
}).finally(|| {
assert!(!failing());
assert_eq!(i, 10);
i = 20;
});
assert_eq!(i, 20);
}
#[test]
#[should_fail]
fn test_fail() {
let mut i = 0;
(|| {
i = 10;
fail!();
}).finally(|| {
assert!(failing());
assert_eq!(i, 10);
})
}
#[test]
fn test_retval() {
let closure: || -> int = || 10;
let i = closure.finally(|| { });
assert_eq!(i, 10);
}
#[test]
fn test_compact() {
fn do_some_fallible_work() {}
fn but_always_run_this_function() { }
do_some_fallible_work.finally(
but_always_run_this_function);
} | }
}
} | random_line_split |
const-fields-and-indexing.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.
const x : [isize; 4] = [1,2,3,4];
static p : isize = x[2];
const y : &'static [isize] = &[1,2,3,4];
static q : isize = y[2];
struct S {a: isize, b: isize}
const s : S = S {a: 10, b: 20}; | struct K {a: isize, b: isize, c: D}
struct D { d: isize, e: isize }
const k : K = K {a: 10, b: 20, c: D {d: 30, e: 40}};
static m : isize = k.c.e;
pub fn main() {
println!("{}", p);
println!("{}", q);
println!("{}", t);
assert_eq!(p, 3);
assert_eq!(q, 3);
assert_eq!(t, 20);
} | static t : isize = s.b;
| random_line_split |
const-fields-and-indexing.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.
const x : [isize; 4] = [1,2,3,4];
static p : isize = x[2];
const y : &'static [isize] = &[1,2,3,4];
static q : isize = y[2];
struct S {a: isize, b: isize}
const s : S = S {a: 10, b: 20};
static t : isize = s.b;
struct K {a: isize, b: isize, c: D}
struct | { d: isize, e: isize }
const k : K = K {a: 10, b: 20, c: D {d: 30, e: 40}};
static m : isize = k.c.e;
pub fn main() {
println!("{}", p);
println!("{}", q);
println!("{}", t);
assert_eq!(p, 3);
assert_eq!(q, 3);
assert_eq!(t, 20);
}
| D | identifier_name |
uniq-cc.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(managed_boxes)]
use std::cell::RefCell;
enum maybe_pointy {
none,
p(@RefCell<Pointy>),
}
struct Pointy {
a : maybe_pointy,
c : Box<int>,
d : proc():Send->(),
}
fn empty_pointy() -> @RefCell<Pointy> {
return @RefCell::new(Pointy {
a : none,
c : box 22,
d : proc() {},
})
}
pub fn main() | {
let v = empty_pointy();
{
let mut vb = v.borrow_mut();
vb.a = p(v);
}
} | identifier_body |
|
uniq-cc.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.
|
use std::cell::RefCell;
enum maybe_pointy {
none,
p(@RefCell<Pointy>),
}
struct Pointy {
a : maybe_pointy,
c : Box<int>,
d : proc():Send->(),
}
fn empty_pointy() -> @RefCell<Pointy> {
return @RefCell::new(Pointy {
a : none,
c : box 22,
d : proc() {},
})
}
pub fn main() {
let v = empty_pointy();
{
let mut vb = v.borrow_mut();
vb.a = p(v);
}
} | #![feature(managed_boxes)] | random_line_split |
uniq-cc.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(managed_boxes)]
use std::cell::RefCell;
enum maybe_pointy {
none,
p(@RefCell<Pointy>),
}
struct Pointy {
a : maybe_pointy,
c : Box<int>,
d : proc():Send->(),
}
fn | () -> @RefCell<Pointy> {
return @RefCell::new(Pointy {
a : none,
c : box 22,
d : proc() {},
})
}
pub fn main() {
let v = empty_pointy();
{
let mut vb = v.borrow_mut();
vb.a = p(v);
}
}
| empty_pointy | identifier_name |
lub.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.
use super::combine::*;
use super::equate::Equate;
use super::glb::Glb;
use super::higher_ranked::HigherRankedRelations;
use super::lattice::*;
use super::sub::Sub;
use super::{cres, InferCtxt};
use super::{TypeTrace, Subtype};
use middle::ty::{BuiltinBounds};
use middle::ty::{self, Ty};
use syntax::ast::{Many, Once};
use syntax::ast::{Onceness, Unsafety};
use syntax::ast::{MutMutable, MutImmutable};
use util::ppaux::mt_to_string;
use util::ppaux::Repr;
/// "Least upper bound" (common supertype)
pub struct Lub<'f, 'tcx: 'f> {
fields: CombineFields<'f, 'tcx>
}
#[allow(non_snake_case)]
pub fn Lub<'f, 'tcx>(cf: CombineFields<'f, 'tcx>) -> Lub<'f, 'tcx> {
Lub { fields: cf }
}
impl<'f, 'tcx> Combine<'tcx> for Lub<'f, 'tcx> {
fn infcx<'a>(&'a self) -> &'a InferCtxt<'a, 'tcx> { self.fields.infcx }
fn tag(&self) -> String { "lub".to_string() }
fn a_is_expected(&self) -> bool { self.fields.a_is_expected }
fn trace(&self) -> TypeTrace<'tcx> { self.fields.trace.clone() }
fn | <'a>(&'a self) -> Equate<'a, 'tcx> { Equate(self.fields.clone()) }
fn sub<'a>(&'a self) -> Sub<'a, 'tcx> { Sub(self.fields.clone()) }
fn lub<'a>(&'a self) -> Lub<'a, 'tcx> { Lub(self.fields.clone()) }
fn glb<'a>(&'a self) -> Glb<'a, 'tcx> { Glb(self.fields.clone()) }
fn mts(&self, a: &ty::mt<'tcx>, b: &ty::mt<'tcx>) -> cres<'tcx, ty::mt<'tcx>> {
let tcx = self.tcx();
debug!("{}.mts({}, {})",
self.tag(),
mt_to_string(tcx, a),
mt_to_string(tcx, b));
if a.mutbl!= b.mutbl {
return Err(ty::terr_mutability)
}
let m = a.mutbl;
match m {
MutImmutable => {
let t = try!(self.tys(a.ty, b.ty));
Ok(ty::mt {ty: t, mutbl: m})
}
MutMutable => {
let t = try!(self.equate().tys(a.ty, b.ty));
Ok(ty::mt {ty: t, mutbl: m})
}
}
}
fn contratys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> cres<'tcx, Ty<'tcx>> {
self.glb().tys(a, b)
}
fn unsafeties(&self, a: Unsafety, b: Unsafety) -> cres<'tcx, Unsafety> {
match (a, b) {
(Unsafety::Unsafe, _) | (_, Unsafety::Unsafe) => Ok(Unsafety::Unsafe),
(Unsafety::Normal, Unsafety::Normal) => Ok(Unsafety::Normal),
}
}
fn oncenesses(&self, a: Onceness, b: Onceness) -> cres<'tcx, Onceness> {
match (a, b) {
(Once, _) | (_, Once) => Ok(Once),
(Many, Many) => Ok(Many)
}
}
fn builtin_bounds(&self,
a: ty::BuiltinBounds,
b: ty::BuiltinBounds)
-> cres<'tcx, ty::BuiltinBounds> {
// More bounds is a subtype of fewer bounds, so
// the LUB (mutual supertype) is the intersection.
Ok(a.intersection(b))
}
fn contraregions(&self, a: ty::Region, b: ty::Region)
-> cres<'tcx, ty::Region> {
self.glb().regions(a, b)
}
fn regions(&self, a: ty::Region, b: ty::Region) -> cres<'tcx, ty::Region> {
debug!("{}.regions({}, {})",
self.tag(),
a.repr(self.tcx()),
b.repr(self.tcx()));
Ok(self.infcx().region_vars.lub_regions(Subtype(self.trace()), a, b))
}
fn tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> cres<'tcx, Ty<'tcx>> {
super_lattice_tys(self, a, b)
}
fn binders<T>(&self, a: &ty::Binder<T>, b: &ty::Binder<T>) -> cres<'tcx, ty::Binder<T>>
where T : Combineable<'tcx>
{
self.higher_ranked_lub(a, b)
}
}
| equate | identifier_name |
lub.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.
use super::combine::*;
use super::equate::Equate;
use super::glb::Glb;
use super::higher_ranked::HigherRankedRelations;
use super::lattice::*;
use super::sub::Sub;
use super::{cres, InferCtxt};
use super::{TypeTrace, Subtype};
use middle::ty::{BuiltinBounds};
use middle::ty::{self, Ty};
use syntax::ast::{Many, Once};
use syntax::ast::{Onceness, Unsafety};
use syntax::ast::{MutMutable, MutImmutable};
use util::ppaux::mt_to_string;
use util::ppaux::Repr;
/// "Least upper bound" (common supertype)
pub struct Lub<'f, 'tcx: 'f> {
fields: CombineFields<'f, 'tcx>
}
#[allow(non_snake_case)]
pub fn Lub<'f, 'tcx>(cf: CombineFields<'f, 'tcx>) -> Lub<'f, 'tcx> {
Lub { fields: cf }
}
impl<'f, 'tcx> Combine<'tcx> for Lub<'f, 'tcx> {
fn infcx<'a>(&'a self) -> &'a InferCtxt<'a, 'tcx> { self.fields.infcx }
fn tag(&self) -> String { "lub".to_string() }
fn a_is_expected(&self) -> bool { self.fields.a_is_expected }
fn trace(&self) -> TypeTrace<'tcx> { self.fields.trace.clone() }
fn equate<'a>(&'a self) -> Equate<'a, 'tcx> { Equate(self.fields.clone()) }
fn sub<'a>(&'a self) -> Sub<'a, 'tcx> { Sub(self.fields.clone()) }
fn lub<'a>(&'a self) -> Lub<'a, 'tcx> { Lub(self.fields.clone()) }
fn glb<'a>(&'a self) -> Glb<'a, 'tcx> { Glb(self.fields.clone()) }
fn mts(&self, a: &ty::mt<'tcx>, b: &ty::mt<'tcx>) -> cres<'tcx, ty::mt<'tcx>> {
let tcx = self.tcx();
debug!("{}.mts({}, {})",
self.tag(),
mt_to_string(tcx, a),
mt_to_string(tcx, b));
if a.mutbl!= b.mutbl { | return Err(ty::terr_mutability)
}
let m = a.mutbl;
match m {
MutImmutable => {
let t = try!(self.tys(a.ty, b.ty));
Ok(ty::mt {ty: t, mutbl: m})
}
MutMutable => {
let t = try!(self.equate().tys(a.ty, b.ty));
Ok(ty::mt {ty: t, mutbl: m})
}
}
}
fn contratys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> cres<'tcx, Ty<'tcx>> {
self.glb().tys(a, b)
}
fn unsafeties(&self, a: Unsafety, b: Unsafety) -> cres<'tcx, Unsafety> {
match (a, b) {
(Unsafety::Unsafe, _) | (_, Unsafety::Unsafe) => Ok(Unsafety::Unsafe),
(Unsafety::Normal, Unsafety::Normal) => Ok(Unsafety::Normal),
}
}
fn oncenesses(&self, a: Onceness, b: Onceness) -> cres<'tcx, Onceness> {
match (a, b) {
(Once, _) | (_, Once) => Ok(Once),
(Many, Many) => Ok(Many)
}
}
fn builtin_bounds(&self,
a: ty::BuiltinBounds,
b: ty::BuiltinBounds)
-> cres<'tcx, ty::BuiltinBounds> {
// More bounds is a subtype of fewer bounds, so
// the LUB (mutual supertype) is the intersection.
Ok(a.intersection(b))
}
fn contraregions(&self, a: ty::Region, b: ty::Region)
-> cres<'tcx, ty::Region> {
self.glb().regions(a, b)
}
fn regions(&self, a: ty::Region, b: ty::Region) -> cres<'tcx, ty::Region> {
debug!("{}.regions({}, {})",
self.tag(),
a.repr(self.tcx()),
b.repr(self.tcx()));
Ok(self.infcx().region_vars.lub_regions(Subtype(self.trace()), a, b))
}
fn tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> cres<'tcx, Ty<'tcx>> {
super_lattice_tys(self, a, b)
}
fn binders<T>(&self, a: &ty::Binder<T>, b: &ty::Binder<T>) -> cres<'tcx, ty::Binder<T>>
where T : Combineable<'tcx>
{
self.higher_ranked_lub(a, b)
}
} | random_line_split |
|
count.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::Enumerate;
struct | <T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {
if self.begin < self.end {
let result = self.begin;
self.begin = self.begin.wrapping_add(1);
Some::<Self::Item>(result)
} else {
None::<Self::Item>
}
}
// fn enumerate(self) -> Enumerate<Self> where Self: Sized {
// Enumerate { iter: self, count: 0 }
// }
// fn count(self) -> usize where Self: Sized {
// // Might overflow.
// self.fold(0, |cnt, _| cnt + 1)
// }
}
}
}
type T = i32;
Iterator_impl!(T);
// impl<I> Iterator for Enumerate<I> where I: Iterator {
// type Item = (usize, <I as Iterator>::Item);
//
// /// # Overflow Behavior
// ///
// /// The method does no guarding against overflows, so enumerating more than
// /// `usize::MAX` elements either produces the wrong result or panics. If
// /// debug assertions are enabled, a panic is guaranteed.
// ///
// /// # Panics
// ///
// /// Might panic if the index of the element overflows a `usize`.
// #[inline]
// fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
// self.iter.next().map(|a| {
// let ret = (self.count, a);
// // Possible undefined overflow.
// self.count += 1;
// ret
// })
// }
//
// #[inline]
// fn size_hint(&self) -> (usize, Option<usize>) {
// self.iter.size_hint()
// }
//
// #[inline]
// fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
// self.iter.nth(n).map(|a| {
// let i = self.count + n;
// self.count = i + 1;
// (i, a)
// })
// }
//
// #[inline]
// fn count(self) -> usize {
// self.iter.count()
// }
// }
#[test]
fn count_test1() {
let a: A<T> = A { begin: 10, end: 20 };
let enumerate: Enumerate<A<T>> = a.enumerate();
assert_eq!(enumerate.count(), 10);
}
#[test]
fn count_test2() {
let a: A<T> = A { begin: 10, end: 20 };
let mut enumerate: Enumerate<A<T>> = a.enumerate();
enumerate.next();
assert_eq!(enumerate.count(), 9);
}
}
| A | identifier_name |
count.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::Enumerate;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {
if self.begin < self.end {
let result = self.begin;
self.begin = self.begin.wrapping_add(1);
Some::<Self::Item>(result)
} else {
None::<Self::Item>
}
}
// fn enumerate(self) -> Enumerate<Self> where Self: Sized {
// Enumerate { iter: self, count: 0 }
// }
// fn count(self) -> usize where Self: Sized {
// // Might overflow.
// self.fold(0, |cnt, _| cnt + 1)
// }
}
}
}
type T = i32;
Iterator_impl!(T);
// impl<I> Iterator for Enumerate<I> where I: Iterator {
// type Item = (usize, <I as Iterator>::Item);
//
// /// # Overflow Behavior
// ///
// /// The method does no guarding against overflows, so enumerating more than
// /// `usize::MAX` elements either produces the wrong result or panics. If
// /// debug assertions are enabled, a panic is guaranteed.
// ///
// /// # Panics
// ///
// /// Might panic if the index of the element overflows a `usize`.
// #[inline]
// fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
// self.iter.next().map(|a| {
// let ret = (self.count, a);
// // Possible undefined overflow.
// self.count += 1;
// ret
// })
// }
//
// #[inline]
// fn size_hint(&self) -> (usize, Option<usize>) {
// self.iter.size_hint()
// }
//
// #[inline]
// fn nth(&mut self, n: usize) -> Option<(usize, I::Item)> {
// self.iter.nth(n).map(|a| { | //
// #[inline]
// fn count(self) -> usize {
// self.iter.count()
// }
// }
#[test]
fn count_test1() {
let a: A<T> = A { begin: 10, end: 20 };
let enumerate: Enumerate<A<T>> = a.enumerate();
assert_eq!(enumerate.count(), 10);
}
#[test]
fn count_test2() {
let a: A<T> = A { begin: 10, end: 20 };
let mut enumerate: Enumerate<A<T>> = a.enumerate();
enumerate.next();
assert_eq!(enumerate.count(), 9);
}
} | // let i = self.count + n;
// self.count = i + 1;
// (i, a)
// })
// } | random_line_split |
test.rs | text
/* this is a
/* nested
block */ comment.
And should stay a comment
even with "strings"
or 42 0x18 0b01011 // blah
or u32 as i16 if impl */
text
/** this is a
/*! nested
block */ doc comment */
text
/// test
/// *test*
/// **test**
/// ***test***
/// _test_
/// __test__
/// __***test***__
/// ___test___
/// # test
/// ## test
/// ### test
/// #### test
/// ##### test
/// ###### test
/// ####### test
/// # test **test**
/// # test _test_
/// [text]()
/// [test](http://test.com)
/// [test](#test)
///
/// [test]
/// [test]: http://test.com
/// `test code`
/// ```rust
/// test code block
/// ```
/// test
///
///
/// # Test
///
/// ```
/// assert!(true);
/// ```
///
fn test(&self) {
asdf
// test
asdf
}
/**
* Deprecated
*/
/*!
* Deprecated
*/
text /**/ text
text /***/ text
text /****/ text
text
text // line comment
text /// line doc comment
text //! line doc comment
text
text #![main] text
text #![allow(great_algorithms)] text
text #![!resolve_unexported] text
text #[deny(silly_comments)] text
#[doc = "This attribute contains ] an attribute ending character"]
text r"This is a raw string" text
text r"This raw string ends in \" text
text r#"This is also valid"# text
text r##"This is ##"# also valid."## text
text r#"This is #"## not valid."# text //"
text b"This is a bytestring" text
text br"And a raw byte string" text
text rb"Invalid raw byte string" text
text br##"This is ##"# also valid."## text
text r##"Raw strings can
span multiple lines"## text
text "double-quote string" text
text "string\nwith\x20escaped\"characters" text
text "string with // comment /* inside" text
text "strings can
span multiple lines" text
text 'c' text
text 'cc' text
text '\n' text
text '\nf' text
text '\n\n' text
text '\x20' text
text '\'' text
text '\\' text
text b'b' text
text b'bb' text
text b'\x20' text
text 42i32 text
text 42is text
text 42int text
text 42f32 text
text 42e+18 text
text 42.1415 text
text 42.1415f32 text
text 42.1415e18 text
text 42.1415e+18 text
text 42.1415e-18f64 text
text 42 text
text 0xf00b text
text 0o755 text
text 0b101010 text
text bool text char text usize text isize text
text u8 text u16 text u32 text u64 text
text i8 text i16 text i32 text i64 text
text Self text
text str text &str text String text &String text
text true text false text
text break text continue text do text else text
text if text in text for text loop text
text match text return text while text
text as text crate text extern text mod text
text let text proc text ref text
text
extern crate foo;
text
use std::slice;
text
use std::{num, str};
text
use self::foo::{bar, baz};
text
use super::foo::{bar, baz};
text
x = 1+1;
y = 4-2;
x *= 3;
y++;
y += 1;
text
pub enum MyEnum {
One,
Two
}
text
pub struct MyStruct<'foo> {
pub one: u32,
two: Option<'a, MyEnum>,
three: &'foo i32,
}
text
pub struct MyTupleStruct(pub i32, u32);
text
text
type MyType = u32;
text
text
static MY_CONSTANT: &str = "hello";
text
text
pub trait MyTrait {
text
fn create_something (param: &str, mut other_param: u32) -> Option<Self>;
text
fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U>;
text
fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool;
text
fn do_even_more<'a, T: Send+Whatever, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U;
text
}
text
text
impl<'foo> MyTrait for MyStruct<'foo> {
text
fn create_something (param: &str, mut other_param: u32) -> Option<Self> {
text
return Some(cake);
text
}
text
fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U> |
text
fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool {
announce!("There's no cake");
if!test_subject.under_control() {
text
let list: Vec<item> = some_iterator.map(|elem| elem.dosomething()).collect();
text
let boxed_list = box list;
text
self.announce_warning();
text
if test_subject.ignored_warnings > 3 {
text
test_subject.incinerate();
text
}
text
}
text
}
text
fn do_even_more<'a, T: Send+Whatever+'static, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U {
text
let foo: Option<'a u32> = Some(18);
text
if self.one < 1 {
text
self.complain(&foo);
text
}
}
text
}
text
text
impl MyStruct<'foo> {
text
pub fn with_something<T: Send> (param: &T, f: |i32, &str| -> T, other_param: u32) -> T {
text
f(123, "hello")
text
}
text
}
text
// Loop expression labels (#2)
'infinity: loop {
do_serious_stuff();
use_a_letter('Z');
break 'infinity;
}
// isize/usize suffixes (#22)
let x = 123usize;
// Float literals without +- after E (#30)
let x = 1.2345e6;
// Nested generic (#33, #37)
let x: Vec<Vec<u8>> = Vec::new();
// Correct detection of == (#40)
struct Foo { x: i32 }
if x == 1 { }
// const function parameter (#52)
fn foo(bar: *const i32) {
let _ = 1234 as *const u32;
}
// Keywords and known types in wrapper structs (#56)
pub struct Foobar(pub Option<bool>);
pub struct Foobar(pub Test<W=bool>);
pub struct Foobar(pub Test<W==bool>);
pub struct Foobar(pub Test<W = bool>);
struct Test(i32);
struct Test(String);
struct Test(Vec<i32>);
struct Test(BTreeMap<String, i32>);
// Lifetimes in associated type definitions
trait Foo {
type B: A +'static;
}
// where clause
impl Foo<A, B> where text { }
text
impl Foo<A, B> for C where text { }
text
impl Foo<A, B> for C {
fn foo<A, B> -> C where text { }
}
text
fn foo<A, B> -> C where text { }
text
struct Foo<A, B> where text { }
text
trait Foo<A, B> : C where { }
text
fn do_work<T: Any + Debug>(value: &T) {}
impl Cookie {}
impl<T> PrintInOption for T where Option<T>: Debug {}
impl<K,V> HashMap<K, V> where K : Hash + Eq {}
impl<A, D> MyTrait<A, D> for YourType where A: TraitB + TraitC, D: TraitE + TraitF {}
impl Debug for a where asdf {}
impl<Flavor> Eat where Cookie<Flavor>: Oatmeal {}
// Unsafe in function arguments
unsafe fn foo();
fn foo(f: unsafe fn());
// Format macros
format!("text");
format!("text{}text", 1);
format!("text{0}text", 1);
format!("text{named}text", named=1);
format!("text{:?}text", to_debug);
format!("text{0:?}text", to_debug);
format!("text{named:?}text", named=to_debug);
format!("text{:<}text", 1);
format!("text{:.>}text", 1);
format!("text{:+}text", pos_or_neg);
format!("text{:+0}text", pos_or_neg);
format!("text{:+04}text", pos_or_neg);
format!("text{:6}", "text");
format!("text{:1$}", "text", 6);
format!("text{1:6$}", 6, "text");
format!("text{:w$}", "text", w=6);
format!("text{:8b}text", byte);
format!("text{:08b}text", byte);
format!("text{:#010b}text", byte);
format!("text{:2x}text", byte);
format!("text{:#4x}text", byte);
format!("text{:.2}text", 0.5);
format!("text{:0.2}text", 0.5);
format!("text{:06.2}text", 0.5);
format!("text{named:.prec$}text", prec=0.5, named=2.0);
format!("text{}text{2:.*}text", "text", 6, 0.5);
format!("text{named:-^+#06.2e}text", named=0.5);
format!("text{named:-^+#0width$.prec$e}text", named=0.5, width=6, prec=2);
format!("text{{escaped}}text\n{0}text", "only {text} first {{text}}");
not_format!("text{}text");
format_args!("{}", "text");
write!("{}", "text");
writeln!("{}", "text");
print!("{}", "text");
println!("{}", "text");
log!("{}", "text");
error!("{}", "text");
warn!("{}", "text");
info!("{}", "text");
debug!("{}", "text");
trace!("{}", "text");
eprint!("{}", "text");
eprintln!("{}", "text");
// Unused reserved words
abstract fn do_thing();
final let MAX = 10us;
let i = 0;
do {
yield do_thing(i++);
} while(i < MAX);
impl Float for f32 {
fn infinity() -> Self {
f32::INFINITY
}
}
#[derive(Default)]
enum State {
/// Currently open in a sane state
Open,
/// Waiting to send a GO_AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO_AWAY_ frame
GoAway(frame::GoAway)
/// Waiting to send a GO*AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO*AWAY* frame
GoAway(frame::GoAway)
/// Waiting to send a GO__AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO__AWAY__ frame
GoAway(frame::GoAway)
/// Waiting to send a GO**AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO**AWAY** frame
GoAway(frame::GoAway)
}
Box<dyn MyTrait>
&dyn Foo
&mut dyn Foo
| {
assert!(1 != 2);
text
self.with_something(param, |arg1, arg2| {
text
}, other_param);
} | identifier_body |
test.rs | text
/* this is a
/* nested
block */ comment.
And should stay a comment
even with "strings"
or 42 0x18 0b01011 // blah
or u32 as i16 if impl */
text
/** this is a
/*! nested
block */ doc comment */
text
/// test
/// *test*
/// **test**
/// ***test***
/// _test_
/// __test__
/// __***test***__
/// ___test___
/// # test
/// ## test
/// ### test
/// #### test
/// ##### test
/// ###### test
/// ####### test
/// # test **test**
/// # test _test_
/// [text]()
/// [test](http://test.com)
/// [test](#test)
///
/// [test]
/// [test]: http://test.com
/// `test code`
/// ```rust
/// test code block
/// ```
/// test
///
///
/// # Test
///
/// ```
/// assert!(true);
/// ```
///
fn test(&self) {
asdf
// test
asdf
}
/**
* Deprecated
*/
/*!
* Deprecated
*/
text /**/ text
text /***/ text
text /****/ text
text
text // line comment
text /// line doc comment
text //! line doc comment
text
text #![main] text
text #![allow(great_algorithms)] text
text #![!resolve_unexported] text
text #[deny(silly_comments)] text
#[doc = "This attribute contains ] an attribute ending character"]
text r"This is a raw string" text
text r"This raw string ends in \" text
text r#"This is also valid"# text
text r##"This is ##"# also valid."## text
text r#"This is #"## not valid."# text //"
text b"This is a bytestring" text
text br"And a raw byte string" text
text rb"Invalid raw byte string" text
text br##"This is ##"# also valid."## text
text r##"Raw strings can
span multiple lines"## text
text "double-quote string" text
text "string\nwith\x20escaped\"characters" text
text "string with // comment /* inside" text
text "strings can
span multiple lines" text
text 'c' text
text 'cc' text
text '\n' text
text '\nf' text
text '\n\n' text
text '\x20' text
text '\'' text
text '\\' text
text b'b' text
text b'bb' text
text b'\x20' text
text 42i32 text
text 42is text
text 42int text
text 42f32 text
text 42e+18 text
text 42.1415 text
text 42.1415f32 text
text 42.1415e18 text
text 42.1415e+18 text
text 42.1415e-18f64 text
text 42 text
text 0xf00b text
text 0o755 text
text 0b101010 text
text bool text char text usize text isize text
text u8 text u16 text u32 text u64 text
text i8 text i16 text i32 text i64 text
text Self text
text str text &str text String text &String text
text true text false text
text break text continue text do text else text
text if text in text for text loop text
text match text return text while text
text as text crate text extern text mod text
text let text proc text ref text
text
extern crate foo;
text
use std::slice;
text
use std::{num, str};
text
use self::foo::{bar, baz};
text
use super::foo::{bar, baz};
text
x = 1+1;
y = 4-2;
x *= 3;
y++;
y += 1;
text
pub enum MyEnum {
One,
Two
}
text
pub struct MyStruct<'foo> {
pub one: u32,
two: Option<'a, MyEnum>,
three: &'foo i32,
}
text
pub struct MyTupleStruct(pub i32, u32);
text
text
type MyType = u32;
text
text
static MY_CONSTANT: &str = "hello";
text
text
pub trait MyTrait {
text
fn create_something (param: &str, mut other_param: u32) -> Option<Self>;
text
fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U>;
text
fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool;
text
fn do_even_more<'a, T: Send+Whatever, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U;
text
}
text
text
impl<'foo> MyTrait for MyStruct<'foo> {
text
fn create_something (param: &str, mut other_param: u32) -> Option<Self> {
text
return Some(cake);
text
}
text
fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U> {
assert!(1!= 2);
text
self.with_something(param, |arg1, arg2| {
text
}, other_param);
}
text
fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool {
announce!("There's no cake");
if!test_subject.under_control() {
text
let list: Vec<item> = some_iterator.map(|elem| elem.dosomething()).collect();
text
let boxed_list = box list;
text
self.announce_warning();
text
if test_subject.ignored_warnings > 3 {
text
test_subject.incinerate();
text
}
text
}
text
}
text
fn do_even_more<'a, T: Send+Whatever+'static, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U {
text
let foo: Option<'a u32> = Some(18);
text
if self.one < 1 {
text
self.complain(&foo);
text
}
}
text
}
text
text
impl MyStruct<'foo> {
text
pub fn with_something<T: Send> (param: &T, f: |i32, &str| -> T, other_param: u32) -> T {
text
f(123, "hello")
text
}
text
}
text
// Loop expression labels (#2)
'infinity: loop {
do_serious_stuff();
use_a_letter('Z');
break 'infinity;
}
// isize/usize suffixes (#22)
let x = 123usize;
// Float literals without +- after E (#30)
let x = 1.2345e6;
// Nested generic (#33, #37)
let x: Vec<Vec<u8>> = Vec::new();
// Correct detection of == (#40)
struct Foo { x: i32 }
if x == 1 |
// const function parameter (#52)
fn foo(bar: *const i32) {
let _ = 1234 as *const u32;
}
// Keywords and known types in wrapper structs (#56)
pub struct Foobar(pub Option<bool>);
pub struct Foobar(pub Test<W=bool>);
pub struct Foobar(pub Test<W==bool>);
pub struct Foobar(pub Test<W = bool>);
struct Test(i32);
struct Test(String);
struct Test(Vec<i32>);
struct Test(BTreeMap<String, i32>);
// Lifetimes in associated type definitions
trait Foo {
type B: A +'static;
}
// where clause
impl Foo<A, B> where text { }
text
impl Foo<A, B> for C where text { }
text
impl Foo<A, B> for C {
fn foo<A, B> -> C where text { }
}
text
fn foo<A, B> -> C where text { }
text
struct Foo<A, B> where text { }
text
trait Foo<A, B> : C where { }
text
fn do_work<T: Any + Debug>(value: &T) {}
impl Cookie {}
impl<T> PrintInOption for T where Option<T>: Debug {}
impl<K,V> HashMap<K, V> where K : Hash + Eq {}
impl<A, D> MyTrait<A, D> for YourType where A: TraitB + TraitC, D: TraitE + TraitF {}
impl Debug for a where asdf {}
impl<Flavor> Eat where Cookie<Flavor>: Oatmeal {}
// Unsafe in function arguments
unsafe fn foo();
fn foo(f: unsafe fn());
// Format macros
format!("text");
format!("text{}text", 1);
format!("text{0}text", 1);
format!("text{named}text", named=1);
format!("text{:?}text", to_debug);
format!("text{0:?}text", to_debug);
format!("text{named:?}text", named=to_debug);
format!("text{:<}text", 1);
format!("text{:.>}text", 1);
format!("text{:+}text", pos_or_neg);
format!("text{:+0}text", pos_or_neg);
format!("text{:+04}text", pos_or_neg);
format!("text{:6}", "text");
format!("text{:1$}", "text", 6);
format!("text{1:6$}", 6, "text");
format!("text{:w$}", "text", w=6);
format!("text{:8b}text", byte);
format!("text{:08b}text", byte);
format!("text{:#010b}text", byte);
format!("text{:2x}text", byte);
format!("text{:#4x}text", byte);
format!("text{:.2}text", 0.5);
format!("text{:0.2}text", 0.5);
format!("text{:06.2}text", 0.5);
format!("text{named:.prec$}text", prec=0.5, named=2.0);
format!("text{}text{2:.*}text", "text", 6, 0.5);
format!("text{named:-^+#06.2e}text", named=0.5);
format!("text{named:-^+#0width$.prec$e}text", named=0.5, width=6, prec=2);
format!("text{{escaped}}text\n{0}text", "only {text} first {{text}}");
not_format!("text{}text");
format_args!("{}", "text");
write!("{}", "text");
writeln!("{}", "text");
print!("{}", "text");
println!("{}", "text");
log!("{}", "text");
error!("{}", "text");
warn!("{}", "text");
info!("{}", "text");
debug!("{}", "text");
trace!("{}", "text");
eprint!("{}", "text");
eprintln!("{}", "text");
// Unused reserved words
abstract fn do_thing();
final let MAX = 10us;
let i = 0;
do {
yield do_thing(i++);
} while(i < MAX);
impl Float for f32 {
fn infinity() -> Self {
f32::INFINITY
}
}
#[derive(Default)]
enum State {
/// Currently open in a sane state
Open,
/// Waiting to send a GO_AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO_AWAY_ frame
GoAway(frame::GoAway)
/// Waiting to send a GO*AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO*AWAY* frame
GoAway(frame::GoAway)
/// Waiting to send a GO__AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO__AWAY__ frame
GoAway(frame::GoAway)
/// Waiting to send a GO**AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO**AWAY** frame
GoAway(frame::GoAway)
}
Box<dyn MyTrait>
&dyn Foo
&mut dyn Foo
| { } | conditional_block |
test.rs | text
/* this is a
/* nested
block */ comment.
And should stay a comment
even with "strings"
or 42 0x18 0b01011 // blah
or u32 as i16 if impl */
text
/** this is a
/*! nested
block */ doc comment */
text
/// test
/// *test*
/// **test**
/// ***test***
/// _test_
/// __test__
/// __***test***__
/// ___test___
/// # test
/// ## test
/// ### test
/// #### test
/// ##### test
/// ###### test
/// ####### test
/// # test **test**
/// # test _test_
/// [text]()
/// [test](http://test.com)
/// [test](#test)
///
/// [test]
/// [test]: http://test.com
/// `test code`
/// ```rust
/// test code block
/// ```
/// test
///
///
/// # Test
///
/// ```
/// assert!(true);
/// ```
///
fn test(&self) {
asdf
// test
asdf
}
/**
* Deprecated
*/
/*!
* Deprecated
*/
text /**/ text
text /***/ text
text /****/ text
text
text // line comment
text /// line doc comment
text //! line doc comment
text
text #![main] text
text #![allow(great_algorithms)] text
text #![!resolve_unexported] text
text #[deny(silly_comments)] text
#[doc = "This attribute contains ] an attribute ending character"]
text r"This is a raw string" text
text r"This raw string ends in \" text
text r#"This is also valid"# text
text r##"This is ##"# also valid."## text
text r#"This is #"## not valid."# text //"
text b"This is a bytestring" text
text br"And a raw byte string" text
text rb"Invalid raw byte string" text
text br##"This is ##"# also valid."## text
text r##"Raw strings can
span multiple lines"## text
text "double-quote string" text
text "string\nwith\x20escaped\"characters" text
text "string with // comment /* inside" text
text "strings can
span multiple lines" text
text 'c' text
text 'cc' text
text '\n' text
text '\nf' text
text '\n\n' text
text '\x20' text
text '\'' text
text '\\' text
text b'b' text
text b'bb' text
text b'\x20' text
text 42i32 text
text 42is text
text 42int text
text 42f32 text
text 42e+18 text
text 42.1415 text
text 42.1415f32 text
text 42.1415e18 text
text 42.1415e+18 text
text 42.1415e-18f64 text
text 42 text
text 0xf00b text
text 0o755 text
text 0b101010 text
text bool text char text usize text isize text
text u8 text u16 text u32 text u64 text
text i8 text i16 text i32 text i64 text
text Self text
text str text &str text String text &String text
text true text false text
text break text continue text do text else text
text if text in text for text loop text
text match text return text while text
text as text crate text extern text mod text
text let text proc text ref text
text
extern crate foo;
text
use std::slice;
text
use std::{num, str};
text
use self::foo::{bar, baz};
text
use super::foo::{bar, baz};
text
x = 1+1;
y = 4-2;
x *= 3;
y++;
y += 1;
text
pub enum MyEnum {
One,
Two
}
text
pub struct MyStruct<'foo> {
pub one: u32,
two: Option<'a, MyEnum>,
three: &'foo i32,
}
text
pub struct MyTupleStruct(pub i32, u32);
text
text
type MyType = u32;
text
text
static MY_CONSTANT: &str = "hello";
text
text
pub trait MyTrait {
text
fn create_something (param: &str, mut other_param: u32) -> Option<Self>;
text
fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U>;
text
fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool;
text
fn do_even_more<'a, T: Send+Whatever, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U;
text
}
text
text
impl<'foo> MyTrait for MyStruct<'foo> {
text
fn create_something (param: &str, mut other_param: u32) -> Option<Self> {
text
return Some(cake);
text
}
text
fn do_whatever<T: Send+Share+Whatever, U: Freeze> (param: &T, other_param: u32) -> Option<U> {
assert!(1!= 2);
text
self.with_something(param, |arg1, arg2| {
text
}, other_param);
}
text
fn do_all_the_work (&mut self, param: &str, mut other_param: u32) -> bool {
announce!("There's no cake");
if!test_subject.under_control() {
text
let list: Vec<item> = some_iterator.map(|elem| elem.dosomething()).collect();
text
let boxed_list = box list;
text
self.announce_warning();
text
if test_subject.ignored_warnings > 3 {
text
test_subject.incinerate();
text
}
text
}
text
}
text
fn do_even_more<'a, T: Send+Whatever+'static, U: Something<T>+Freeze> (&'a mut self, param: &T) -> &'a U {
text
let foo: Option<'a u32> = Some(18);
text
if self.one < 1 {
text
self.complain(&foo);
text
}
}
text
}
text
text
impl MyStruct<'foo> {
text
pub fn with_something<T: Send> (param: &T, f: |i32, &str| -> T, other_param: u32) -> T {
text
f(123, "hello")
text
}
text
}
text
// Loop expression labels (#2)
'infinity: loop {
do_serious_stuff();
use_a_letter('Z');
break 'infinity;
}
// isize/usize suffixes (#22)
let x = 123usize;
// Float literals without +- after E (#30)
let x = 1.2345e6;
// Nested generic (#33, #37)
let x: Vec<Vec<u8>> = Vec::new();
// Correct detection of == (#40)
struct Foo { x: i32 }
if x == 1 { }
// const function parameter (#52)
fn foo(bar: *const i32) {
let _ = 1234 as *const u32;
}
// Keywords and known types in wrapper structs (#56)
pub struct Foobar(pub Option<bool>);
pub struct | (pub Test<W=bool>);
pub struct Foobar(pub Test<W==bool>);
pub struct Foobar(pub Test<W = bool>);
struct Test(i32);
struct Test(String);
struct Test(Vec<i32>);
struct Test(BTreeMap<String, i32>);
// Lifetimes in associated type definitions
trait Foo {
type B: A +'static;
}
// where clause
impl Foo<A, B> where text { }
text
impl Foo<A, B> for C where text { }
text
impl Foo<A, B> for C {
fn foo<A, B> -> C where text { }
}
text
fn foo<A, B> -> C where text { }
text
struct Foo<A, B> where text { }
text
trait Foo<A, B> : C where { }
text
fn do_work<T: Any + Debug>(value: &T) {}
impl Cookie {}
impl<T> PrintInOption for T where Option<T>: Debug {}
impl<K,V> HashMap<K, V> where K : Hash + Eq {}
impl<A, D> MyTrait<A, D> for YourType where A: TraitB + TraitC, D: TraitE + TraitF {}
impl Debug for a where asdf {}
impl<Flavor> Eat where Cookie<Flavor>: Oatmeal {}
// Unsafe in function arguments
unsafe fn foo();
fn foo(f: unsafe fn());
// Format macros
format!("text");
format!("text{}text", 1);
format!("text{0}text", 1);
format!("text{named}text", named=1);
format!("text{:?}text", to_debug);
format!("text{0:?}text", to_debug);
format!("text{named:?}text", named=to_debug);
format!("text{:<}text", 1);
format!("text{:.>}text", 1);
format!("text{:+}text", pos_or_neg);
format!("text{:+0}text", pos_or_neg);
format!("text{:+04}text", pos_or_neg);
format!("text{:6}", "text");
format!("text{:1$}", "text", 6);
format!("text{1:6$}", 6, "text");
format!("text{:w$}", "text", w=6);
format!("text{:8b}text", byte);
format!("text{:08b}text", byte);
format!("text{:#010b}text", byte);
format!("text{:2x}text", byte);
format!("text{:#4x}text", byte);
format!("text{:.2}text", 0.5);
format!("text{:0.2}text", 0.5);
format!("text{:06.2}text", 0.5);
format!("text{named:.prec$}text", prec=0.5, named=2.0);
format!("text{}text{2:.*}text", "text", 6, 0.5);
format!("text{named:-^+#06.2e}text", named=0.5);
format!("text{named:-^+#0width$.prec$e}text", named=0.5, width=6, prec=2);
format!("text{{escaped}}text\n{0}text", "only {text} first {{text}}");
not_format!("text{}text");
format_args!("{}", "text");
write!("{}", "text");
writeln!("{}", "text");
print!("{}", "text");
println!("{}", "text");
log!("{}", "text");
error!("{}", "text");
warn!("{}", "text");
info!("{}", "text");
debug!("{}", "text");
trace!("{}", "text");
eprint!("{}", "text");
eprintln!("{}", "text");
// Unused reserved words
abstract fn do_thing();
final let MAX = 10us;
let i = 0;
do {
yield do_thing(i++);
} while(i < MAX);
impl Float for f32 {
fn infinity() -> Self {
f32::INFINITY
}
}
#[derive(Default)]
enum State {
/// Currently open in a sane state
Open,
/// Waiting to send a GO_AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO_AWAY_ frame
GoAway(frame::GoAway)
/// Waiting to send a GO*AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO*AWAY* frame
GoAway(frame::GoAway)
/// Waiting to send a GO__AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO__AWAY__ frame
GoAway(frame::GoAway)
/// Waiting to send a GO**AWAY frame
GoAway(frame::GoAway)
/// Waiting to send a GO**AWAY** frame
GoAway(frame::GoAway)
}
Box<dyn MyTrait>
&dyn Foo
&mut dyn Foo
| Foobar | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.