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
socks4.rs
//! Socks4a Protocol Definition //! //! <http://ftp.icm.edu.pl/packages/socks/socks4/SOCKS4.protocol> #![allow(dead_code)] use std::{ fmt, io::{self, ErrorKind}, net::{Ipv4Addr, SocketAddr, SocketAddrV4}, }; use byteorder::{BigEndian, ByteOrder}; use bytes::{BufMut, BytesMut}; use thiserror::Error; use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use shadowsocks::relay::socks5; #[rustfmt::skip] mod consts { pub const SOCKS4_VERSION: u8 = 4; pub const SOCKS4_COMMAND_CONNECT: u8 = 1; pub const SOCKS4_COMMAND_BIND: u8 = 2; pub const SOCKS4_RESULT_REQUEST_GRANTED: u8 = 90; pub const SOCKS4_RESULT_REQUEST_REJECTED_OR_FAILED: u8 = 91; pub const SOCKS4_RESULT_REQUEST_REJECTED_CANNOT_CONNECT: u8 = 92; pub const SOCKS4_RESULT_REQUEST_REJECTED_DIFFERENT_USER_ID: u8 = 93; } /// SOCKS4 Command #[derive(Clone, Debug, Copy)] pub enum Command { /// CONNECT command Connect, /// BIND command Bind, } impl Command { #[inline] fn as_u8(self) -> u8 { match self { Command::Connect => consts::SOCKS4_COMMAND_CONNECT, Command::Bind => consts::SOCKS4_COMMAND_BIND, } } #[inline] fn from_u8(code: u8) -> Option<Command> { match code { consts::SOCKS4_COMMAND_CONNECT => Some(Command::Connect), consts::SOCKS4_COMMAND_BIND => Some(Command::Bind), _ => None, } } } /// SOCKS4 Result Code #[derive(Clone, Debug, Copy, Eq, PartialEq)] pub enum ResultCode { /// 90: request granted RequestGranted, /// 91: request rejected or failed RequestRejectedOrFailed, /// 92: request rejected because SOCKS server cannot connect to identd on the client RequestRejectedCannotConnect, /// 93: request rejected because the client program and identd report different user-ids RequestRejectedDifferentUserId, /// Other replies Other(u8), } impl ResultCode { #[inline] fn as_u8(self) -> u8 { match self { ResultCode::RequestGranted => consts::SOCKS4_RESULT_REQUEST_GRANTED, ResultCode::RequestRejectedOrFailed => consts::SOCKS4_RESULT_REQUEST_REJECTED_OR_FAILED, ResultCode::RequestRejectedCannotConnect => consts::SOCKS4_RESULT_REQUEST_REJECTED_CANNOT_CONNECT, ResultCode::RequestRejectedDifferentUserId => consts::SOCKS4_RESULT_REQUEST_REJECTED_DIFFERENT_USER_ID, ResultCode::Other(c) => c, } } #[inline] fn from_u8(code: u8) -> ResultCode { match code { consts::SOCKS4_RESULT_REQUEST_GRANTED => ResultCode::RequestGranted, consts::SOCKS4_RESULT_REQUEST_REJECTED_OR_FAILED => ResultCode::RequestRejectedOrFailed, consts::SOCKS4_RESULT_REQUEST_REJECTED_CANNOT_CONNECT => ResultCode::RequestRejectedCannotConnect, consts::SOCKS4_RESULT_REQUEST_REJECTED_DIFFERENT_USER_ID => ResultCode::RequestRejectedDifferentUserId, code => ResultCode::Other(code), } } } impl fmt::Display for ResultCode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { ResultCode::RequestGranted => f.write_str("request granted"), ResultCode::RequestRejectedOrFailed => f.write_str("request rejected or failed"), ResultCode::RequestRejectedCannotConnect => { f.write_str("request rejected because SOCKS server cannot connect to identd on the client") } ResultCode::RequestRejectedDifferentUserId => { f.write_str("request rejected because the client program and identd report different user-ids") } ResultCode::Other(code) => write!(f, "other result code {}", code), } } } /// SOCKS4 Address type #[derive(Clone, PartialEq, Eq, Hash)] pub enum Address { /// Socket address (IP Address) SocketAddress(SocketAddrV4), /// Domain name address (SOCKS4a) DomainNameAddress(String, u16), } impl fmt::Debug for Address { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Address::SocketAddress(ref addr) => write!(f, "{}", addr), Address::DomainNameAddress(ref addr, ref port) => write!(f, "{}:{}", addr, port), } } } impl fmt::Display for Address { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Address::SocketAddress(ref addr) => write!(f, "{}", addr), Address::DomainNameAddress(ref addr, ref port) => write!(f, "{}:{}", addr, port), } } } impl From<SocketAddrV4> for Address { fn from(s: SocketAddrV4) -> Address { Address::SocketAddress(s) } } impl From<(String, u16)> for Address { fn from((dn, port): (String, u16)) -> Address { Address::DomainNameAddress(dn, port) } } impl From<(&str, u16)> for Address { fn from((dn, port): (&str, u16)) -> Address { Address::DomainNameAddress(dn.to_owned(), port) } } impl From<&Address> for Address { fn from(addr: &Address) -> Address { addr.clone() } } impl From<Address> for socks5::Address { fn from(addr: Address) -> socks5::Address { match addr { Address::SocketAddress(a) => socks5::Address::SocketAddress(SocketAddr::V4(a)), Address::DomainNameAddress(d, p) => socks5::Address::DomainNameAddress(d, p), } } } /// Handshake Request /// /// ```plain /// The client connects to the SOCKS server and sends a CONNECT/BIND request when /// it wants to establish a connection to an application server. The client /// includes in the request packet the IP address and the port number of the /// destination host, and userid, in the following format. /// /// +----+----+----+----+----+----+----+----+----+----+....+----+ /// | VN | CD | DSTPORT | DSTIP | USERID |NULL| /// +----+----+----+----+----+----+----+----+----+----+....+----+ /// # of bytes: 1 1 2 4 variable 1 /// /// VN is the SOCKS protocol version number and should be 4. CD is the /// SOCKS command code and should be 1 for CONNECT request, 2 for BIND request. NULL is a byte /// of all zero bits. /// ``` #[derive(Debug, Clone)] pub struct HandshakeRequest { pub cd: Command, pub dst: Address, pub user_id: Vec<u8>, } impl HandshakeRequest { /// Read from a reader pub async fn read_from<R>(r: &mut R) -> Result<HandshakeRequest, Error> where R: AsyncBufRead + Unpin, { let mut buf = [0u8; 8]; let _ = r.read_exact(&mut buf).await?; let vn = buf[0]; if vn!= consts::SOCKS4_VERSION { return Err(Error::UnsupportedSocksVersion(vn)); } let cd = buf[1]; let command = match Command::from_u8(cd) { Some(c) => c, None => { return Err(Error::UnsupportedSocksVersion(cd)); } }; let port = BigEndian::read_u16(&buf[2..4]); let mut user_id = Vec::new(); let _ = r.read_until(b'\0', &mut user_id).await?; if user_id.is_empty() || user_id.last()!= Some(&b'\0') { return Err(io::Error::from(ErrorKind::UnexpectedEof).into()); } user_id.pop(); // Pops the last b'\0' let dst = if buf[4] == 0x00 && buf[5] == 0x00 && buf[6] == 0x00 && buf[7]!= 0x00 { // SOCKS4a, indicates that it is a HOST address let mut host = Vec::new(); let _ = r.read_until(b'\0', &mut host).await?; if host.is_empty() || host.last()!= Some(&b'\0') { return Err(io::Error::from(ErrorKind::UnexpectedEof).into()); } host.pop(); // Pops the last b'\0' match String::from_utf8(host) { Ok(host) => Address::DomainNameAddress(host, port), Err(..) => { return Err(Error::AddressHostInvalidEncoding); } } } else { let ip = Ipv4Addr::new(buf[4], buf[5], buf[6], buf[7]); Address::SocketAddress(SocketAddrV4::new(ip, port)) }; Ok(HandshakeRequest { cd: command, dst, user_id, }) } /// Writes to writer pub async fn write_to<W>(&self, w: &mut W) -> io::Result<()> where W: AsyncWrite + Unpin, { let mut buf = BytesMut::with_capacity(self.serialized_len()); self.write_to_buf(&mut buf); w.write_all(&buf).await } /// Writes to buffer pub fn write_to_buf<B: BufMut>(&self, buf: &mut B) { debug_assert!( !self.user_id.contains(&b'\0'), "USERID shouldn't contain any NULL characters" ); buf.put_u8(consts::SOCKS4_VERSION); buf.put_u8(self.cd.as_u8()); match self.dst { Address::SocketAddress(ref saddr) => { let port = saddr.port(); buf.put_u16(port); buf.put_slice(&saddr.ip().octets()); buf.put_slice(&self.user_id); buf.put_u8(b'\0'); } Address::DomainNameAddress(ref dname, port) => { buf.put_u16(port); // 0.0.0.x (x!= 0) const PLACEHOLDER: [u8; 4] = [0x00, 0x00, 0x00, 0xff]; buf.put_slice(&PLACEHOLDER); buf.put_slice(&self.user_id); buf.put_u8(b'\0'); buf.put_slice(dname.as_bytes()); buf.put_u8(b'\0'); } } } /// Length in bytes #[inline] pub fn serialized_len(&self) -> usize { let mut s = 1 + 1 + 2 + 4 + self.user_id.len() + 1; // USERID.LEN + NULL if let Address::DomainNameAddress(ref dname, _) = self.dst { s += dname.len() + 1; } s } } /// Handshake Response /// /// ```plain /// +----+----+----+----+----+----+----+----+ /// | VN | CD | DSTPORT | DSTIP | /// +----+----+----+----+----+----+----+----+ /// # of bytes: 1 1 2 4 /// ``` #[derive(Debug, Clone)] pub struct HandshakeResponse { pub cd: ResultCode, } impl HandshakeResponse { /// Create a response with code pub fn new(code: ResultCode) -> HandshakeResponse { HandshakeResponse { cd: code } } /// Read from a reader pub async fn read_from<R>(r: &mut R) -> Result<HandshakeResponse, Error> where R: AsyncRead + Unpin, { let mut buf = [0u8; 8]; let _ = r.read_exact(&mut buf).await?; let vn = buf[0]; if vn!= 0 { return Err(Error::UnsupportedSocksVersion(vn)); } let cd = buf[1]; let result_code = ResultCode::from_u8(cd); // DSTPORT, DSTIP are ignored Ok(HandshakeResponse { cd: result_code }) } /// Write data into a writer pub async fn write_to<W>(&self, w: &mut W) -> io::Result<()> where W: AsyncWrite + Unpin, { let mut buf = BytesMut::with_capacity(self.serialized_len()); self.write_to_buf(&mut buf);
} /// Writes to buffer pub fn write_to_buf<B: BufMut>(&self, buf: &mut B) { let HandshakeResponse { ref cd } = *self; buf.put_slice(&[ // VN: Result Code's version, must be 0 0x00, // CD: Result Code cd.as_u8(), // DSTPORT: Ignored 0x00, 0x00, // DSTIP: Ignored 0x00, 0x00, 0x00, 0x00, ]); } /// Length in bytes #[inline] pub fn serialized_len(&self) -> usize { 1 + 1 + 2 + 4 } } /// SOCKS 4/4a Error #[derive(Error, Debug)] pub enum Error { // I/O Error #[error("{0}")] IoError(#[from] io::Error), #[error("host must be UTF-8 encoding")] AddressHostInvalidEncoding, #[error("unsupported socks version {0:#x}")] UnsupportedSocksVersion(u8), #[error("unsupported command {0:#x}")] UnsupportedCommand(u8), #[error("{0}")] Result(ResultCode), } impl From<Error> for io::Error { fn from(err: Error) -> io::Error { match err { Error::IoError(err) => err, e => io::Error::new(ErrorKind::Other, e), } } }
w.write_all(&buf).await
random_line_split
text_mark.rs
// This file was generated by gir (5c017c9) from gir-files (71d73f0) // DO NOT EDIT use TextBuffer; use ffi; use glib::object::IsA; use glib::translate::*; glib_wrapper! { pub struct TextMark(Object<ffi::GtkTextMark>); match fn { get_type => || ffi::gtk_text_mark_get_type(), } } impl TextMark { pub fn new<'a, P: Into<Option<&'a str>>>(name: P, left_gravity: bool) -> TextMark { assert_initialized_main_thread!(); let name = name.into(); let name = name.to_glib_none(); unsafe { from_glib_full(ffi::gtk_text_mark_new(name.0, left_gravity.to_glib())) } } } pub trait TextMarkExt { fn get_buffer(&self) -> Option<TextBuffer>; fn get_deleted(&self) -> bool; fn get_left_gravity(&self) -> bool; fn get_name(&self) -> Option<String>; fn get_visible(&self) -> bool; fn set_visible(&self, setting: bool); } impl<O: IsA<TextMark>> TextMarkExt for O { fn get_buffer(&self) -> Option<TextBuffer> { unsafe { from_glib_none(ffi::gtk_text_mark_get_buffer(self.to_glib_none().0)) } } fn get_deleted(&self) -> bool { unsafe { from_glib(ffi::gtk_text_mark_get_deleted(self.to_glib_none().0)) } } fn get_left_gravity(&self) -> bool { unsafe { from_glib(ffi::gtk_text_mark_get_left_gravity(self.to_glib_none().0)) } } fn
(&self) -> Option<String> { unsafe { from_glib_none(ffi::gtk_text_mark_get_name(self.to_glib_none().0)) } } fn get_visible(&self) -> bool { unsafe { from_glib(ffi::gtk_text_mark_get_visible(self.to_glib_none().0)) } } fn set_visible(&self, setting: bool) { unsafe { ffi::gtk_text_mark_set_visible(self.to_glib_none().0, setting.to_glib()); } } }
get_name
identifier_name
text_mark.rs
// This file was generated by gir (5c017c9) from gir-files (71d73f0) // DO NOT EDIT use TextBuffer; use ffi; use glib::object::IsA; use glib::translate::*; glib_wrapper! { pub struct TextMark(Object<ffi::GtkTextMark>); match fn { get_type => || ffi::gtk_text_mark_get_type(), } } impl TextMark { pub fn new<'a, P: Into<Option<&'a str>>>(name: P, left_gravity: bool) -> TextMark { assert_initialized_main_thread!(); let name = name.into(); let name = name.to_glib_none(); unsafe { from_glib_full(ffi::gtk_text_mark_new(name.0, left_gravity.to_glib())) } } } pub trait TextMarkExt { fn get_buffer(&self) -> Option<TextBuffer>; fn get_deleted(&self) -> bool; fn get_left_gravity(&self) -> bool; fn get_name(&self) -> Option<String>; fn get_visible(&self) -> bool; fn set_visible(&self, setting: bool); } impl<O: IsA<TextMark>> TextMarkExt for O { fn get_buffer(&self) -> Option<TextBuffer> { unsafe { from_glib_none(ffi::gtk_text_mark_get_buffer(self.to_glib_none().0)) } } fn get_deleted(&self) -> bool { unsafe { from_glib(ffi::gtk_text_mark_get_deleted(self.to_glib_none().0)) } } fn get_left_gravity(&self) -> bool { unsafe { from_glib(ffi::gtk_text_mark_get_left_gravity(self.to_glib_none().0))
} } fn get_name(&self) -> Option<String> { unsafe { from_glib_none(ffi::gtk_text_mark_get_name(self.to_glib_none().0)) } } fn get_visible(&self) -> bool { unsafe { from_glib(ffi::gtk_text_mark_get_visible(self.to_glib_none().0)) } } fn set_visible(&self, setting: bool) { unsafe { ffi::gtk_text_mark_set_visible(self.to_glib_none().0, setting.to_glib()); } } }
random_line_split
text_mark.rs
// This file was generated by gir (5c017c9) from gir-files (71d73f0) // DO NOT EDIT use TextBuffer; use ffi; use glib::object::IsA; use glib::translate::*; glib_wrapper! { pub struct TextMark(Object<ffi::GtkTextMark>); match fn { get_type => || ffi::gtk_text_mark_get_type(), } } impl TextMark { pub fn new<'a, P: Into<Option<&'a str>>>(name: P, left_gravity: bool) -> TextMark { assert_initialized_main_thread!(); let name = name.into(); let name = name.to_glib_none(); unsafe { from_glib_full(ffi::gtk_text_mark_new(name.0, left_gravity.to_glib())) } } } pub trait TextMarkExt { fn get_buffer(&self) -> Option<TextBuffer>; fn get_deleted(&self) -> bool; fn get_left_gravity(&self) -> bool; fn get_name(&self) -> Option<String>; fn get_visible(&self) -> bool; fn set_visible(&self, setting: bool); } impl<O: IsA<TextMark>> TextMarkExt for O { fn get_buffer(&self) -> Option<TextBuffer> { unsafe { from_glib_none(ffi::gtk_text_mark_get_buffer(self.to_glib_none().0)) } } fn get_deleted(&self) -> bool { unsafe { from_glib(ffi::gtk_text_mark_get_deleted(self.to_glib_none().0)) } } fn get_left_gravity(&self) -> bool
fn get_name(&self) -> Option<String> { unsafe { from_glib_none(ffi::gtk_text_mark_get_name(self.to_glib_none().0)) } } fn get_visible(&self) -> bool { unsafe { from_glib(ffi::gtk_text_mark_get_visible(self.to_glib_none().0)) } } fn set_visible(&self, setting: bool) { unsafe { ffi::gtk_text_mark_set_visible(self.to_glib_none().0, setting.to_glib()); } } }
{ unsafe { from_glib(ffi::gtk_text_mark_get_left_gravity(self.to_glib_none().0)) } }
identifier_body
gamma.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. // // ignore-lexer-test FIXME #15679 //! The Gamma and derived distributions. use self::GammaRepr::*; use self::ChiSquaredRepr::*; use core::num::Float; use {Rng, Open01}; use super::normal::StandardNormal; use super::{IndependentSample, Sample, Exp}; /// The Gamma distribution `Gamma(shape, scale)` distribution. /// /// The density function of this distribution is /// /// ```text /// f(x) = x^(k - 1) * exp(-x / θ) / (Γ(k) * θ^k) /// ``` /// /// where `Γ` is the Gamma function, `k` is the shape and `θ` is the /// scale and both `k` and `θ` are strictly positive. /// /// The algorithm used is that described by Marsaglia & Tsang 2000[1], /// falling back to directly sampling from an Exponential for `shape /// == 1`, and using the boosting technique described in [1] for /// `shape < 1`. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{IndependentSample, Gamma}; /// /// let gamma = Gamma::new(2.0, 5.0); /// let v = gamma.ind_sample(&mut rand::task_rng()); /// println!("{} is from a Gamma(2, 5) distribution", v); /// ``` /// /// [1]: George Marsaglia and Wai Wan Tsang. 2000. "A Simple Method /// for Generating Gamma Variables" *ACM Trans. Math. Softw.* 26, 3 /// (September 2000), /// 363-372. DOI:[10.1145/358407.358414](http://doi.acm.org/10.1145/358407.358414) pub struct Gamma { repr: GammaRepr, } enum GammaRepr { Large(GammaLargeShape), One(Exp), Small(GammaSmallShape) } // These two helpers could be made public, but saving the // match-on-Gamma-enum branch from using them directly (e.g. if one // knows that the shape is always > 1) doesn't appear to be much // faster. /// Gamma distribution where the shape parameter is less than 1. /// /// Note, samples from this require a compulsory floating-point `pow` /// call, which makes it significantly slower than sampling from a /// gamma distribution where the shape parameter is greater than or /// equal to 1. /// /// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaSmallShape { inv_shape: f64, large_shape: GammaLargeShape } /// Gamma distribution where the shape parameter is larger than 1. /// /// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaLargeShape { scale: f64, c: f64, d: f64 } impl Gamma { /// Construct an object representing the `Gamma(shape, scale)` /// distribution. /// /// Panics if `shape <= 0` or `scale <= 0`. pub fn new(shape: f64, scale: f64) -> Gamma { assert!(shape > 0.0, "Gamma::new called with shape <= 0"); assert!(scale > 0.0, "Gamma::new called with scale <= 0"); let repr = match shape { 1.0 => One(Exp::new(1.0 / scale)), 0.0... 1.0 => Small(GammaSmallShape::new_raw(shape, scale)), _ => Large(GammaLargeShape::new_raw(shape, scale)) }; Gamma { repr: repr } } } impl GammaSmallShape { fn new_raw(shape: f64, scale: f64) -> GammaSmallShape { GammaSmallShape { inv_shape: 1. / shape, large_shape: GammaLargeShape::new_raw(shape + 1.0, scale) } } } impl GammaLargeShape { fn new_raw(shape: f64, scale: f64) -> GammaLargeShape { let d = shape - 1. / 3.; GammaLargeShape { scale: scale, c: 1. / (9. * d).sqrt(), d: d } } } impl Sample<f64> for Gamma { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl Sample<f64> for GammaSmallShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl Sample<f64> for GammaLargeShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Gamma { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { match self.repr { Small(ref g) => g.ind_sample(rng), One(ref g) => g.ind_sample(rng), Large(ref g) => g.ind_sample(rng), } } } impl IndependentSample<f64> for GammaSmallShape { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let Open01(u) = rng.gen::<Open01<f64>>(); self.large_shape.ind_sample(rng) * u.powf(self.inv_shape) } } impl IndependentSample<f64> for GammaLargeShape { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { loop { let StandardNormal(x) = rng.gen::<StandardNormal>(); let v_cbrt = 1.0 + self.c * x; if v_cbrt <= 0.0 { // a^3 <= 0 iff a <= 0 continue } let v = v_cbrt * v_cbrt * v_cbrt; let Open01(u) = rng.gen::<Open01<f64>>(); let x_sqr = x * x; if u < 1.0 - 0.0331 * x_sqr * x_sqr || u.ln() < 0.5 * x_sqr + self.d * (1.0 - v + v.ln()) { return self.d * v * self.scale } } } } /// The chi-squared distribution `χ²(k)`, where `k` is the degrees of /// freedom. /// /// For `k > 0` integral, this distribution is the sum of the squares /// of `k` independent standard normal random variables. For other /// `k`, this uses the equivalent characterisation `χ²(k) = Gamma(k/2, /// 2)`. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{ChiSquared, IndependentSample}; /// /// let chi = ChiSquared::new(11.0); /// let v = chi.ind_sample(&mut rand::task_rng()); /// println!("{} is from a χ²(11) distribution", v) /// ``` pub struct ChiSquared { repr: ChiSquaredRepr, } enum ChiSquaredRepr { // k == 1, Gamma(alpha,..) is particularly slow for alpha < 1, // e.g. when alpha = 1/2 as it would be for this case, so special- // casing and using the definition of N(0,1)^2 is faster. DoFExactlyOne, DoFAnythingElse(Gamma), } impl ChiSquared { /// Create a new chi-squared distribution with degrees-of-freedom /// `k`. Panics if `k < 0`. pub fn new(k: f64) -> ChiSquared { let repr = if k == 1.0 { DoFExactlyOne } else { assert!(k > 0.0, "ChiSquared::new called with `k` < 0"); DoFAnythingElse(Gamma::new(0.5 * k, 2.0)) }; ChiSquared { repr: repr } } } impl Sample<f64> for ChiSquared { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for ChiSquared { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { match self.repr { DoFExactlyOne => { // k == 1 => N(0,1)^2 let StandardNormal(norm) = rng.gen::<StandardNormal>(); norm * norm } DoFAnythingElse(ref g) => g.ind_sample(rng) } } } /// The Fisher F distribution `F(m, n)`. /// /// This distribution is equivalent to the ratio of two normalised /// chi-squared distributions, that is, `F(m,n) = (χ²(m)/m) / /// (χ²(n)/n)`. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{FisherF, IndependentSample}; /// /// let f = FisherF::new(2.0, 32.0); /// let v = f.ind_sample(&mut rand::task_rng()); /// println!("{} is from an F(2, 32) distribution", v) /// ``` pub struct FisherF { numer: ChiSquared, denom: ChiSquared, // denom_dof / numer_dof so that this can just be a straight // multiplication, rather than a division. dof_ratio: f64, } impl FisherF { /// Create a new `FisherF` distribution, with the given /// parameter. Panics if either `m` or `n` are not positive. pub fn new(m: f64, n: f64) -> FisherF { assert!(m > 0.0, "FisherF::new called with `m < 0`"); assert!(n > 0.0, "FisherF::new called with `n < 0`"); FisherF { numer: ChiSquared::new(m), denom: ChiSquared::new(n), dof_ratio: n / m } } } impl Sample<f64> for FisherF { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for FisherF { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.numer.ind_sample(rng) / self.denom.ind_sample(rng) * self.dof_ratio } } /// The Student t distribution, `t(nu)`, where `nu` is the degrees of /// freedom. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{StudentT, IndependentSample}; /// /// let t = StudentT::new(11.0); /// let v = t.ind_sample(&mut rand::task_rng()); /// println!("{} is from a t(11) distribution", v) /// ``` pub struct StudentT { chi: ChiSquared, dof: f64 } impl StudentT { /// Create a new Student t distribution with `n` degrees of /// freedom. Panics if `n <= 0`. pub fn new(n: f64) -> StudentT { assert!(n > 0.0, "StudentT::new called with `n <= 0`"); StudentT { chi: ChiSquared::new(n), dof: n } } } impl Sample<f64> for StudentT { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for StudentT { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(norm) = rng.gen::<StandardNormal>(); norm * (self.dof / self.chi.ind_sample(rng)).sqrt() } } #[cfg(test)] mod test { use std::prelude::*; use distributions::{Sample, IndependentSample}; use super::{ChiSquared, StudentT, FisherF}; #[test] fn test_chi_squared_one() { let mut chi = ChiSquared::new(1.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] fn test_chi_squared_small() { let mut chi = ChiSquared::new(0.5); let mut rng = ::test::rng(); for _ in range(0u, 1000) { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] fn test_chi_squared_large() { let mut chi = ChiSquared::new(30.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_chi_squared_invalid_dof() { ChiSquared::new(-1.0); } #[test]
let mut f = FisherF::new(2.0, 32.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { f.sample(&mut rng); f.ind_sample(&mut rng); } } #[test] fn test_t() { let mut t = StudentT::new(11.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { t.sample(&mut rng); t.ind_sample(&mut rng); } } } #[cfg(test)] mod bench { extern crate test; use std::prelude::*; use self::test::Bencher; use std::mem::size_of; use distributions::IndependentSample; use super::Gamma; #[bench] fn bench_gamma_large_shape(b: &mut Bencher) { let gamma = Gamma::new(10., 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in range(0, ::RAND_BENCH_N) { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } #[bench] fn bench_gamma_small_shape(b: &mut Bencher) { let gamma = Gamma::new(0.1, 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in range(0, ::RAND_BENCH_N) { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } }
fn test_f() {
random_line_split
gamma.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. // // ignore-lexer-test FIXME #15679 //! The Gamma and derived distributions. use self::GammaRepr::*; use self::ChiSquaredRepr::*; use core::num::Float; use {Rng, Open01}; use super::normal::StandardNormal; use super::{IndependentSample, Sample, Exp}; /// The Gamma distribution `Gamma(shape, scale)` distribution. /// /// The density function of this distribution is /// /// ```text /// f(x) = x^(k - 1) * exp(-x / θ) / (Γ(k) * θ^k) /// ``` /// /// where `Γ` is the Gamma function, `k` is the shape and `θ` is the /// scale and both `k` and `θ` are strictly positive. /// /// The algorithm used is that described by Marsaglia & Tsang 2000[1], /// falling back to directly sampling from an Exponential for `shape /// == 1`, and using the boosting technique described in [1] for /// `shape < 1`. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{IndependentSample, Gamma}; /// /// let gamma = Gamma::new(2.0, 5.0); /// let v = gamma.ind_sample(&mut rand::task_rng()); /// println!("{} is from a Gamma(2, 5) distribution", v); /// ``` /// /// [1]: George Marsaglia and Wai Wan Tsang. 2000. "A Simple Method /// for Generating Gamma Variables" *ACM Trans. Math. Softw.* 26, 3 /// (September 2000), /// 363-372. DOI:[10.1145/358407.358414](http://doi.acm.org/10.1145/358407.358414) pub struct Gamma { repr: GammaRepr, } enum GammaRepr { Large(GammaLargeShape), One(Exp), Small(GammaSmallShape) } // These two helpers could be made public, but saving the // match-on-Gamma-enum branch from using them directly (e.g. if one // knows that the shape is always > 1) doesn't appear to be much // faster. /// Gamma distribution where the shape parameter is less than 1. /// /// Note, samples from this require a compulsory floating-point `pow` /// call, which makes it significantly slower than sampling from a /// gamma distribution where the shape parameter is greater than or /// equal to 1. /// /// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaSmallShape { inv_shape: f64, large_shape: GammaLargeShape } /// Gamma distribution where the shape parameter is larger than 1. /// /// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaLargeShape { scale: f64, c: f64, d: f64 } impl Gamma { /// Construct an object representing the `Gamma(shape, scale)` /// distribution. /// /// Panics if `shape <= 0` or `scale <= 0`. pub fn new(shape: f64, scale: f64) -> Gamma { assert!(shape > 0.0, "Gamma::new called with shape <= 0"); assert!(scale > 0.0, "Gamma::new called with scale <= 0"); let repr = match shape { 1.0 => One(Exp::new(1.0 / scale)), 0.0... 1.0 => Small(GammaSmallShape::new_raw(shape, scale)), _ => Large(GammaLargeShape::new_raw(shape, scale)) }; Gamma { repr: repr } } } impl GammaSmallShape { fn new_raw(shape: f64, scale: f64) -> GammaSmallShape { GammaSmallShape { inv_shape: 1. / shape, large_shape: GammaLargeShape::new_raw(shape + 1.0, scale) } } } impl GammaLargeShape { fn new_raw(shape: f64, scale: f64) -> GammaLargeShape { let d = shape - 1. / 3.; GammaLargeShape { scale: scale, c: 1. / (9. * d).sqrt(), d: d } } } impl Sample<f64> for Gamma { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl Sample<f64> for GammaSmallShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl Sample<f64> for GammaLargeShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Gamma { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { match self.repr { Small(ref g) => g.ind_sample(rng), One(ref g) => g.ind_sample(rng), Large(ref g) => g.ind_sample(rng), } } } impl IndependentSample<f64> for GammaSmallShape { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let Open01(u) = rng.gen::<Open01<f64>>(); self.large_shape.ind_sample(rng) * u.powf(self.inv_shape) } } impl IndependentSample<f64> for GammaLargeShape { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { loop { let StandardNormal(x) = rng.gen::<StandardNormal>(); let v_cbrt = 1.0 + self.c * x; if v_cbrt <= 0.0 { // a^3 <= 0 iff a <= 0 continue } let v = v_cbrt * v_cbrt * v_cbrt; let Open01(u) = rng.gen::<Open01<f64>>(); let x_sqr = x * x; if u < 1.0 - 0.0331 * x_sqr * x_sqr || u.ln() < 0.5 * x_sqr + self.d * (1.0 - v + v.ln()) { return self.d * v * self.scale } } } } /// The chi-squared distribution `χ²(k)`, where `k` is the degrees of /// freedom. /// /// For `k > 0` integral, this distribution is the sum of the squares /// of `k` independent standard normal random variables. For other /// `k`, this uses the equivalent characterisation `χ²(k) = Gamma(k/2, /// 2)`. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{ChiSquared, IndependentSample}; /// /// let chi = ChiSquared::new(11.0); /// let v = chi.ind_sample(&mut rand::task_rng()); /// println!("{} is from a χ²(11) distribution", v) /// ``` pub struct ChiSquared { repr: ChiSquaredRepr, } enum ChiSquaredRepr { // k == 1, Gamma(alpha,..) is particularly slow for alpha < 1, // e.g. when alpha = 1/2 as it would be for this case, so special- // casing and using the definition of N(0,1)^2 is faster. DoFExactlyOne, DoFAnythingElse(Gamma), } impl ChiSquared { /// Create a new chi-squared distribution with degrees-of-freedom /// `k`. Panics if `k < 0`. pub fn new(k: f64) -> ChiSquared { let repr = if k == 1.0 { DoFExactlyOne } else { assert!(k > 0.0, "ChiSquared::new called with `k` < 0"); DoFAnythingElse(Gamma::new(0.5 * k, 2.0)) }; ChiSquared { repr: repr } } } impl Sample<f64> for ChiSquared { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for ChiSquared { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { match self.repr { DoFExactlyOne => { // k == 1 => N(0,1)^2 let StandardNormal(norm) = rng.gen::<StandardNormal>(); norm * norm } DoFAnythingElse(ref g) => g.ind_sample(rng) } } } /// The Fisher F distribution `F(m, n)`. /// /// This distribution is equivalent to the ratio of two normalised /// chi-squared distributions, that is, `F(m,n) = (χ²(m)/m) / /// (χ²(n)/n)`. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{FisherF, IndependentSample}; /// /// let f = FisherF::new(2.0, 32.0); /// let v = f.ind_sample(&mut rand::task_rng()); /// println!("{} is from an F(2, 32) distribution", v) /// ``` pub struct FisherF { numer: ChiSquared, denom: ChiSquared, // denom_dof / numer_dof so that this can just be a straight // multiplication, rather than a division. dof_ratio: f64, } impl FisherF { /// Create a new `FisherF` distribution, with the given /// parameter. Panics if either `m` or `n` are not positive. pub fn new(m: f64, n: f64) -> FisherF { assert!(m > 0.0, "FisherF::new called with `m < 0`"); assert!(n > 0.0, "FisherF::new called with `n < 0`"); FisherF { numer: ChiSquared::new(m), denom: ChiSquared::new(n), dof_ratio: n / m } } } impl Sample<f64> for FisherF { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for FisherF { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.numer.ind_sample(rng) / self.denom.ind_sample(rng) * self.dof_ratio } } /// The Student t distribution, `t(nu)`, where `nu` is the degrees of /// freedom. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{StudentT, IndependentSample}; /// /// let t = StudentT::new(11.0); /// let v = t.ind_sample(&mut rand::task_rng()); /// println!("{} is from a t(11) distribution", v) /// ``` pub struct StudentT { chi: ChiSquared, dof: f64 } impl StudentT { /// Create a new Student t distribution with `n` degrees of /// freedom. Panics if `n <= 0`. pub fn new(n: f64) -> S
entT { assert!(n > 0.0, "StudentT::new called with `n <= 0`"); StudentT { chi: ChiSquared::new(n), dof: n } } } impl Sample<f64> for StudentT { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for StudentT { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(norm) = rng.gen::<StandardNormal>(); norm * (self.dof / self.chi.ind_sample(rng)).sqrt() } } #[cfg(test)] mod test { use std::prelude::*; use distributions::{Sample, IndependentSample}; use super::{ChiSquared, StudentT, FisherF}; #[test] fn test_chi_squared_one() { let mut chi = ChiSquared::new(1.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] fn test_chi_squared_small() { let mut chi = ChiSquared::new(0.5); let mut rng = ::test::rng(); for _ in range(0u, 1000) { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] fn test_chi_squared_large() { let mut chi = ChiSquared::new(30.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_chi_squared_invalid_dof() { ChiSquared::new(-1.0); } #[test] fn test_f() { let mut f = FisherF::new(2.0, 32.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { f.sample(&mut rng); f.ind_sample(&mut rng); } } #[test] fn test_t() { let mut t = StudentT::new(11.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { t.sample(&mut rng); t.ind_sample(&mut rng); } } } #[cfg(test)] mod bench { extern crate test; use std::prelude::*; use self::test::Bencher; use std::mem::size_of; use distributions::IndependentSample; use super::Gamma; #[bench] fn bench_gamma_large_shape(b: &mut Bencher) { let gamma = Gamma::new(10., 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in range(0, ::RAND_BENCH_N) { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } #[bench] fn bench_gamma_small_shape(b: &mut Bencher) { let gamma = Gamma::new(0.1, 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in range(0, ::RAND_BENCH_N) { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } }
tud
identifier_name
gamma.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. // // ignore-lexer-test FIXME #15679 //! The Gamma and derived distributions. use self::GammaRepr::*; use self::ChiSquaredRepr::*; use core::num::Float; use {Rng, Open01}; use super::normal::StandardNormal; use super::{IndependentSample, Sample, Exp}; /// The Gamma distribution `Gamma(shape, scale)` distribution. /// /// The density function of this distribution is /// /// ```text /// f(x) = x^(k - 1) * exp(-x / θ) / (Γ(k) * θ^k) /// ``` /// /// where `Γ` is the Gamma function, `k` is the shape and `θ` is the /// scale and both `k` and `θ` are strictly positive. /// /// The algorithm used is that described by Marsaglia & Tsang 2000[1], /// falling back to directly sampling from an Exponential for `shape /// == 1`, and using the boosting technique described in [1] for /// `shape < 1`. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{IndependentSample, Gamma}; /// /// let gamma = Gamma::new(2.0, 5.0); /// let v = gamma.ind_sample(&mut rand::task_rng()); /// println!("{} is from a Gamma(2, 5) distribution", v); /// ``` /// /// [1]: George Marsaglia and Wai Wan Tsang. 2000. "A Simple Method /// for Generating Gamma Variables" *ACM Trans. Math. Softw.* 26, 3 /// (September 2000), /// 363-372. DOI:[10.1145/358407.358414](http://doi.acm.org/10.1145/358407.358414) pub struct Gamma { repr: GammaRepr, } enum GammaRepr { Large(GammaLargeShape), One(Exp), Small(GammaSmallShape) } // These two helpers could be made public, but saving the // match-on-Gamma-enum branch from using them directly (e.g. if one // knows that the shape is always > 1) doesn't appear to be much // faster. /// Gamma distribution where the shape parameter is less than 1. /// /// Note, samples from this require a compulsory floating-point `pow` /// call, which makes it significantly slower than sampling from a /// gamma distribution where the shape parameter is greater than or /// equal to 1. /// /// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaSmallShape { inv_shape: f64, large_shape: GammaLargeShape } /// Gamma distribution where the shape parameter is larger than 1. /// /// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaLargeShape { scale: f64, c: f64, d: f64 } impl Gamma { /// Construct an object representing the `Gamma(shape, scale)` /// distribution. /// /// Panics if `shape <= 0` or `scale <= 0`. pub fn new(shape: f64, scale: f64) -> Gamma { assert!(shape > 0.0, "Gamma::new called with shape <= 0"); assert!(scale > 0.0, "Gamma::new called with scale <= 0"); let repr = match shape { 1.0 => One(Exp::new(1.0 / scale)), 0.0... 1.0 => Small(GammaSmallShape::new_raw(shape, scale)), _ => Large(GammaLargeShape::new_raw(shape, scale)) }; Gamma { repr: repr } } } impl GammaSmallShape { fn new_raw(shape: f64, scale: f64) -> GammaSmallShape { GammaSmallShape { inv_shape: 1. / shape, large_shape: GammaLargeShape::new_raw(shape + 1.0, scale) } } } impl GammaLargeShape { fn new_raw(shape: f64, scale: f64) -> GammaLargeShape { let d = shape - 1. / 3.; GammaLargeShape { scale: scale, c: 1. / (9. * d).sqrt(), d: d } } } impl Sample<f64> for Gamma { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl Sample<f64> for GammaSmallShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl Sample<f64> for GammaLargeShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Gamma { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { match self.repr { Small(ref g) => g.ind_sample(rng), One(ref g) => g.ind_sample(rng), Large(ref g) => g.ind_sample(rng), } } } impl IndependentSample<f64> for GammaSmallShape { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let Open01(u) = rng.gen::<Open01<f64>>(); self.large_shape.ind_sample(rng) * u.powf(self.inv_shape) } } impl IndependentSample<f64> for GammaLargeShape { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { loop { let StandardNormal(x) = rng.gen::<StandardNormal>(); let v_cbrt = 1.0 + self.c * x; if v_cbrt <= 0.0 { // a^3 <= 0 iff a <= 0 continue } let v = v_cbrt * v_cbrt * v_cbrt; let Open01(u) = rng.gen::<Open01<f64>>(); let x_sqr = x * x; if u < 1.0 - 0.0331 * x_sqr * x_sqr || u.ln() < 0.5 * x_sqr + self.d * (1.0 - v + v.ln()) { return self.d * v * self.scale } } } } /// The chi-squared distribution `χ²(k)`, where `k` is the degrees of /// freedom. /// /// For `k > 0` integral, this distribution is the sum of the squares /// of `k` independent standard normal random variables. For other /// `k`, this uses the equivalent characterisation `χ²(k) = Gamma(k/2, /// 2)`. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{ChiSquared, IndependentSample}; /// /// let chi = ChiSquared::new(11.0); /// let v = chi.ind_sample(&mut rand::task_rng()); /// println!("{} is from a χ²(11) distribution", v) /// ``` pub struct ChiSquared { repr: ChiSquaredRepr, } enum ChiSquaredRepr { // k == 1, Gamma(alpha,..) is particularly slow for alpha < 1, // e.g. when alpha = 1/2 as it would be for this case, so special- // casing and using the definition of N(0,1)^2 is faster. DoFExactlyOne, DoFAnythingElse(Gamma), } impl ChiSquared { /// Create a new chi-squared distribution with degrees-of-freedom /// `k`. Panics if `k < 0`. pub fn new(k: f64) -> ChiSquared { let repr = if k == 1.0 { DoFExactlyOne } else { assert!(k > 0.0, "ChiSquared::new called with `k` < 0"); DoFAnythingElse(Gamma::new(0.5 * k, 2.0)) }; ChiSquared { repr: repr } } } impl Sample<f64> for ChiSquared { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for ChiSquared { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { match self.repr { DoFExactlyOne => { // k == 1 => N(0,1)^2 let StandardNormal(norm) = rng.gen::<StandardNormal>(); norm * norm } DoFAnythingElse(ref g) => g.ind_sample(rng) } } } /// The Fisher F distribution `F(m, n)`. /// /// This distribution is equivalent to the ratio of two normalised /// chi-squared distributions, that is, `F(m,n) = (χ²(m)/m) / /// (χ²(n)/n)`. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{FisherF, IndependentSample}; /// /// let f = FisherF::new(2.0, 32.0); /// let v = f.ind_sample(&mut rand::task_rng()); /// println!("{} is from an F(2, 32) distribution", v) /// ``` pub struct FisherF { numer: ChiSquared, denom: ChiSquared, // denom_dof / numer_dof so that this can just be a straight // multiplication, rather than a division. dof_ratio: f64, } impl FisherF { /// Create a new `FisherF` distribution, with the given /// parameter. Panics if either `m` or `n` are not positive. pub fn new(m: f64, n: f64) -> FisherF { assert!(m > 0.0, "FisherF::new called with `m < 0`"); assert!(n > 0.0, "FisherF::new called with `n < 0`"); FisherF { numer: ChiSquared::new(m), denom: ChiSquared::new(n), dof_ratio: n / m } } } impl Sample<f64> for FisherF { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for FisherF { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.numer.ind_sample(rng) / self.denom.ind_sample(rng) * self.dof_ratio } } /// The Student t distribution, `t(nu)`, where `nu` is the degrees of /// freedom. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{StudentT, IndependentSample}; /// /// let t = StudentT::new(11.0); /// let v = t.ind_sample(&mut rand::task_rng()); /// println!("{} is from a t(11) distribution", v) /// ``` pub struct StudentT { chi: ChiSquared, dof: f64 } impl StudentT { /// Create a new Student t distribution with `n` degrees of /// freedom. Panics if `n <= 0`. pub fn new(n: f64) -> StudentT { assert!(n > 0.0, "StudentT::new called with `n <= 0`"); StudentT { chi: ChiSquared::new(n), dof: n } } } impl Sample<f64> for StudentT { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for StudentT { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(norm) = rng.gen::<StandardNormal>(); norm * (self.dof / self.chi.ind_sample(rng)).sqrt() } } #[cfg(test)] mod test { use std::prelude::*; use distributions::{Sample, IndependentSample}; use super::{ChiSquared, StudentT, FisherF}; #[test] fn test_chi_squared_one() { let mut chi = ChiSquared::new(1.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] fn test_chi_squared_small() { let mut chi = ChiSquared::new(0.5); let mut rng = ::test::rng(); for _ in range(0u, 1000) { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] fn test_chi_squared_large() { let mut chi = ChiSquared::new(30.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_chi_squared_invalid_dof() { ChiSquared::new(-1.0); } #[test] fn test_f() { let mut f = FisherF::new(2.0, 32.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { f.sample(&mut rng); f.ind_sample(&mut rng); } } #[test] fn test_t() { let mut t = StudentT::new(11.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { t.sample(&mut rng); t.ind_sample(&mut rng); } } } #[cfg(test)] mod bench { extern crate test; use std::prelude::*; use self::test::Bencher; use std::mem::size_of; use distributions::IndependentSample; use super::Gamma; #[bench] fn bench_gamma_large_shape(b: &mut Bencher) { let gamma = Gamma::new(10., 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in range(0, ::RAND_BENCH_N) { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } #[bench] fn bench_gamma_small_shape(b: &mut Bencher) { let ga
mma = Gamma::new(0.1, 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in range(0, ::RAND_BENCH_N) { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } }
identifier_body
gamma.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. // // ignore-lexer-test FIXME #15679 //! The Gamma and derived distributions. use self::GammaRepr::*; use self::ChiSquaredRepr::*; use core::num::Float; use {Rng, Open01}; use super::normal::StandardNormal; use super::{IndependentSample, Sample, Exp}; /// The Gamma distribution `Gamma(shape, scale)` distribution. /// /// The density function of this distribution is /// /// ```text /// f(x) = x^(k - 1) * exp(-x / θ) / (Γ(k) * θ^k) /// ``` /// /// where `Γ` is the Gamma function, `k` is the shape and `θ` is the /// scale and both `k` and `θ` are strictly positive. /// /// The algorithm used is that described by Marsaglia & Tsang 2000[1], /// falling back to directly sampling from an Exponential for `shape /// == 1`, and using the boosting technique described in [1] for /// `shape < 1`. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{IndependentSample, Gamma}; /// /// let gamma = Gamma::new(2.0, 5.0); /// let v = gamma.ind_sample(&mut rand::task_rng()); /// println!("{} is from a Gamma(2, 5) distribution", v); /// ``` /// /// [1]: George Marsaglia and Wai Wan Tsang. 2000. "A Simple Method /// for Generating Gamma Variables" *ACM Trans. Math. Softw.* 26, 3 /// (September 2000), /// 363-372. DOI:[10.1145/358407.358414](http://doi.acm.org/10.1145/358407.358414) pub struct Gamma { repr: GammaRepr, } enum GammaRepr { Large(GammaLargeShape), One(Exp), Small(GammaSmallShape) } // These two helpers could be made public, but saving the // match-on-Gamma-enum branch from using them directly (e.g. if one // knows that the shape is always > 1) doesn't appear to be much // faster. /// Gamma distribution where the shape parameter is less than 1. /// /// Note, samples from this require a compulsory floating-point `pow` /// call, which makes it significantly slower than sampling from a /// gamma distribution where the shape parameter is greater than or /// equal to 1. /// /// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaSmallShape { inv_shape: f64, large_shape: GammaLargeShape } /// Gamma distribution where the shape parameter is larger than 1. /// /// See `Gamma` for sampling from a Gamma distribution with general /// shape parameters. struct GammaLargeShape { scale: f64, c: f64, d: f64 } impl Gamma { /// Construct an object representing the `Gamma(shape, scale)` /// distribution. /// /// Panics if `shape <= 0` or `scale <= 0`. pub fn new(shape: f64, scale: f64) -> Gamma { assert!(shape > 0.0, "Gamma::new called with shape <= 0"); assert!(scale > 0.0, "Gamma::new called with scale <= 0"); let repr = match shape { 1.0 => One(Exp::new(1.0 / scale)), 0.0... 1.0 => Small(GammaSmallShape::new_raw(shape, scale)), _ => Large(GammaLargeShape::new_raw(shape, scale)) }; Gamma { repr: repr } } } impl GammaSmallShape { fn new_raw(shape: f64, scale: f64) -> GammaSmallShape { GammaSmallShape { inv_shape: 1. / shape, large_shape: GammaLargeShape::new_raw(shape + 1.0, scale) } } } impl GammaLargeShape { fn new_raw(shape: f64, scale: f64) -> GammaLargeShape { let d = shape - 1. / 3.; GammaLargeShape { scale: scale, c: 1. / (9. * d).sqrt(), d: d } } } impl Sample<f64> for Gamma { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl Sample<f64> for GammaSmallShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl Sample<f64> for GammaLargeShape { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Gamma { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { match self.repr { Small(ref g) => g.ind_sample(rng), One(ref g) => g.ind_sample(rng), Large(ref g) => g.ind_sample(rng), } } } impl IndependentSample<f64> for GammaSmallShape { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let Open01(u) = rng.gen::<Open01<f64>>(); self.large_shape.ind_sample(rng) * u.powf(self.inv_shape) } } impl IndependentSample<f64> for GammaLargeShape { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { loop { let StandardNormal(x) = rng.gen::<StandardNormal>(); let v_cbrt = 1.0 + self.c * x; if v_cbrt <= 0.0 { // a
let v = v_cbrt * v_cbrt * v_cbrt; let Open01(u) = rng.gen::<Open01<f64>>(); let x_sqr = x * x; if u < 1.0 - 0.0331 * x_sqr * x_sqr || u.ln() < 0.5 * x_sqr + self.d * (1.0 - v + v.ln()) { return self.d * v * self.scale } } } } /// The chi-squared distribution `χ²(k)`, where `k` is the degrees of /// freedom. /// /// For `k > 0` integral, this distribution is the sum of the squares /// of `k` independent standard normal random variables. For other /// `k`, this uses the equivalent characterisation `χ²(k) = Gamma(k/2, /// 2)`. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{ChiSquared, IndependentSample}; /// /// let chi = ChiSquared::new(11.0); /// let v = chi.ind_sample(&mut rand::task_rng()); /// println!("{} is from a χ²(11) distribution", v) /// ``` pub struct ChiSquared { repr: ChiSquaredRepr, } enum ChiSquaredRepr { // k == 1, Gamma(alpha,..) is particularly slow for alpha < 1, // e.g. when alpha = 1/2 as it would be for this case, so special- // casing and using the definition of N(0,1)^2 is faster. DoFExactlyOne, DoFAnythingElse(Gamma), } impl ChiSquared { /// Create a new chi-squared distribution with degrees-of-freedom /// `k`. Panics if `k < 0`. pub fn new(k: f64) -> ChiSquared { let repr = if k == 1.0 { DoFExactlyOne } else { assert!(k > 0.0, "ChiSquared::new called with `k` < 0"); DoFAnythingElse(Gamma::new(0.5 * k, 2.0)) }; ChiSquared { repr: repr } } } impl Sample<f64> for ChiSquared { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for ChiSquared { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { match self.repr { DoFExactlyOne => { // k == 1 => N(0,1)^2 let StandardNormal(norm) = rng.gen::<StandardNormal>(); norm * norm } DoFAnythingElse(ref g) => g.ind_sample(rng) } } } /// The Fisher F distribution `F(m, n)`. /// /// This distribution is equivalent to the ratio of two normalised /// chi-squared distributions, that is, `F(m,n) = (χ²(m)/m) / /// (χ²(n)/n)`. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{FisherF, IndependentSample}; /// /// let f = FisherF::new(2.0, 32.0); /// let v = f.ind_sample(&mut rand::task_rng()); /// println!("{} is from an F(2, 32) distribution", v) /// ``` pub struct FisherF { numer: ChiSquared, denom: ChiSquared, // denom_dof / numer_dof so that this can just be a straight // multiplication, rather than a division. dof_ratio: f64, } impl FisherF { /// Create a new `FisherF` distribution, with the given /// parameter. Panics if either `m` or `n` are not positive. pub fn new(m: f64, n: f64) -> FisherF { assert!(m > 0.0, "FisherF::new called with `m < 0`"); assert!(n > 0.0, "FisherF::new called with `n < 0`"); FisherF { numer: ChiSquared::new(m), denom: ChiSquared::new(n), dof_ratio: n / m } } } impl Sample<f64> for FisherF { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for FisherF { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.numer.ind_sample(rng) / self.denom.ind_sample(rng) * self.dof_ratio } } /// The Student t distribution, `t(nu)`, where `nu` is the degrees of /// freedom. /// /// # Example /// /// ```rust /// use std::rand; /// use std::rand::distributions::{StudentT, IndependentSample}; /// /// let t = StudentT::new(11.0); /// let v = t.ind_sample(&mut rand::task_rng()); /// println!("{} is from a t(11) distribution", v) /// ``` pub struct StudentT { chi: ChiSquared, dof: f64 } impl StudentT { /// Create a new Student t distribution with `n` degrees of /// freedom. Panics if `n <= 0`. pub fn new(n: f64) -> StudentT { assert!(n > 0.0, "StudentT::new called with `n <= 0`"); StudentT { chi: ChiSquared::new(n), dof: n } } } impl Sample<f64> for StudentT { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for StudentT { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(norm) = rng.gen::<StandardNormal>(); norm * (self.dof / self.chi.ind_sample(rng)).sqrt() } } #[cfg(test)] mod test { use std::prelude::*; use distributions::{Sample, IndependentSample}; use super::{ChiSquared, StudentT, FisherF}; #[test] fn test_chi_squared_one() { let mut chi = ChiSquared::new(1.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] fn test_chi_squared_small() { let mut chi = ChiSquared::new(0.5); let mut rng = ::test::rng(); for _ in range(0u, 1000) { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] fn test_chi_squared_large() { let mut chi = ChiSquared::new(30.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { chi.sample(&mut rng); chi.ind_sample(&mut rng); } } #[test] #[should_fail] fn test_chi_squared_invalid_dof() { ChiSquared::new(-1.0); } #[test] fn test_f() { let mut f = FisherF::new(2.0, 32.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { f.sample(&mut rng); f.ind_sample(&mut rng); } } #[test] fn test_t() { let mut t = StudentT::new(11.0); let mut rng = ::test::rng(); for _ in range(0u, 1000) { t.sample(&mut rng); t.ind_sample(&mut rng); } } } #[cfg(test)] mod bench { extern crate test; use std::prelude::*; use self::test::Bencher; use std::mem::size_of; use distributions::IndependentSample; use super::Gamma; #[bench] fn bench_gamma_large_shape(b: &mut Bencher) { let gamma = Gamma::new(10., 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in range(0, ::RAND_BENCH_N) { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } #[bench] fn bench_gamma_small_shape(b: &mut Bencher) { let gamma = Gamma::new(0.1, 1.0); let mut rng = ::test::weak_rng(); b.iter(|| { for _ in range(0, ::RAND_BENCH_N) { gamma.ind_sample(&mut rng); } }); b.bytes = size_of::<f64>() as u64 * ::RAND_BENCH_N; } }
^3 <= 0 iff a <= 0 continue }
conditional_block
mod.rs
// This file is part of Rubik. // Copyright Peter Beard, licensed under the GPLv3. See LICENSE for details. // //! Algorithms for solving Rubik's cubes use super::cube::{Cube, Move}; /// Trait for things that can solve Rubik's cubes pub trait Solver { /// Calculate a sequence of moves that puts the cube in the solved state fn find_solution(&mut self, cube: &Cube) -> Vec<Move>; } /// Solver that doesn't do anything /// /// # Example /// ``` /// use rubik::cube::Cube; /// use rubik::solver::{Solver, NullSolver}; /// /// let mut c = Cube::new(); /// let mut ns = NullSolver::new(); /// /// assert_eq!(c.solve(&mut ns), vec![]); /// ``` pub struct NullSolver; impl NullSolver { pub fn new() -> NullSolver { NullSolver } } impl Solver for NullSolver { fn find_solution(&mut self, _: &Cube) -> Vec<Move>
} /// Solver that uses a simple iterative deepening algorithm /// /// This algorithm is very slow and probably won't halt in a reasonable time for /// most cubes /// /// # Example /// ``` /// use rubik::cube::Cube; /// use rubik::solver::IDSolver; /// /// let mut c = Cube::new(); /// let mut ids = IDSolver::new(); /// /// c.apply_moves("F'U'D'"); /// println!("{:?}", c.solve(&mut ids)); /// /// assert!(c.is_solved()); /// ``` pub struct IDSolver { max_depth: u8, } impl IDSolver { /// Create a new solver with the default maximum depth of 26 /// (all cubes are solveable in at most 26 moves) pub fn new() -> IDSolver { IDSolver { max_depth: 26u8, } } /// Create a solver with the given maximum depth (max number of moves) pub fn with_max_depth(d: u8) -> IDSolver { IDSolver { max_depth: d, } } } impl Solver for IDSolver { fn find_solution(&mut self, cube: &Cube) -> Vec<Move> { let mut current_solution: Option<Vec<Move>> = None; let mut current_depth = 1; // A solved cube requires zero moves to solve if!cube.is_solved() { // Look until we find a solution or run out of moves while current_depth <= self.max_depth && current_solution.is_none() { current_solution = dbsearch(cube, current_depth); current_depth += 1; } } // Return no moves if there's no solution within the max depth if let Some(s) = current_solution { s } else { vec![] } } } /// Depth-bounded search for a solution fn dbsearch(start: &Cube, maxdepth: u8) -> Option<Vec<Move>> { // Zero means we're at the max depth if maxdepth == 0 { return None; } let possible_moves = [ Move::F, Move::R, Move::U, Move::B, Move::L, Move::D, Move::FPrime, Move::RPrime, Move::UPrime, Move::BPrime, Move::LPrime, Move::DPrime, ]; let mut moves = Vec::new(); // Try every possible move and see where we get for &m in &possible_moves { let mut s = start.clone(); s.apply_move(m); moves.push(m); if s.is_solved() { break; } if let Some(ms) = dbsearch(&s, maxdepth - 1) { moves.append(&mut ms.clone()); break; } else { moves.pop(); } } if moves.len() > 0 { Some(moves) } else { None } }
{ vec![] }
identifier_body
mod.rs
// This file is part of Rubik. // Copyright Peter Beard, licensed under the GPLv3. See LICENSE for details. // //! Algorithms for solving Rubik's cubes use super::cube::{Cube, Move}; /// Trait for things that can solve Rubik's cubes pub trait Solver { /// Calculate a sequence of moves that puts the cube in the solved state fn find_solution(&mut self, cube: &Cube) -> Vec<Move>; } /// Solver that doesn't do anything /// /// # Example /// ``` /// use rubik::cube::Cube; /// use rubik::solver::{Solver, NullSolver}; /// /// let mut c = Cube::new(); /// let mut ns = NullSolver::new(); /// /// assert_eq!(c.solve(&mut ns), vec![]); /// ``` pub struct NullSolver; impl NullSolver { pub fn new() -> NullSolver { NullSolver } } impl Solver for NullSolver { fn find_solution(&mut self, _: &Cube) -> Vec<Move> { vec![] } } /// Solver that uses a simple iterative deepening algorithm /// /// This algorithm is very slow and probably won't halt in a reasonable time for /// most cubes /// /// # Example /// ``` /// use rubik::cube::Cube; /// use rubik::solver::IDSolver; /// /// let mut c = Cube::new(); /// let mut ids = IDSolver::new(); /// /// c.apply_moves("F'U'D'"); /// println!("{:?}", c.solve(&mut ids)); /// /// assert!(c.is_solved()); /// ``` pub struct IDSolver { max_depth: u8, } impl IDSolver { /// Create a new solver with the default maximum depth of 26 /// (all cubes are solveable in at most 26 moves) pub fn new() -> IDSolver { IDSolver { max_depth: 26u8, } } /// Create a solver with the given maximum depth (max number of moves) pub fn with_max_depth(d: u8) -> IDSolver { IDSolver { max_depth: d, } } } impl Solver for IDSolver { fn find_solution(&mut self, cube: &Cube) -> Vec<Move> { let mut current_solution: Option<Vec<Move>> = None; let mut current_depth = 1; // A solved cube requires zero moves to solve if!cube.is_solved() { // Look until we find a solution or run out of moves while current_depth <= self.max_depth && current_solution.is_none() { current_solution = dbsearch(cube, current_depth); current_depth += 1; } } // Return no moves if there's no solution within the max depth if let Some(s) = current_solution { s } else { vec![] } } } /// Depth-bounded search for a solution fn dbsearch(start: &Cube, maxdepth: u8) -> Option<Vec<Move>> { // Zero means we're at the max depth if maxdepth == 0 { return None; } let possible_moves = [ Move::F, Move::R, Move::U, Move::B, Move::L, Move::D, Move::FPrime, Move::RPrime, Move::UPrime, Move::BPrime, Move::LPrime, Move::DPrime, ]; let mut moves = Vec::new(); // Try every possible move and see where we get for &m in &possible_moves { let mut s = start.clone(); s.apply_move(m); moves.push(m); if s.is_solved()
if let Some(ms) = dbsearch(&s, maxdepth - 1) { moves.append(&mut ms.clone()); break; } else { moves.pop(); } } if moves.len() > 0 { Some(moves) } else { None } }
{ break; }
conditional_block
mod.rs
// This file is part of Rubik. // Copyright Peter Beard, licensed under the GPLv3. See LICENSE for details. // //! Algorithms for solving Rubik's cubes use super::cube::{Cube, Move}; /// Trait for things that can solve Rubik's cubes pub trait Solver { /// Calculate a sequence of moves that puts the cube in the solved state fn find_solution(&mut self, cube: &Cube) -> Vec<Move>; } /// Solver that doesn't do anything /// /// # Example /// ``` /// use rubik::cube::Cube; /// use rubik::solver::{Solver, NullSolver}; /// /// let mut c = Cube::new(); /// let mut ns = NullSolver::new(); /// /// assert_eq!(c.solve(&mut ns), vec![]); /// ``` pub struct NullSolver; impl NullSolver { pub fn new() -> NullSolver { NullSolver } } impl Solver for NullSolver { fn find_solution(&mut self, _: &Cube) -> Vec<Move> { vec![] } } /// Solver that uses a simple iterative deepening algorithm /// /// This algorithm is very slow and probably won't halt in a reasonable time for /// most cubes /// /// # Example /// ``` /// use rubik::cube::Cube; /// use rubik::solver::IDSolver; /// /// let mut c = Cube::new(); /// let mut ids = IDSolver::new(); /// /// c.apply_moves("F'U'D'"); /// println!("{:?}", c.solve(&mut ids)); ///
impl IDSolver { /// Create a new solver with the default maximum depth of 26 /// (all cubes are solveable in at most 26 moves) pub fn new() -> IDSolver { IDSolver { max_depth: 26u8, } } /// Create a solver with the given maximum depth (max number of moves) pub fn with_max_depth(d: u8) -> IDSolver { IDSolver { max_depth: d, } } } impl Solver for IDSolver { fn find_solution(&mut self, cube: &Cube) -> Vec<Move> { let mut current_solution: Option<Vec<Move>> = None; let mut current_depth = 1; // A solved cube requires zero moves to solve if!cube.is_solved() { // Look until we find a solution or run out of moves while current_depth <= self.max_depth && current_solution.is_none() { current_solution = dbsearch(cube, current_depth); current_depth += 1; } } // Return no moves if there's no solution within the max depth if let Some(s) = current_solution { s } else { vec![] } } } /// Depth-bounded search for a solution fn dbsearch(start: &Cube, maxdepth: u8) -> Option<Vec<Move>> { // Zero means we're at the max depth if maxdepth == 0 { return None; } let possible_moves = [ Move::F, Move::R, Move::U, Move::B, Move::L, Move::D, Move::FPrime, Move::RPrime, Move::UPrime, Move::BPrime, Move::LPrime, Move::DPrime, ]; let mut moves = Vec::new(); // Try every possible move and see where we get for &m in &possible_moves { let mut s = start.clone(); s.apply_move(m); moves.push(m); if s.is_solved() { break; } if let Some(ms) = dbsearch(&s, maxdepth - 1) { moves.append(&mut ms.clone()); break; } else { moves.pop(); } } if moves.len() > 0 { Some(moves) } else { None } }
/// assert!(c.is_solved()); /// ``` pub struct IDSolver { max_depth: u8, }
random_line_split
mod.rs
// This file is part of Rubik. // Copyright Peter Beard, licensed under the GPLv3. See LICENSE for details. // //! Algorithms for solving Rubik's cubes use super::cube::{Cube, Move}; /// Trait for things that can solve Rubik's cubes pub trait Solver { /// Calculate a sequence of moves that puts the cube in the solved state fn find_solution(&mut self, cube: &Cube) -> Vec<Move>; } /// Solver that doesn't do anything /// /// # Example /// ``` /// use rubik::cube::Cube; /// use rubik::solver::{Solver, NullSolver}; /// /// let mut c = Cube::new(); /// let mut ns = NullSolver::new(); /// /// assert_eq!(c.solve(&mut ns), vec![]); /// ``` pub struct NullSolver; impl NullSolver { pub fn
() -> NullSolver { NullSolver } } impl Solver for NullSolver { fn find_solution(&mut self, _: &Cube) -> Vec<Move> { vec![] } } /// Solver that uses a simple iterative deepening algorithm /// /// This algorithm is very slow and probably won't halt in a reasonable time for /// most cubes /// /// # Example /// ``` /// use rubik::cube::Cube; /// use rubik::solver::IDSolver; /// /// let mut c = Cube::new(); /// let mut ids = IDSolver::new(); /// /// c.apply_moves("F'U'D'"); /// println!("{:?}", c.solve(&mut ids)); /// /// assert!(c.is_solved()); /// ``` pub struct IDSolver { max_depth: u8, } impl IDSolver { /// Create a new solver with the default maximum depth of 26 /// (all cubes are solveable in at most 26 moves) pub fn new() -> IDSolver { IDSolver { max_depth: 26u8, } } /// Create a solver with the given maximum depth (max number of moves) pub fn with_max_depth(d: u8) -> IDSolver { IDSolver { max_depth: d, } } } impl Solver for IDSolver { fn find_solution(&mut self, cube: &Cube) -> Vec<Move> { let mut current_solution: Option<Vec<Move>> = None; let mut current_depth = 1; // A solved cube requires zero moves to solve if!cube.is_solved() { // Look until we find a solution or run out of moves while current_depth <= self.max_depth && current_solution.is_none() { current_solution = dbsearch(cube, current_depth); current_depth += 1; } } // Return no moves if there's no solution within the max depth if let Some(s) = current_solution { s } else { vec![] } } } /// Depth-bounded search for a solution fn dbsearch(start: &Cube, maxdepth: u8) -> Option<Vec<Move>> { // Zero means we're at the max depth if maxdepth == 0 { return None; } let possible_moves = [ Move::F, Move::R, Move::U, Move::B, Move::L, Move::D, Move::FPrime, Move::RPrime, Move::UPrime, Move::BPrime, Move::LPrime, Move::DPrime, ]; let mut moves = Vec::new(); // Try every possible move and see where we get for &m in &possible_moves { let mut s = start.clone(); s.apply_move(m); moves.push(m); if s.is_solved() { break; } if let Some(ms) = dbsearch(&s, maxdepth - 1) { moves.append(&mut ms.clone()); break; } else { moves.pop(); } } if moves.len() > 0 { Some(moves) } else { None } }
new
identifier_name
lib.rs
//! # Elektra //! Safe bindings for [libelektra](https://www.libelektra.org). //! //! See the [project's readme](https://master.libelektra.org/src/bindings/rust) for an introduction and examples. //! //! The crate consists of three major parts. //! //! - The [keys](key/index.html) that encapsulate name, value and metainfo //! - A [`KeySet`](keyset/index.html) holds a set of `StringKey`s, since these are the most common type of key //! - [`KDB`](kdb/index.html) allows access to the persistent key database by reading or writing `KeySet`s //! //! Refer to the documentation of the modules to learn more about each. extern crate bitflags; extern crate elektra_sys; pub mod key; pub mod keybuilder; /// Trait to read values from a key. pub mod readable; /// A wrapper Trait to make keys readonly. pub mod readonly;
pub mod kdb; pub use self::key::{BinaryKey, StringKey, MetaIter, NameIter, KeyNameInvalidError, KeyNameReadOnlyError, KeyNotFoundError, CopyOption}; pub use self::keybuilder::KeyBuilder; pub use self::readable::ReadableKey; pub use self::readonly::ReadOnly; pub use self::writeable::WriteableKey; pub use self::keyset::{KeySet, ReadOnlyStringKeyIter, StringKeyIter, Cursor, LookupOption}; pub use self::kdb::{KDB, KDBError};
/// Trait to write values to a key. pub mod writeable; pub mod keyset;
random_line_split
lib.rs
//! # Iron CMS //! CMS based on Iron Framework for **Rust**. #[macro_use] extern crate iron; #[macro_use] extern crate router; #[macro_use] extern crate maplit; #[macro_use] extern crate diesel; extern crate handlebars_iron as hbs; extern crate handlebars; extern crate rustc_serialize; extern crate staticfile; extern crate mount; extern crate time; extern crate params; extern crate iron_diesel_middleware; extern crate r2d2; extern crate r2d2_diesel; extern crate regex; /// Base middleware for CMS pub mod middleware; mod admin; mod frontend; use router::Router; use staticfile::Static; #[cfg(feature = "cache")] use staticfile::Cache; use mount::Mount; use std::path::Path; #[cfg(feature = "cache")] use time::Duration; /// Routes aggregator. /// It accumulate all posible routes for CMS. /// ## How to use /// ``` /// extern crate iron; /// extern crate iron_cms; /// use iron::{Iron, Chain}; /// fn main() { /// // Add routers /// let mut chain = Chain::new(iron_cms::routes()); /// // Add Template renderer and views path /// let paths = vec!["./views/"]; /// chain.link_after(iron_cms::middleware::template_render(paths)); /// // Add error-404 handler /// chain.link_after(iron_cms::middleware::Error404); /// // Start applocation and other actions /// // Iron::new(chain).http("localhost:3000").unwrap(); /// } /// ``` pub fn routes() -> Mount
{ // Init router let mut routes = Router::new(); // Add routes frontend::add_routes(&mut routes); admin::add_routes(&mut routes); // Add static router let mut mount = Mount::new(); mount .mount("/", routes) .mount("/assets/", Static::new(Path::new("static"))); // .cache(Duration::days(30))); mount }
identifier_body
lib.rs
//! # Iron CMS //! CMS based on Iron Framework for **Rust**. #[macro_use] extern crate iron; #[macro_use] extern crate router; #[macro_use] extern crate maplit; #[macro_use] extern crate diesel; extern crate handlebars_iron as hbs; extern crate handlebars; extern crate rustc_serialize; extern crate staticfile; extern crate mount; extern crate time; extern crate params; extern crate iron_diesel_middleware; extern crate r2d2; extern crate r2d2_diesel; extern crate regex; /// Base middleware for CMS pub mod middleware; mod admin; mod frontend; use router::Router; use staticfile::Static; #[cfg(feature = "cache")] use staticfile::Cache; use mount::Mount; use std::path::Path; #[cfg(feature = "cache")] use time::Duration; /// Routes aggregator. /// It accumulate all posible routes for CMS. /// ## How to use /// ``` /// extern crate iron; /// extern crate iron_cms; /// use iron::{Iron, Chain}; /// fn main() { /// // Add routers /// let mut chain = Chain::new(iron_cms::routes()); /// // Add Template renderer and views path /// let paths = vec!["./views/"];
/// // Start applocation and other actions /// // Iron::new(chain).http("localhost:3000").unwrap(); /// } /// ``` pub fn routes() -> Mount { // Init router let mut routes = Router::new(); // Add routes frontend::add_routes(&mut routes); admin::add_routes(&mut routes); // Add static router let mut mount = Mount::new(); mount .mount("/", routes) .mount("/assets/", Static::new(Path::new("static"))); // .cache(Duration::days(30))); mount }
/// chain.link_after(iron_cms::middleware::template_render(paths)); /// // Add error-404 handler /// chain.link_after(iron_cms::middleware::Error404);
random_line_split
lib.rs
//! # Iron CMS //! CMS based on Iron Framework for **Rust**. #[macro_use] extern crate iron; #[macro_use] extern crate router; #[macro_use] extern crate maplit; #[macro_use] extern crate diesel; extern crate handlebars_iron as hbs; extern crate handlebars; extern crate rustc_serialize; extern crate staticfile; extern crate mount; extern crate time; extern crate params; extern crate iron_diesel_middleware; extern crate r2d2; extern crate r2d2_diesel; extern crate regex; /// Base middleware for CMS pub mod middleware; mod admin; mod frontend; use router::Router; use staticfile::Static; #[cfg(feature = "cache")] use staticfile::Cache; use mount::Mount; use std::path::Path; #[cfg(feature = "cache")] use time::Duration; /// Routes aggregator. /// It accumulate all posible routes for CMS. /// ## How to use /// ``` /// extern crate iron; /// extern crate iron_cms; /// use iron::{Iron, Chain}; /// fn main() { /// // Add routers /// let mut chain = Chain::new(iron_cms::routes()); /// // Add Template renderer and views path /// let paths = vec!["./views/"]; /// chain.link_after(iron_cms::middleware::template_render(paths)); /// // Add error-404 handler /// chain.link_after(iron_cms::middleware::Error404); /// // Start applocation and other actions /// // Iron::new(chain).http("localhost:3000").unwrap(); /// } /// ``` pub fn
() -> Mount { // Init router let mut routes = Router::new(); // Add routes frontend::add_routes(&mut routes); admin::add_routes(&mut routes); // Add static router let mut mount = Mount::new(); mount .mount("/", routes) .mount("/assets/", Static::new(Path::new("static"))); // .cache(Duration::days(30))); mount }
routes
identifier_name
harfbuzz.rs
get_glyph_infos(buffer, &mut glyph_count); let glyph_count = glyph_count as int; assert!(glyph_infos.is_not_null()); let mut pos_count = 0; let pos_infos = hb_buffer_get_glyph_positions(buffer, &mut pos_count); let pos_count = pos_count as int; assert!(pos_infos.is_not_null()); assert!(glyph_count == pos_count); ShapedGlyphData { count: glyph_count, glyph_infos: glyph_infos, pos_infos: pos_infos, } } } #[inline(always)] fn byte_offset_of_glyph(&self, i: int) -> int { assert!(i < self.count); unsafe { let glyph_info_i = self.glyph_infos.offset(i); (*glyph_info_i).cluster as int } } pub fn len(&self) -> int { self.count } /// Returns shaped glyph data for one glyph, and updates the y-position of the pen. pub fn get_entry_for_glyph(&self, i: int, y_pos: &mut Au) -> ShapedGlyphEntry { assert!(i < self.count); unsafe { let glyph_info_i = self.glyph_infos.offset(i); let pos_info_i = self.pos_infos.offset(i); let x_offset = Shaper::fixed_to_float((*pos_info_i).x_offset); let y_offset = Shaper::fixed_to_float((*pos_info_i).y_offset); let x_advance = Shaper::fixed_to_float((*pos_info_i).x_advance); let y_advance = Shaper::fixed_to_float((*pos_info_i).y_advance); let x_offset = Au::from_frac_px(x_offset); let y_offset = Au::from_frac_px(y_offset); let x_advance = Au::from_frac_px(x_advance); let y_advance = Au::from_frac_px(y_advance); let offset = if x_offset == Au(0) && y_offset == Au(0) && y_advance == Au(0) { None } else { // adjust the pen.. if y_advance > Au(0) { *y_pos = *y_pos - y_advance; } Some(Point2D(x_offset, *y_pos - y_offset)) }; ShapedGlyphEntry { codepoint: (*glyph_info_i).codepoint as GlyphId, advance: x_advance, offset: offset, } } } } pub struct Shaper { hb_face: *mut hb_face_t, hb_font: *mut hb_font_t, hb_funcs: *mut hb_font_funcs_t, } #[unsafe_destructor] impl Drop for Shaper { fn drop(&mut self) { unsafe { assert!(self.hb_face.is_not_null()); hb_face_destroy(self.hb_face); assert!(self.hb_font.is_not_null()); hb_font_destroy(self.hb_font); assert!(self.hb_funcs.is_not_null()); hb_font_funcs_destroy(self.hb_funcs); } } } impl Shaper { pub fn
(font: &mut Font) -> Shaper { unsafe { // Indirection for Rust Issue #6248, dynamic freeze scope artifically extended let font_ptr = font as *mut Font; let hb_face: *mut hb_face_t = hb_face_create_for_tables(get_font_table_func, font_ptr as *mut c_void, None); let hb_font: *mut hb_font_t = hb_font_create(hb_face); // Set points-per-em. if zero, performs no hinting in that direction. let pt_size = font.actual_pt_size; hb_font_set_ppem(hb_font, pt_size as c_uint, pt_size as c_uint); // Set scaling. Note that this takes 16.16 fixed point. hb_font_set_scale(hb_font, Shaper::float_to_fixed(pt_size) as c_int, Shaper::float_to_fixed(pt_size) as c_int); // configure static function callbacks. // NB. This funcs structure could be reused globally, as it never changes. let hb_funcs: *mut hb_font_funcs_t = hb_font_funcs_create(); hb_font_funcs_set_glyph_func(hb_funcs, glyph_func, ptr::null_mut(), None); hb_font_funcs_set_glyph_h_advance_func(hb_funcs, glyph_h_advance_func, ptr::null_mut(), None); hb_font_funcs_set_glyph_h_kerning_func(hb_funcs, glyph_h_kerning_func, ptr::null_mut(), ptr::null_mut()); hb_font_set_funcs(hb_font, hb_funcs, font_ptr as *mut c_void, None); Shaper { hb_face: hb_face, hb_font: hb_font, hb_funcs: hb_funcs, } } } fn float_to_fixed(f: f64) -> i32 { float_to_fixed(16, f) } fn fixed_to_float(i: hb_position_t) -> f64 { fixed_to_float(16, i) } } impl ShaperMethods for Shaper { /// Calculate the layout metrics associated with the given text when rendered in a specific /// font. fn shape_text(&self, text: &str, glyphs: &mut GlyphStore) { unsafe { let hb_buffer: *mut hb_buffer_t = hb_buffer_create(); hb_buffer_set_direction(hb_buffer, HB_DIRECTION_LTR); hb_buffer_add_utf8(hb_buffer, text.as_ptr() as *const c_char, text.len() as c_int, 0, text.len() as c_int); hb_shape(self.hb_font, hb_buffer, ptr::null_mut(), 0); self.save_glyph_results(text, glyphs, hb_buffer); hb_buffer_destroy(hb_buffer); } } } impl Shaper { fn save_glyph_results(&self, text: &str, glyphs: &mut GlyphStore, buffer: *mut hb_buffer_t) { let glyph_data = ShapedGlyphData::new(buffer); let glyph_count = glyph_data.len(); let byte_max = text.len() as int; let char_max = text.char_len() as int; // GlyphStore records are indexed by character, not byte offset. // so, we must be careful to increment this when saving glyph entries. let mut char_idx = CharIndex(0); assert!(glyph_count <= char_max); debug!("Shaped text[char count={}], got back {} glyph info records.", char_max, glyph_count); if char_max!= glyph_count { debug!("NOTE: Since these are not equal, we probably have been given some complex \ glyphs."); } // make map of what chars have glyphs let mut byte_to_glyph: Vec<i32>; // fast path: all chars are single-byte. if byte_max == char_max { byte_to_glyph = Vec::from_elem(byte_max as uint, NO_GLYPH); } else { byte_to_glyph = Vec::from_elem(byte_max as uint, CONTINUATION_BYTE); for (i, _) in text.char_indices() { *byte_to_glyph.get_mut(i) = NO_GLYPH; } } debug!("(glyph idx) -> (text byte offset)"); for i in range(0, glyph_data.len()) { // loc refers to a *byte* offset within the utf8 string. let loc = glyph_data.byte_offset_of_glyph(i); if loc < byte_max { assert!(byte_to_glyph[loc as uint]!= CONTINUATION_BYTE); *byte_to_glyph.get_mut(loc as uint) = i as i32; } else { debug!("ERROR: tried to set out of range byte_to_glyph: idx={}, glyph idx={}", loc, i); } debug!("{} -> {}", i, loc); } debug!("text: {:s}", text); debug!("(char idx): char->(glyph index):"); for (i, ch) in text.char_indices() { debug!("{}: {} --> {:d}", i, ch, *byte_to_glyph.get(i) as int); } // some helpers let mut glyph_span: Range<int> = Range::empty(); // this span contains first byte of first char, to last byte of last char in range. // so, end() points to first byte of last+1 char, if it's less than byte_max. let mut char_byte_span: Range<int> = Range::empty(); let mut y_pos = Au(0); // main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars. // in cases with complex glyph-character assocations, 2+ glyphs and 1+ chars can be // processed. while glyph_span.begin() < glyph_count { // start by looking at just one glyph. glyph_span.extend_by(1); debug!("Processing glyph at idx={}", glyph_span.begin()); let char_byte_start = glyph_data.byte_offset_of_glyph(glyph_span.begin()); char_byte_span.reset(char_byte_start, 0); // find a range of chars corresponding to this glyph, plus // any trailing chars that do not have associated glyphs. while char_byte_span.end() < byte_max { let range = text.char_range_at(char_byte_span.end() as uint); drop(range.ch); char_byte_span.extend_to(range.next as int); debug!("Processing char byte span: off={}, len={} for glyph idx={}", char_byte_span.begin(), char_byte_span.length(), glyph_span.begin()); while char_byte_span.end()!= byte_max && byte_to_glyph[char_byte_span.end() as uint] == NO_GLYPH { debug!("Extending char byte span to include byte offset={} with no associated \ glyph", char_byte_span.end()); let range = text.char_range_at(char_byte_span.end() as uint); drop(range.ch); char_byte_span.extend_to(range.next as int); } // extend glyph range to max glyph index covered by char_span, // in cases where one char made several glyphs and left some unassociated chars. let mut max_glyph_idx = glyph_span.end(); for i in char_byte_span.each_index() { if byte_to_glyph[i as uint] > NO_GLYPH { max_glyph_idx = cmp::max(byte_to_glyph[i as uint] as int + 1, max_glyph_idx); } } if max_glyph_idx > glyph_span.end() { glyph_span.extend_to(max_glyph_idx); debug!("Extended glyph span (off={}, len={}) to cover char byte span's max \ glyph index", glyph_span.begin(), glyph_span.length()); } // if there's just one glyph, then we don't need further checks. if glyph_span.length() == 1 { break; } // if no glyphs were found yet, extend the char byte range more. if glyph_span.length() == 0 { continue; } debug!("Complex (multi-glyph to multi-char) association found. This case \ probably doesn't work."); let mut all_glyphs_are_within_cluster: bool = true; for j in glyph_span.each_index() { let loc = glyph_data.byte_offset_of_glyph(j); if!char_byte_span.contains(loc) { all_glyphs_are_within_cluster = false; break } } debug!("All glyphs within char_byte_span cluster?: {}", all_glyphs_are_within_cluster); // found a valid range; stop extending char_span. if all_glyphs_are_within_cluster { break } } // character/glyph clump must contain characters. assert!(char_byte_span.length() > 0); // character/glyph clump must contain glyphs. assert!(glyph_span.length() > 0); // now char_span is a ligature clump, formed by the glyphs in glyph_span. // we need to find the chars that correspond to actual glyphs (char_extended_span), //and set glyph info for those and empty infos for the chars that are continuations. // a simple example: // chars: 'f' 't' 't' // glyphs: 'ftt' '' '' // cgmap: t f f // gspan: [-] // cspan: [-] // covsp: [---------------] let mut covered_byte_span = char_byte_span.clone(); // extend, clipping at end of text range. while covered_byte_span.end() < byte_max && byte_to_glyph[covered_byte_span.end() as uint] == NO_GLYPH { let range = text.char_range_at(covered_byte_span.end() as uint); drop(range.ch); covered_byte_span.extend_to(range.next as int); } if covered_byte_span.begin() >= byte_max { // oops, out of range. clip and forget this clump. let end = glyph_span.end(); // FIXME: borrow checker workaround glyph_span.reset(end, 0); let end = char_byte_span.end(); // FIXME: borrow checker workaround char_byte_span.reset(end, 0); } // clamp to end of text. (I don't think this will be necessary, but..) let end = covered_byte_span.end(); // FIXME: borrow checker workaround covered_byte_span.extend_to(cmp::min(end, byte_max)); // fast path: 1-to-1 mapping of single char and single glyph. if glyph_span.length() == 1 { // TODO(Issue #214): cluster ranges need to be computed before // shaping, and then consulted here. // for now, just pretend that every character is a cluster start. // (i.e., pretend there are no combining character sequences). // 1-to-1 mapping of character to glyph also treated as ligature start. let shape = glyph_data.get_entry_for_glyph(glyph_span.begin(), &mut y_pos); let data = GlyphData::new(shape.codepoint, shape.advance, shape.offset, false, true, true); glyphs.add_glyph_for_char_index(char_idx, &data); } else { // collect all glyphs to be assigned to the first character. let mut datas = vec!(); for glyph_i in glyph_span.each_index() { let shape = glyph_data.get_entry_for_glyph(glyph_i, &mut y_pos); datas.push(GlyphData::new(shape.codepoint, shape.advance, shape.offset, false, // not missing true, // treat as cluster start glyph_i > glyph_span.begin())); // all but first are ligature continuations } // now add the detailed glyph entry. glyphs.add_glyphs_for_char_index(char_idx, datas.as_slice()); // set the other chars, who have no glyphs let mut i = covered_byte_span.begin(); loop { let range = text.char_range_at(i as uint); drop(range.ch); i = range.next as int; if i >= covered_byte_span.end() { break; } char_idx = char_idx + CharIndex(1); glyphs.add_nonglyph_for_char_index(char_idx, false, false); } } // shift up our working spans past things we just handled. let end = glyph_span.end
new
identifier_name
harfbuzz.rs
_get_glyph_infos(buffer, &mut glyph_count); let glyph_count = glyph_count as int; assert!(glyph_infos.is_not_null()); let mut pos_count = 0; let pos_infos = hb_buffer_get_glyph_positions(buffer, &mut pos_count); let pos_count = pos_count as int; assert!(pos_infos.is_not_null()); assert!(glyph_count == pos_count); ShapedGlyphData { count: glyph_count, glyph_infos: glyph_infos, pos_infos: pos_infos, } } } #[inline(always)] fn byte_offset_of_glyph(&self, i: int) -> int { assert!(i < self.count); unsafe { let glyph_info_i = self.glyph_infos.offset(i); (*glyph_info_i).cluster as int } } pub fn len(&self) -> int { self.count } /// Returns shaped glyph data for one glyph, and updates the y-position of the pen. pub fn get_entry_for_glyph(&self, i: int, y_pos: &mut Au) -> ShapedGlyphEntry { assert!(i < self.count); unsafe { let glyph_info_i = self.glyph_infos.offset(i); let pos_info_i = self.pos_infos.offset(i); let x_offset = Shaper::fixed_to_float((*pos_info_i).x_offset); let y_offset = Shaper::fixed_to_float((*pos_info_i).y_offset); let x_advance = Shaper::fixed_to_float((*pos_info_i).x_advance); let y_advance = Shaper::fixed_to_float((*pos_info_i).y_advance); let x_offset = Au::from_frac_px(x_offset); let y_offset = Au::from_frac_px(y_offset); let x_advance = Au::from_frac_px(x_advance); let y_advance = Au::from_frac_px(y_advance); let offset = if x_offset == Au(0) && y_offset == Au(0) && y_advance == Au(0) { None } else { // adjust the pen.. if y_advance > Au(0) { *y_pos = *y_pos - y_advance; } Some(Point2D(x_offset, *y_pos - y_offset)) }; ShapedGlyphEntry { codepoint: (*glyph_info_i).codepoint as GlyphId, advance: x_advance, offset: offset, } } } } pub struct Shaper { hb_face: *mut hb_face_t, hb_font: *mut hb_font_t, hb_funcs: *mut hb_font_funcs_t, } #[unsafe_destructor] impl Drop for Shaper { fn drop(&mut self) { unsafe { assert!(self.hb_face.is_not_null()); hb_face_destroy(self.hb_face); assert!(self.hb_font.is_not_null()); hb_font_destroy(self.hb_font); assert!(self.hb_funcs.is_not_null()); hb_font_funcs_destroy(self.hb_funcs); } } } impl Shaper { pub fn new(font: &mut Font) -> Shaper { unsafe { // Indirection for Rust Issue #6248, dynamic freeze scope artifically extended let font_ptr = font as *mut Font; let hb_face: *mut hb_face_t = hb_face_create_for_tables(get_font_table_func, font_ptr as *mut c_void, None); let hb_font: *mut hb_font_t = hb_font_create(hb_face); // Set points-per-em. if zero, performs no hinting in that direction. let pt_size = font.actual_pt_size; hb_font_set_ppem(hb_font, pt_size as c_uint, pt_size as c_uint); // Set scaling. Note that this takes 16.16 fixed point. hb_font_set_scale(hb_font, Shaper::float_to_fixed(pt_size) as c_int, Shaper::float_to_fixed(pt_size) as c_int); // configure static function callbacks. // NB. This funcs structure could be reused globally, as it never changes. let hb_funcs: *mut hb_font_funcs_t = hb_font_funcs_create(); hb_font_funcs_set_glyph_func(hb_funcs, glyph_func, ptr::null_mut(), None); hb_font_funcs_set_glyph_h_advance_func(hb_funcs, glyph_h_advance_func, ptr::null_mut(), None); hb_font_funcs_set_glyph_h_kerning_func(hb_funcs, glyph_h_kerning_func, ptr::null_mut(), ptr::null_mut()); hb_font_set_funcs(hb_font, hb_funcs, font_ptr as *mut c_void, None); Shaper { hb_face: hb_face, hb_font: hb_font, hb_funcs: hb_funcs, } } } fn float_to_fixed(f: f64) -> i32 { float_to_fixed(16, f) } fn fixed_to_float(i: hb_position_t) -> f64 { fixed_to_float(16, i) } } impl ShaperMethods for Shaper { /// Calculate the layout metrics associated with the given text when rendered in a specific /// font. fn shape_text(&self, text: &str, glyphs: &mut GlyphStore) { unsafe { let hb_buffer: *mut hb_buffer_t = hb_buffer_create(); hb_buffer_set_direction(hb_buffer, HB_DIRECTION_LTR); hb_buffer_add_utf8(hb_buffer, text.as_ptr() as *const c_char, text.len() as c_int, 0, text.len() as c_int); hb_shape(self.hb_font, hb_buffer, ptr::null_mut(), 0); self.save_glyph_results(text, glyphs, hb_buffer); hb_buffer_destroy(hb_buffer); } } } impl Shaper { fn save_glyph_results(&self, text: &str, glyphs: &mut GlyphStore, buffer: *mut hb_buffer_t) { let glyph_data = ShapedGlyphData::new(buffer); let glyph_count = glyph_data.len(); let byte_max = text.len() as int; let char_max = text.char_len() as int; // GlyphStore records are indexed by character, not byte offset. // so, we must be careful to increment this when saving glyph entries. let mut char_idx = CharIndex(0); assert!(glyph_count <= char_max); debug!("Shaped text[char count={}], got back {} glyph info records.", char_max, glyph_count); if char_max!= glyph_count { debug!("NOTE: Since these are not equal, we probably have been given some complex \ glyphs."); } // make map of what chars have glyphs let mut byte_to_glyph: Vec<i32>; // fast path: all chars are single-byte. if byte_max == char_max { byte_to_glyph = Vec::from_elem(byte_max as uint, NO_GLYPH); } else { byte_to_glyph = Vec::from_elem(byte_max as uint, CONTINUATION_BYTE); for (i, _) in text.char_indices() { *byte_to_glyph.get_mut(i) = NO_GLYPH; } } debug!("(glyph idx) -> (text byte offset)"); for i in range(0, glyph_data.len()) { // loc refers to a *byte* offset within the utf8 string. let loc = glyph_data.byte_offset_of_glyph(i); if loc < byte_max { assert!(byte_to_glyph[loc as uint]!= CONTINUATION_BYTE); *byte_to_glyph.get_mut(loc as uint) = i as i32; } else { debug!("ERROR: tried to set out of range byte_to_glyph: idx={}, glyph idx={}", loc, i); } debug!("{} -> {}", i, loc); } debug!("text: {:s}", text); debug!("(char idx): char->(glyph index):"); for (i, ch) in text.char_indices() { debug!("{}: {} --> {:d}", i, ch, *byte_to_glyph.get(i) as int); } // some helpers let mut glyph_span: Range<int> = Range::empty(); // this span contains first byte of first char, to last byte of last char in range. // so, end() points to first byte of last+1 char, if it's less than byte_max. let mut char_byte_span: Range<int> = Range::empty();
// processed. while glyph_span.begin() < glyph_count { // start by looking at just one glyph. glyph_span.extend_by(1); debug!("Processing glyph at idx={}", glyph_span.begin()); let char_byte_start = glyph_data.byte_offset_of_glyph(glyph_span.begin()); char_byte_span.reset(char_byte_start, 0); // find a range of chars corresponding to this glyph, plus // any trailing chars that do not have associated glyphs. while char_byte_span.end() < byte_max { let range = text.char_range_at(char_byte_span.end() as uint); drop(range.ch); char_byte_span.extend_to(range.next as int); debug!("Processing char byte span: off={}, len={} for glyph idx={}", char_byte_span.begin(), char_byte_span.length(), glyph_span.begin()); while char_byte_span.end()!= byte_max && byte_to_glyph[char_byte_span.end() as uint] == NO_GLYPH { debug!("Extending char byte span to include byte offset={} with no associated \ glyph", char_byte_span.end()); let range = text.char_range_at(char_byte_span.end() as uint); drop(range.ch); char_byte_span.extend_to(range.next as int); } // extend glyph range to max glyph index covered by char_span, // in cases where one char made several glyphs and left some unassociated chars. let mut max_glyph_idx = glyph_span.end(); for i in char_byte_span.each_index() { if byte_to_glyph[i as uint] > NO_GLYPH { max_glyph_idx = cmp::max(byte_to_glyph[i as uint] as int + 1, max_glyph_idx); } } if max_glyph_idx > glyph_span.end() { glyph_span.extend_to(max_glyph_idx); debug!("Extended glyph span (off={}, len={}) to cover char byte span's max \ glyph index", glyph_span.begin(), glyph_span.length()); } // if there's just one glyph, then we don't need further checks. if glyph_span.length() == 1 { break; } // if no glyphs were found yet, extend the char byte range more. if glyph_span.length() == 0 { continue; } debug!("Complex (multi-glyph to multi-char) association found. This case \ probably doesn't work."); let mut all_glyphs_are_within_cluster: bool = true; for j in glyph_span.each_index() { let loc = glyph_data.byte_offset_of_glyph(j); if!char_byte_span.contains(loc) { all_glyphs_are_within_cluster = false; break } } debug!("All glyphs within char_byte_span cluster?: {}", all_glyphs_are_within_cluster); // found a valid range; stop extending char_span. if all_glyphs_are_within_cluster { break } } // character/glyph clump must contain characters. assert!(char_byte_span.length() > 0); // character/glyph clump must contain glyphs. assert!(glyph_span.length() > 0); // now char_span is a ligature clump, formed by the glyphs in glyph_span. // we need to find the chars that correspond to actual glyphs (char_extended_span), //and set glyph info for those and empty infos for the chars that are continuations. // a simple example: // chars: 'f' 't' 't' // glyphs: 'ftt' '' '' // cgmap: t f f // gspan: [-] // cspan: [-] // covsp: [---------------] let mut covered_byte_span = char_byte_span.clone(); // extend, clipping at end of text range. while covered_byte_span.end() < byte_max && byte_to_glyph[covered_byte_span.end() as uint] == NO_GLYPH { let range = text.char_range_at(covered_byte_span.end() as uint); drop(range.ch); covered_byte_span.extend_to(range.next as int); } if covered_byte_span.begin() >= byte_max { // oops, out of range. clip and forget this clump. let end = glyph_span.end(); // FIXME: borrow checker workaround glyph_span.reset(end, 0); let end = char_byte_span.end(); // FIXME: borrow checker workaround char_byte_span.reset(end, 0); } // clamp to end of text. (I don't think this will be necessary, but..) let end = covered_byte_span.end(); // FIXME: borrow checker workaround covered_byte_span.extend_to(cmp::min(end, byte_max)); // fast path: 1-to-1 mapping of single char and single glyph. if glyph_span.length() == 1 { // TODO(Issue #214): cluster ranges need to be computed before // shaping, and then consulted here. // for now, just pretend that every character is a cluster start. // (i.e., pretend there are no combining character sequences). // 1-to-1 mapping of character to glyph also treated as ligature start. let shape = glyph_data.get_entry_for_glyph(glyph_span.begin(), &mut y_pos); let data = GlyphData::new(shape.codepoint, shape.advance, shape.offset, false, true, true); glyphs.add_glyph_for_char_index(char_idx, &data); } else { // collect all glyphs to be assigned to the first character. let mut datas = vec!(); for glyph_i in glyph_span.each_index() { let shape = glyph_data.get_entry_for_glyph(glyph_i, &mut y_pos); datas.push(GlyphData::new(shape.codepoint, shape.advance, shape.offset, false, // not missing true, // treat as cluster start glyph_i > glyph_span.begin())); // all but first are ligature continuations } // now add the detailed glyph entry. glyphs.add_glyphs_for_char_index(char_idx, datas.as_slice()); // set the other chars, who have no glyphs let mut i = covered_byte_span.begin(); loop { let range = text.char_range_at(i as uint); drop(range.ch); i = range.next as int; if i >= covered_byte_span.end() { break; } char_idx = char_idx + CharIndex(1); glyphs.add_nonglyph_for_char_index(char_idx, false, false); } } // shift up our working spans past things we just handled. let end = glyph_span.end(); //
let mut y_pos = Au(0); // main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars. // in cases with complex glyph-character assocations, 2+ glyphs and 1+ chars can be
random_line_split
harfbuzz.rs
get_glyph_infos(buffer, &mut glyph_count); let glyph_count = glyph_count as int; assert!(glyph_infos.is_not_null()); let mut pos_count = 0; let pos_infos = hb_buffer_get_glyph_positions(buffer, &mut pos_count); let pos_count = pos_count as int; assert!(pos_infos.is_not_null()); assert!(glyph_count == pos_count); ShapedGlyphData { count: glyph_count, glyph_infos: glyph_infos, pos_infos: pos_infos, } } } #[inline(always)] fn byte_offset_of_glyph(&self, i: int) -> int { assert!(i < self.count); unsafe { let glyph_info_i = self.glyph_infos.offset(i); (*glyph_info_i).cluster as int } } pub fn len(&self) -> int { self.count } /// Returns shaped glyph data for one glyph, and updates the y-position of the pen. pub fn get_entry_for_glyph(&self, i: int, y_pos: &mut Au) -> ShapedGlyphEntry { assert!(i < self.count); unsafe { let glyph_info_i = self.glyph_infos.offset(i); let pos_info_i = self.pos_infos.offset(i); let x_offset = Shaper::fixed_to_float((*pos_info_i).x_offset); let y_offset = Shaper::fixed_to_float((*pos_info_i).y_offset); let x_advance = Shaper::fixed_to_float((*pos_info_i).x_advance); let y_advance = Shaper::fixed_to_float((*pos_info_i).y_advance); let x_offset = Au::from_frac_px(x_offset); let y_offset = Au::from_frac_px(y_offset); let x_advance = Au::from_frac_px(x_advance); let y_advance = Au::from_frac_px(y_advance); let offset = if x_offset == Au(0) && y_offset == Au(0) && y_advance == Au(0) { None } else { // adjust the pen.. if y_advance > Au(0) { *y_pos = *y_pos - y_advance; } Some(Point2D(x_offset, *y_pos - y_offset)) }; ShapedGlyphEntry { codepoint: (*glyph_info_i).codepoint as GlyphId, advance: x_advance, offset: offset, } } } } pub struct Shaper { hb_face: *mut hb_face_t, hb_font: *mut hb_font_t, hb_funcs: *mut hb_font_funcs_t, } #[unsafe_destructor] impl Drop for Shaper { fn drop(&mut self) { unsafe { assert!(self.hb_face.is_not_null()); hb_face_destroy(self.hb_face); assert!(self.hb_font.is_not_null()); hb_font_destroy(self.hb_font); assert!(self.hb_funcs.is_not_null()); hb_font_funcs_destroy(self.hb_funcs); } } } impl Shaper { pub fn new(font: &mut Font) -> Shaper { unsafe { // Indirection for Rust Issue #6248, dynamic freeze scope artifically extended let font_ptr = font as *mut Font; let hb_face: *mut hb_face_t = hb_face_create_for_tables(get_font_table_func, font_ptr as *mut c_void, None); let hb_font: *mut hb_font_t = hb_font_create(hb_face); // Set points-per-em. if zero, performs no hinting in that direction. let pt_size = font.actual_pt_size; hb_font_set_ppem(hb_font, pt_size as c_uint, pt_size as c_uint); // Set scaling. Note that this takes 16.16 fixed point. hb_font_set_scale(hb_font, Shaper::float_to_fixed(pt_size) as c_int, Shaper::float_to_fixed(pt_size) as c_int); // configure static function callbacks. // NB. This funcs structure could be reused globally, as it never changes. let hb_funcs: *mut hb_font_funcs_t = hb_font_funcs_create(); hb_font_funcs_set_glyph_func(hb_funcs, glyph_func, ptr::null_mut(), None); hb_font_funcs_set_glyph_h_advance_func(hb_funcs, glyph_h_advance_func, ptr::null_mut(), None); hb_font_funcs_set_glyph_h_kerning_func(hb_funcs, glyph_h_kerning_func, ptr::null_mut(), ptr::null_mut()); hb_font_set_funcs(hb_font, hb_funcs, font_ptr as *mut c_void, None); Shaper { hb_face: hb_face, hb_font: hb_font, hb_funcs: hb_funcs, } } } fn float_to_fixed(f: f64) -> i32 { float_to_fixed(16, f) } fn fixed_to_float(i: hb_position_t) -> f64 { fixed_to_float(16, i) } } impl ShaperMethods for Shaper { /// Calculate the layout metrics associated with the given text when rendered in a specific /// font. fn shape_text(&self, text: &str, glyphs: &mut GlyphStore) { unsafe { let hb_buffer: *mut hb_buffer_t = hb_buffer_create(); hb_buffer_set_direction(hb_buffer, HB_DIRECTION_LTR); hb_buffer_add_utf8(hb_buffer, text.as_ptr() as *const c_char, text.len() as c_int, 0, text.len() as c_int); hb_shape(self.hb_font, hb_buffer, ptr::null_mut(), 0); self.save_glyph_results(text, glyphs, hb_buffer); hb_buffer_destroy(hb_buffer); } } } impl Shaper { fn save_glyph_results(&self, text: &str, glyphs: &mut GlyphStore, buffer: *mut hb_buffer_t) { let glyph_data = ShapedGlyphData::new(buffer); let glyph_count = glyph_data.len(); let byte_max = text.len() as int; let char_max = text.char_len() as int; // GlyphStore records are indexed by character, not byte offset. // so, we must be careful to increment this when saving glyph entries. let mut char_idx = CharIndex(0); assert!(glyph_count <= char_max); debug!("Shaped text[char count={}], got back {} glyph info records.", char_max, glyph_count); if char_max!= glyph_count { debug!("NOTE: Since these are not equal, we probably have been given some complex \ glyphs."); } // make map of what chars have glyphs let mut byte_to_glyph: Vec<i32>; // fast path: all chars are single-byte. if byte_max == char_max { byte_to_glyph = Vec::from_elem(byte_max as uint, NO_GLYPH); } else { byte_to_glyph = Vec::from_elem(byte_max as uint, CONTINUATION_BYTE); for (i, _) in text.char_indices() { *byte_to_glyph.get_mut(i) = NO_GLYPH; } } debug!("(glyph idx) -> (text byte offset)"); for i in range(0, glyph_data.len()) { // loc refers to a *byte* offset within the utf8 string. let loc = glyph_data.byte_offset_of_glyph(i); if loc < byte_max { assert!(byte_to_glyph[loc as uint]!= CONTINUATION_BYTE); *byte_to_glyph.get_mut(loc as uint) = i as i32; } else { debug!("ERROR: tried to set out of range byte_to_glyph: idx={}, glyph idx={}", loc, i); } debug!("{} -> {}", i, loc); } debug!("text: {:s}", text); debug!("(char idx): char->(glyph index):"); for (i, ch) in text.char_indices() { debug!("{}: {} --> {:d}", i, ch, *byte_to_glyph.get(i) as int); } // some helpers let mut glyph_span: Range<int> = Range::empty(); // this span contains first byte of first char, to last byte of last char in range. // so, end() points to first byte of last+1 char, if it's less than byte_max. let mut char_byte_span: Range<int> = Range::empty(); let mut y_pos = Au(0); // main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars. // in cases with complex glyph-character assocations, 2+ glyphs and 1+ chars can be // processed. while glyph_span.begin() < glyph_count { // start by looking at just one glyph. glyph_span.extend_by(1); debug!("Processing glyph at idx={}", glyph_span.begin()); let char_byte_start = glyph_data.byte_offset_of_glyph(glyph_span.begin()); char_byte_span.reset(char_byte_start, 0); // find a range of chars corresponding to this glyph, plus // any trailing chars that do not have associated glyphs. while char_byte_span.end() < byte_max { let range = text.char_range_at(char_byte_span.end() as uint); drop(range.ch); char_byte_span.extend_to(range.next as int); debug!("Processing char byte span: off={}, len={} for glyph idx={}", char_byte_span.begin(), char_byte_span.length(), glyph_span.begin()); while char_byte_span.end()!= byte_max && byte_to_glyph[char_byte_span.end() as uint] == NO_GLYPH { debug!("Extending char byte span to include byte offset={} with no associated \ glyph", char_byte_span.end()); let range = text.char_range_at(char_byte_span.end() as uint); drop(range.ch); char_byte_span.extend_to(range.next as int); } // extend glyph range to max glyph index covered by char_span, // in cases where one char made several glyphs and left some unassociated chars. let mut max_glyph_idx = glyph_span.end(); for i in char_byte_span.each_index() { if byte_to_glyph[i as uint] > NO_GLYPH { max_glyph_idx = cmp::max(byte_to_glyph[i as uint] as int + 1, max_glyph_idx); } } if max_glyph_idx > glyph_span.end() { glyph_span.extend_to(max_glyph_idx); debug!("Extended glyph span (off={}, len={}) to cover char byte span's max \ glyph index", glyph_span.begin(), glyph_span.length()); } // if there's just one glyph, then we don't need further checks. if glyph_span.length() == 1 { break; } // if no glyphs were found yet, extend the char byte range more. if glyph_span.length() == 0 { continue; } debug!("Complex (multi-glyph to multi-char) association found. This case \ probably doesn't work."); let mut all_glyphs_are_within_cluster: bool = true; for j in glyph_span.each_index() { let loc = glyph_data.byte_offset_of_glyph(j); if!char_byte_span.contains(loc) { all_glyphs_are_within_cluster = false; break } } debug!("All glyphs within char_byte_span cluster?: {}", all_glyphs_are_within_cluster); // found a valid range; stop extending char_span. if all_glyphs_are_within_cluster { break } } // character/glyph clump must contain characters. assert!(char_byte_span.length() > 0); // character/glyph clump must contain glyphs. assert!(glyph_span.length() > 0); // now char_span is a ligature clump, formed by the glyphs in glyph_span. // we need to find the chars that correspond to actual glyphs (char_extended_span), //and set glyph info for those and empty infos for the chars that are continuations. // a simple example: // chars: 'f' 't' 't' // glyphs: 'ftt' '' '' // cgmap: t f f // gspan: [-] // cspan: [-] // covsp: [---------------] let mut covered_byte_span = char_byte_span.clone(); // extend, clipping at end of text range. while covered_byte_span.end() < byte_max && byte_to_glyph[covered_byte_span.end() as uint] == NO_GLYPH { let range = text.char_range_at(covered_byte_span.end() as uint); drop(range.ch); covered_byte_span.extend_to(range.next as int); } if covered_byte_span.begin() >= byte_max { // oops, out of range. clip and forget this clump. let end = glyph_span.end(); // FIXME: borrow checker workaround glyph_span.reset(end, 0); let end = char_byte_span.end(); // FIXME: borrow checker workaround char_byte_span.reset(end, 0); } // clamp to end of text. (I don't think this will be necessary, but..) let end = covered_byte_span.end(); // FIXME: borrow checker workaround covered_byte_span.extend_to(cmp::min(end, byte_max)); // fast path: 1-to-1 mapping of single char and single glyph. if glyph_span.length() == 1 { // TODO(Issue #214): cluster ranges need to be computed before // shaping, and then consulted here. // for now, just pretend that every character is a cluster start. // (i.e., pretend there are no combining character sequences). // 1-to-1 mapping of character to glyph also treated as ligature start. let shape = glyph_data.get_entry_for_glyph(glyph_span.begin(), &mut y_pos); let data = GlyphData::new(shape.codepoint, shape.advance, shape.offset, false, true, true); glyphs.add_glyph_for_char_index(char_idx, &data); } else
loop { let range = text.char_range_at(i as uint); drop(range.ch); i = range.next as int; if i >= covered_byte_span.end() { break; } char_idx = char_idx + CharIndex(1); glyphs.add_nonglyph_for_char_index(char_idx, false, false); } } // shift up our working spans past things we just handled. let end = glyph_span.end
{ // collect all glyphs to be assigned to the first character. let mut datas = vec!(); for glyph_i in glyph_span.each_index() { let shape = glyph_data.get_entry_for_glyph(glyph_i, &mut y_pos); datas.push(GlyphData::new(shape.codepoint, shape.advance, shape.offset, false, // not missing true, // treat as cluster start glyph_i > glyph_span.begin())); // all but first are ligature continuations } // now add the detailed glyph entry. glyphs.add_glyphs_for_char_index(char_idx, datas.as_slice()); // set the other chars, who have no glyphs let mut i = covered_byte_span.begin();
conditional_block
dispatcher.rs
/* Copyright 2017 Jinjing Wang This file is part of mtcp. mtcp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. mtcp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with mtcp. If not, see <http://www.gnu.org/licenses/>. */ use std::sync::mpsc; use constant::*; use structure::socket::udp::*; use structure::socket::tcp::*; use structure::socket::packet::*; pub fn dispatch ( tun_in_receiver: TunReceiver, udp_sender: Option<mpsc::Sender<UDP>>, tcp_sender: Option<mpsc::Sender<TCP>>, )
} } } _ => {} } } } // fn skip_tun_incoming(connection: Connection) -> bool { // let tun_ip: IpAddr = IpAddr::from_str("10.0.0.1").unwrap(); // let source_ip = connection.source.ip(); // let destination_ip = connection.destination.ip(); // debug!("comparing {:#?} -> {:#?}, {:#?}", source_ip, destination_ip, tun_ip); // (source_ip == tun_ip) || (destination_ip == tun_ip); // false // }
{ while let Ok(Some(received)) = tun_in_receiver.recv() { match parse_packet(&received) { Some(Packet::UDP(udp)) => { // debug!("Dispatch UDP: {:#?}", udp.connection); match udp_sender { None => {} Some(ref sender) => { let _ = sender.send(udp); } } } Some(Packet::TCP(tcp)) => { // debug!("Dispatch TCP: {:#?}", tcp.connection); match tcp_sender { None => {} Some(ref sender) => { let _ = sender.send(tcp);
identifier_body
dispatcher.rs
/* Copyright 2017 Jinjing Wang This file is part of mtcp. mtcp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. mtcp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with mtcp. If not, see <http://www.gnu.org/licenses/>. */ use std::sync::mpsc; use constant::*; use structure::socket::udp::*; use structure::socket::tcp::*; use structure::socket::packet::*; pub fn
( tun_in_receiver: TunReceiver, udp_sender: Option<mpsc::Sender<UDP>>, tcp_sender: Option<mpsc::Sender<TCP>>, ) { while let Ok(Some(received)) = tun_in_receiver.recv() { match parse_packet(&received) { Some(Packet::UDP(udp)) => { // debug!("Dispatch UDP: {:#?}", udp.connection); match udp_sender { None => {} Some(ref sender) => { let _ = sender.send(udp); } } } Some(Packet::TCP(tcp)) => { // debug!("Dispatch TCP: {:#?}", tcp.connection); match tcp_sender { None => {} Some(ref sender) => { let _ = sender.send(tcp); } } } _ => {} } } } // fn skip_tun_incoming(connection: Connection) -> bool { // let tun_ip: IpAddr = IpAddr::from_str("10.0.0.1").unwrap(); // let source_ip = connection.source.ip(); // let destination_ip = connection.destination.ip(); // debug!("comparing {:#?} -> {:#?}, {:#?}", source_ip, destination_ip, tun_ip); // (source_ip == tun_ip) || (destination_ip == tun_ip); // false // }
dispatch
identifier_name
dispatcher.rs
/* Copyright 2017 Jinjing Wang This file is part of mtcp. mtcp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. mtcp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with mtcp. If not, see <http://www.gnu.org/licenses/>. */ use std::sync::mpsc; use constant::*; use structure::socket::udp::*; use structure::socket::tcp::*; use structure::socket::packet::*; pub fn dispatch ( tun_in_receiver: TunReceiver, udp_sender: Option<mpsc::Sender<UDP>>, tcp_sender: Option<mpsc::Sender<TCP>>, ) { while let Ok(Some(received)) = tun_in_receiver.recv() { match parse_packet(&received) { Some(Packet::UDP(udp)) => { // debug!("Dispatch UDP: {:#?}", udp.connection); match udp_sender { None => {} Some(ref sender) => { let _ = sender.send(udp); }
} } Some(Packet::TCP(tcp)) => { // debug!("Dispatch TCP: {:#?}", tcp.connection); match tcp_sender { None => {} Some(ref sender) => { let _ = sender.send(tcp); } } } _ => {} } } } // fn skip_tun_incoming(connection: Connection) -> bool { // let tun_ip: IpAddr = IpAddr::from_str("10.0.0.1").unwrap(); // let source_ip = connection.source.ip(); // let destination_ip = connection.destination.ip(); // debug!("comparing {:#?} -> {:#?}, {:#?}", source_ip, destination_ip, tun_ip); // (source_ip == tun_ip) || (destination_ip == tun_ip); // false // }
random_line_split
identity.rs
use std::ops::{Mul, MulAssign, Add, AddAssign, Div, DivAssign}; use std::marker::PhantomData; use std::cmp::{PartialOrd, Ordering}; use std::fmt; use num::{Num, Zero, One}; use num_complex::Complex; use approx::ApproxEq; use general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup, AbstractSemigroup, Operator, Inverse, AbstractGroupAbelian, SubsetOf, Additive, Multiplicative, MeetSemilattice, JoinSemilattice, Lattice}; /// A type that is equipped with identity. pub trait Identity<O: Operator> { /// The identity element. fn identity() -> Self; /// Specific identity. #[inline] fn id(_: O) -> Self where Self: Sized { Self::identity() } } impl_ident!(Additive; 0; u8, u16, u32, u64, usize, i8, i16, i32, i64, isize); impl_ident!(Additive; 0.; f32, f64); #[cfg(decimal)] impl_ident!(Additive; 0.; decimal::d128); impl_ident!(Multiplicative; 1; u8, u16, u32, u64, usize, i8, i16, i32, i64, isize); impl_ident!(Multiplicative; 1.; f32, f64); #[cfg(decimal)] impl_ident!(Multiplicative; 1.; decimal::d128); impl<N: Identity<Additive>> Identity<Additive> for Complex<N> { #[inline] fn identity() -> Self { Complex { re: N::identity(), im: N::identity() } } } impl<N: Num + Clone> Identity<Multiplicative> for Complex<N> { #[inline] fn identity() -> Self { Complex::new(N::one(), N::zero()) } } /// The universal identity element wrt. a given operator, usually noted `Id` with a /// context-dependent subscript. /// /// By default, it is the multiplicative identity element. It represents the degenerate set /// containing only the identity element of any group-like structure. It has no dimension known at /// compile-time. All its operations are no-ops. #[repr(C)] #[derive(Debug)] pub struct Id<O: Operator = Multiplicative> { _op: PhantomData<O> } impl<O: Operator> Id<O> { /// Creates a new identity element. #[inline] pub fn new() -> Id<O> { Id { _op: PhantomData } } } impl<O: Operator> Copy for Id<O> { } impl<O: Operator> Clone for Id<O> { #[inline] fn clone(&self) -> Id<O> { Id::new() } } impl<O: Operator> fmt::Display for Id<O> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Identity element") } } impl<O: Operator> PartialEq for Id<O> { #[inline] fn eq(&self, _: &Id<O>) -> bool { true } } impl<O: Operator> Eq for Id<O> { } impl<O: Operator> PartialOrd for Id<O> { #[inline] fn partial_cmp(&self, _: &Id<O>) -> Option<Ordering> { Some(Ordering::Equal) } } impl<O: Operator> Identity<O> for Id<O> { #[inline] fn identity() -> Id<O>
} impl<O: Operator> ApproxEq for Id<O> { type Epsilon = Id<O>; #[inline] fn default_epsilon() -> Self::Epsilon { Id::new() } #[inline] fn default_max_relative() -> Self::Epsilon { Id::new() } #[inline] fn default_max_ulps() -> u32 { 0 } #[inline] fn relative_eq(&self, _: &Self, _: Self::Epsilon, _: Self::Epsilon) -> bool { true } #[inline] fn ulps_eq(&self, _: &Self, _: Self::Epsilon, _: u32) -> bool { true } } /* * * Algebraic structures. * */ impl Mul<Id> for Id { type Output = Id; fn mul(self, _: Id) -> Id { self } } impl MulAssign<Id> for Id { fn mul_assign(&mut self, _: Id) { // no-op } } impl Div<Id> for Id { type Output = Id; fn div(self, _: Id) -> Id { self } } impl DivAssign<Id> for Id { fn div_assign(&mut self, _: Id) { // no-op } } impl Add<Id> for Id { type Output = Id; fn add(self, _: Id) -> Id { self } } impl AddAssign<Id> for Id { fn add_assign(&mut self, _: Id) { // no-op } } impl<O: Operator> AbstractMagma<O> for Id<O> { #[inline] fn operate(&self, _: &Self) -> Id<O> { Id::new() } } impl<O: Operator> Inverse<O> for Id<O> { #[inline] fn inverse(&self) -> Self { Id::new() } #[inline] fn inverse_mut(&mut self) { // no-op } } impl<O: Operator> AbstractSemigroup<O> for Id<O> { } impl<O: Operator> AbstractQuasigroup<O> for Id<O> { } impl<O: Operator> AbstractMonoid<O> for Id<O> { } impl<O: Operator> AbstractLoop<O> for Id<O> { } impl<O: Operator> AbstractGroup<O> for Id<O> { } impl<O: Operator> AbstractGroupAbelian<O> for Id<O> { } impl One for Id { #[inline] fn one() -> Id { Id::new() } } impl Zero for Id { #[inline] fn zero() -> Id { Id::new() } #[inline] fn is_zero(&self) -> bool { true } } /* * * Conversions. * */ impl<O: Operator, T: PartialEq + Identity<O>> SubsetOf<T> for Id<O> { #[inline] fn to_superset(&self) -> T { T::identity() } #[inline] fn is_in_subset(t: &T) -> bool { *t == T::identity() } #[inline] unsafe fn from_superset_unchecked(_: &T) -> Self { Id::new() } } impl<O: Operator> MeetSemilattice for Id<O> { #[inline] fn meet(&self, _: &Self) -> Self { Id::new() } } impl<O: Operator> JoinSemilattice for Id<O> { #[inline] fn join(&self, _: &Self) -> Self { Id::new() } } impl<O: Operator> Lattice for Id<O> { }
{ Id::new() }
identifier_body
identity.rs
use std::ops::{Mul, MulAssign, Add, AddAssign, Div, DivAssign}; use std::marker::PhantomData; use std::cmp::{PartialOrd, Ordering}; use std::fmt; use num::{Num, Zero, One}; use num_complex::Complex; use approx::ApproxEq; use general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup, AbstractSemigroup, Operator, Inverse, AbstractGroupAbelian, SubsetOf, Additive, Multiplicative, MeetSemilattice, JoinSemilattice, Lattice}; /// A type that is equipped with identity. pub trait Identity<O: Operator> { /// The identity element. fn identity() -> Self; /// Specific identity. #[inline] fn id(_: O) -> Self where Self: Sized { Self::identity() } } impl_ident!(Additive; 0; u8, u16, u32, u64, usize, i8, i16, i32, i64, isize); impl_ident!(Additive; 0.; f32, f64); #[cfg(decimal)] impl_ident!(Additive; 0.; decimal::d128); impl_ident!(Multiplicative; 1; u8, u16, u32, u64, usize, i8, i16, i32, i64, isize); impl_ident!(Multiplicative; 1.; f32, f64); #[cfg(decimal)] impl_ident!(Multiplicative; 1.; decimal::d128); impl<N: Identity<Additive>> Identity<Additive> for Complex<N> { #[inline] fn identity() -> Self { Complex { re: N::identity(), im: N::identity() } } } impl<N: Num + Clone> Identity<Multiplicative> for Complex<N> { #[inline] fn identity() -> Self { Complex::new(N::one(), N::zero()) } } /// The universal identity element wrt. a given operator, usually noted `Id` with a /// context-dependent subscript. /// /// By default, it is the multiplicative identity element. It represents the degenerate set /// containing only the identity element of any group-like structure. It has no dimension known at /// compile-time. All its operations are no-ops. #[repr(C)] #[derive(Debug)] pub struct Id<O: Operator = Multiplicative> { _op: PhantomData<O> } impl<O: Operator> Id<O> { /// Creates a new identity element. #[inline] pub fn new() -> Id<O> { Id { _op: PhantomData } } } impl<O: Operator> Copy for Id<O> { } impl<O: Operator> Clone for Id<O> { #[inline] fn clone(&self) -> Id<O> { Id::new() } } impl<O: Operator> fmt::Display for Id<O> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Identity element") } } impl<O: Operator> PartialEq for Id<O> { #[inline] fn eq(&self, _: &Id<O>) -> bool { true } } impl<O: Operator> Eq for Id<O> { } impl<O: Operator> PartialOrd for Id<O> { #[inline] fn partial_cmp(&self, _: &Id<O>) -> Option<Ordering> { Some(Ordering::Equal) } } impl<O: Operator> Identity<O> for Id<O> { #[inline] fn identity() -> Id<O> { Id::new() } } impl<O: Operator> ApproxEq for Id<O> { type Epsilon = Id<O>; #[inline] fn default_epsilon() -> Self::Epsilon { Id::new() } #[inline] fn default_max_relative() -> Self::Epsilon { Id::new() } #[inline] fn default_max_ulps() -> u32 { 0 } #[inline] fn
(&self, _: &Self, _: Self::Epsilon, _: Self::Epsilon) -> bool { true } #[inline] fn ulps_eq(&self, _: &Self, _: Self::Epsilon, _: u32) -> bool { true } } /* * * Algebraic structures. * */ impl Mul<Id> for Id { type Output = Id; fn mul(self, _: Id) -> Id { self } } impl MulAssign<Id> for Id { fn mul_assign(&mut self, _: Id) { // no-op } } impl Div<Id> for Id { type Output = Id; fn div(self, _: Id) -> Id { self } } impl DivAssign<Id> for Id { fn div_assign(&mut self, _: Id) { // no-op } } impl Add<Id> for Id { type Output = Id; fn add(self, _: Id) -> Id { self } } impl AddAssign<Id> for Id { fn add_assign(&mut self, _: Id) { // no-op } } impl<O: Operator> AbstractMagma<O> for Id<O> { #[inline] fn operate(&self, _: &Self) -> Id<O> { Id::new() } } impl<O: Operator> Inverse<O> for Id<O> { #[inline] fn inverse(&self) -> Self { Id::new() } #[inline] fn inverse_mut(&mut self) { // no-op } } impl<O: Operator> AbstractSemigroup<O> for Id<O> { } impl<O: Operator> AbstractQuasigroup<O> for Id<O> { } impl<O: Operator> AbstractMonoid<O> for Id<O> { } impl<O: Operator> AbstractLoop<O> for Id<O> { } impl<O: Operator> AbstractGroup<O> for Id<O> { } impl<O: Operator> AbstractGroupAbelian<O> for Id<O> { } impl One for Id { #[inline] fn one() -> Id { Id::new() } } impl Zero for Id { #[inline] fn zero() -> Id { Id::new() } #[inline] fn is_zero(&self) -> bool { true } } /* * * Conversions. * */ impl<O: Operator, T: PartialEq + Identity<O>> SubsetOf<T> for Id<O> { #[inline] fn to_superset(&self) -> T { T::identity() } #[inline] fn is_in_subset(t: &T) -> bool { *t == T::identity() } #[inline] unsafe fn from_superset_unchecked(_: &T) -> Self { Id::new() } } impl<O: Operator> MeetSemilattice for Id<O> { #[inline] fn meet(&self, _: &Self) -> Self { Id::new() } } impl<O: Operator> JoinSemilattice for Id<O> { #[inline] fn join(&self, _: &Self) -> Self { Id::new() } } impl<O: Operator> Lattice for Id<O> { }
relative_eq
identifier_name
identity.rs
use std::ops::{Mul, MulAssign, Add, AddAssign, Div, DivAssign}; use std::marker::PhantomData; use std::cmp::{PartialOrd, Ordering}; use std::fmt; use num::{Num, Zero, One}; use num_complex::Complex; use approx::ApproxEq; use general::{AbstractMagma, AbstractGroup, AbstractLoop, AbstractMonoid, AbstractQuasigroup, AbstractSemigroup, Operator, Inverse, AbstractGroupAbelian, SubsetOf, Additive, Multiplicative, MeetSemilattice, JoinSemilattice, Lattice}; /// A type that is equipped with identity. pub trait Identity<O: Operator> { /// The identity element. fn identity() -> Self; /// Specific identity. #[inline] fn id(_: O) -> Self where Self: Sized { Self::identity() } } impl_ident!(Additive; 0; u8, u16, u32, u64, usize, i8, i16, i32, i64, isize); impl_ident!(Additive; 0.; f32, f64); #[cfg(decimal)] impl_ident!(Additive; 0.; decimal::d128); impl_ident!(Multiplicative; 1; u8, u16, u32, u64, usize, i8, i16, i32, i64, isize); impl_ident!(Multiplicative; 1.; f32, f64); #[cfg(decimal)] impl_ident!(Multiplicative; 1.; decimal::d128); impl<N: Identity<Additive>> Identity<Additive> for Complex<N> { #[inline] fn identity() -> Self { Complex { re: N::identity(), im: N::identity() } } } impl<N: Num + Clone> Identity<Multiplicative> for Complex<N> { #[inline] fn identity() -> Self { Complex::new(N::one(), N::zero()) } } /// The universal identity element wrt. a given operator, usually noted `Id` with a /// context-dependent subscript. /// /// By default, it is the multiplicative identity element. It represents the degenerate set /// containing only the identity element of any group-like structure. It has no dimension known at /// compile-time. All its operations are no-ops. #[repr(C)] #[derive(Debug)] pub struct Id<O: Operator = Multiplicative> { _op: PhantomData<O> } impl<O: Operator> Id<O> { /// Creates a new identity element. #[inline] pub fn new() -> Id<O> { Id { _op: PhantomData } } } impl<O: Operator> Copy for Id<O> { } impl<O: Operator> Clone for Id<O> { #[inline] fn clone(&self) -> Id<O> { Id::new() } } impl<O: Operator> fmt::Display for Id<O> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Identity element") } } impl<O: Operator> PartialEq for Id<O> { #[inline] fn eq(&self, _: &Id<O>) -> bool { true } } impl<O: Operator> Eq for Id<O> { } impl<O: Operator> PartialOrd for Id<O> { #[inline] fn partial_cmp(&self, _: &Id<O>) -> Option<Ordering> { Some(Ordering::Equal) } } impl<O: Operator> Identity<O> for Id<O> { #[inline] fn identity() -> Id<O> { Id::new() } } impl<O: Operator> ApproxEq for Id<O> { type Epsilon = Id<O>; #[inline] fn default_epsilon() -> Self::Epsilon { Id::new() } #[inline] fn default_max_relative() -> Self::Epsilon { Id::new() } #[inline] fn default_max_ulps() -> u32 { 0 } #[inline] fn relative_eq(&self, _: &Self, _: Self::Epsilon, _: Self::Epsilon) -> bool { true } #[inline] fn ulps_eq(&self, _: &Self, _: Self::Epsilon, _: u32) -> bool { true } } /* * * Algebraic structures. * */ impl Mul<Id> for Id { type Output = Id; fn mul(self, _: Id) -> Id { self } } impl MulAssign<Id> for Id { fn mul_assign(&mut self, _: Id) { // no-op } } impl Div<Id> for Id { type Output = Id; fn div(self, _: Id) -> Id { self } } impl DivAssign<Id> for Id { fn div_assign(&mut self, _: Id) { // no-op } } impl Add<Id> for Id { type Output = Id; fn add(self, _: Id) -> Id { self } }
// no-op } } impl<O: Operator> AbstractMagma<O> for Id<O> { #[inline] fn operate(&self, _: &Self) -> Id<O> { Id::new() } } impl<O: Operator> Inverse<O> for Id<O> { #[inline] fn inverse(&self) -> Self { Id::new() } #[inline] fn inverse_mut(&mut self) { // no-op } } impl<O: Operator> AbstractSemigroup<O> for Id<O> { } impl<O: Operator> AbstractQuasigroup<O> for Id<O> { } impl<O: Operator> AbstractMonoid<O> for Id<O> { } impl<O: Operator> AbstractLoop<O> for Id<O> { } impl<O: Operator> AbstractGroup<O> for Id<O> { } impl<O: Operator> AbstractGroupAbelian<O> for Id<O> { } impl One for Id { #[inline] fn one() -> Id { Id::new() } } impl Zero for Id { #[inline] fn zero() -> Id { Id::new() } #[inline] fn is_zero(&self) -> bool { true } } /* * * Conversions. * */ impl<O: Operator, T: PartialEq + Identity<O>> SubsetOf<T> for Id<O> { #[inline] fn to_superset(&self) -> T { T::identity() } #[inline] fn is_in_subset(t: &T) -> bool { *t == T::identity() } #[inline] unsafe fn from_superset_unchecked(_: &T) -> Self { Id::new() } } impl<O: Operator> MeetSemilattice for Id<O> { #[inline] fn meet(&self, _: &Self) -> Self { Id::new() } } impl<O: Operator> JoinSemilattice for Id<O> { #[inline] fn join(&self, _: &Self) -> Self { Id::new() } } impl<O: Operator> Lattice for Id<O> { }
impl AddAssign<Id> for Id { fn add_assign(&mut self, _: Id) {
random_line_split
125.rs
/// Quickest to just calculate sequences of squares less than the specified /// limit and determine if they are palindromic. /// /// The highest value needed to be calculated is 10^4, since 10^4*10^2 = 10^8. use std::collections::HashSet; fn is_palindrome(n: u64) -> bool { let mut nn = n; if n % 10 == 0 { false } else { let mut r = 0; while r < nn { r = 10 * r + nn % 10; nn /= 10; } nn == r || nn == r / 10 } } // Minor problem with something here fn
() { let mut seen = HashSet::new(); let mut total_sum = 0_u64; // Compute sequences from the specified start point 'outer: for n in 1..100_000 { let mut sum = n * n; for i in (n+1).. { // sequence must be at least length two sum += i * i; if sum >= 100_000_000 { continue 'outer; } if is_palindrome(sum) &&!seen.contains(&sum) { total_sum += sum; seen.insert(sum); } } } println!("{}", total_sum); }
main
identifier_name
125.rs
/// Quickest to just calculate sequences of squares less than the specified /// limit and determine if they are palindromic. /// /// The highest value needed to be calculated is 10^4, since 10^4*10^2 = 10^8. use std::collections::HashSet; fn is_palindrome(n: u64) -> bool { let mut nn = n; if n % 10 == 0 { false } else { let mut r = 0; while r < nn { r = 10 * r + nn % 10; nn /= 10; } nn == r || nn == r / 10 } } // Minor problem with something here fn main() { let mut seen = HashSet::new(); let mut total_sum = 0_u64; // Compute sequences from the specified start point 'outer: for n in 1..100_000 { let mut sum = n * n; for i in (n+1).. { // sequence must be at least length two sum += i * i; if sum >= 100_000_000 { continue 'outer; } if is_palindrome(sum) &&!seen.contains(&sum)
} } println!("{}", total_sum); }
{ total_sum += sum; seen.insert(sum); }
conditional_block
125.rs
/// Quickest to just calculate sequences of squares less than the specified /// limit and determine if they are palindromic. /// /// The highest value needed to be calculated is 10^4, since 10^4*10^2 = 10^8. use std::collections::HashSet; fn is_palindrome(n: u64) -> bool { let mut nn = n; if n % 10 == 0 { false } else { let mut r = 0; while r < nn { r = 10 * r + nn % 10; nn /= 10; } nn == r || nn == r / 10 } }
let mut seen = HashSet::new(); let mut total_sum = 0_u64; // Compute sequences from the specified start point 'outer: for n in 1..100_000 { let mut sum = n * n; for i in (n+1).. { // sequence must be at least length two sum += i * i; if sum >= 100_000_000 { continue 'outer; } if is_palindrome(sum) &&!seen.contains(&sum) { total_sum += sum; seen.insert(sum); } } } println!("{}", total_sum); }
// Minor problem with something here fn main() {
random_line_split
125.rs
/// Quickest to just calculate sequences of squares less than the specified /// limit and determine if they are palindromic. /// /// The highest value needed to be calculated is 10^4, since 10^4*10^2 = 10^8. use std::collections::HashSet; fn is_palindrome(n: u64) -> bool
// Minor problem with something here fn main() { let mut seen = HashSet::new(); let mut total_sum = 0_u64; // Compute sequences from the specified start point 'outer: for n in 1..100_000 { let mut sum = n * n; for i in (n+1).. { // sequence must be at least length two sum += i * i; if sum >= 100_000_000 { continue 'outer; } if is_palindrome(sum) &&!seen.contains(&sum) { total_sum += sum; seen.insert(sum); } } } println!("{}", total_sum); }
{ let mut nn = n; if n % 10 == 0 { false } else { let mut r = 0; while r < nn { r = 10 * r + nn % 10; nn /= 10; } nn == r || nn == r / 10 } }
identifier_body
decoding.rs
use serde::de::DeserializeOwned; use crate::algorithms::AlgorithmFamily; use crate::crypto::verify; use crate::errors::{new_error, ErrorKind, Result}; use crate::header::Header; #[cfg(feature = "use_pem")] use crate::pem::decoder::PemEncodedKey; use crate::serialization::{b64_decode, DecodedJwtPartClaims}; use crate::validation::{validate, Validation}; /// The return type of a successful call to [decode](fn.decode.html). #[derive(Debug)] pub struct
<T> { /// The decoded JWT header pub header: Header, /// The decoded JWT claims pub claims: T, } /// Takes the result of a rsplit and ensure we only get 2 parts /// Errors if we don't macro_rules! expect_two { ($iter:expr) => {{ let mut i = $iter; match (i.next(), i.next(), i.next()) { (Some(first), Some(second), None) => (first, second), _ => return Err(new_error(ErrorKind::InvalidToken)), } }}; } #[derive(Clone)] pub(crate) enum DecodingKeyKind { SecretOrDer(Vec<u8>), RsaModulusExponent { n: Vec<u8>, e: Vec<u8> }, } /// All the different kind of keys we can use to decode a JWT /// This key can be re-used so make sure you only initialize it once if you can for better performance #[derive(Clone)] pub struct DecodingKey { pub(crate) family: AlgorithmFamily, pub(crate) kind: DecodingKeyKind, } impl DecodingKey { /// If you're using HMAC, use this. pub fn from_secret(secret: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Hmac, kind: DecodingKeyKind::SecretOrDer(secret.to_vec()), } } /// If you're using HMAC with a base64 encoded secret, use this. pub fn from_base64_secret(secret: &str) -> Result<Self> { let out = base64::decode(&secret)?; Ok(DecodingKey { family: AlgorithmFamily::Hmac, kind: DecodingKeyKind::SecretOrDer(out) }) } /// If you are loading a public RSA key in a PEM format, use this. /// Only exists if the feature `use_pem` is enabled. #[cfg(feature = "use_pem")] pub fn from_rsa_pem(key: &[u8]) -> Result<Self> { let pem_key = PemEncodedKey::new(key)?; let content = pem_key.as_rsa_key()?; Ok(DecodingKey { family: AlgorithmFamily::Rsa, kind: DecodingKeyKind::SecretOrDer(content.to_vec()), }) } /// If you have (n, e) RSA public key components as strings, use this. pub fn from_rsa_components(modulus: &str, exponent: &str) -> Result<Self> { let n = b64_decode(modulus)?; let e = b64_decode(exponent)?; Ok(DecodingKey { family: AlgorithmFamily::Rsa, kind: DecodingKeyKind::RsaModulusExponent { n, e }, }) } /// If you have (n, e) RSA public key components already decoded, use this. pub fn from_rsa_raw_components(modulus: &[u8], exponent: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Rsa, kind: DecodingKeyKind::RsaModulusExponent { n: modulus.to_vec(), e: exponent.to_vec() }, } } /// If you have a ECDSA public key in PEM format, use this. /// Only exists if the feature `use_pem` is enabled. #[cfg(feature = "use_pem")] pub fn from_ec_pem(key: &[u8]) -> Result<Self> { let pem_key = PemEncodedKey::new(key)?; let content = pem_key.as_ec_public_key()?; Ok(DecodingKey { family: AlgorithmFamily::Ec, kind: DecodingKeyKind::SecretOrDer(content.to_vec()), }) } /// If you have a EdDSA public key in PEM format, use this. /// Only exists if the feature `use_pem` is enabled. #[cfg(feature = "use_pem")] pub fn from_ed_pem(key: &[u8]) -> Result<Self> { let pem_key = PemEncodedKey::new(key)?; let content = pem_key.as_ed_public_key()?; Ok(DecodingKey { family: AlgorithmFamily::Ed, kind: DecodingKeyKind::SecretOrDer(content.to_vec()), }) } /// If you know what you're doing and have a RSA DER encoded public key, use this. pub fn from_rsa_der(der: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Rsa, kind: DecodingKeyKind::SecretOrDer(der.to_vec()), } } /// If you know what you're doing and have a RSA EC encoded public key, use this. pub fn from_ec_der(der: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Ec, kind: DecodingKeyKind::SecretOrDer(der.to_vec()), } } /// If you know what you're doing and have a Ed DER encoded public key, use this. pub fn from_ed_der(der: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Ed, kind: DecodingKeyKind::SecretOrDer(der.to_vec()), } } pub(crate) fn as_bytes(&self) -> &[u8] { match &self.kind { DecodingKeyKind::SecretOrDer(b) => b, DecodingKeyKind::RsaModulusExponent {.. } => unreachable!(), } } } /// Verify signature of a JWT, and return header object and raw payload /// /// If the token or its signature is invalid, it will return an error. fn verify_signature<'a>( token: &'a str, key: &DecodingKey, validation: &Validation, ) -> Result<(Header, &'a str)> { if validation.validate_signature && validation.algorithms.is_empty() { return Err(new_error(ErrorKind::MissingAlgorithm)); } if validation.validate_signature { for alg in &validation.algorithms { if key.family!= alg.family() { return Err(new_error(ErrorKind::InvalidAlgorithm)); } } } let (signature, message) = expect_two!(token.rsplitn(2, '.')); let (payload, header) = expect_two!(message.rsplitn(2, '.')); let header = Header::from_encoded(header)?; if validation.validate_signature &&!validation.algorithms.contains(&header.alg) { return Err(new_error(ErrorKind::InvalidAlgorithm)); } if validation.validate_signature &&!verify(signature, message.as_bytes(), key, header.alg)? { return Err(new_error(ErrorKind::InvalidSignature)); } Ok((header, payload)) } /// Decode and validate a JWT /// /// If the token or its signature is invalid or the claims fail validation, it will return an error. /// /// ```rust /// use serde::{Deserialize, Serialize}; /// use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm}; /// /// #[derive(Debug, Serialize, Deserialize)] /// struct Claims { /// sub: String, /// company: String /// } /// /// let token = "a.jwt.token".to_string(); /// // Claims is a struct that implements Deserialize /// let token_message = decode::<Claims>(&token, &DecodingKey::from_secret("secret".as_ref()), &Validation::new(Algorithm::HS256)); /// ``` pub fn decode<T: DeserializeOwned>( token: &str, key: &DecodingKey, validation: &Validation, ) -> Result<TokenData<T>> { match verify_signature(token, key, validation) { Err(e) => Err(e), Ok((header, claims)) => { let decoded_claims = DecodedJwtPartClaims::from_jwt_part_claims(claims)?; let claims = decoded_claims.deserialize()?; validate(decoded_claims.deserialize()?, validation)?; Ok(TokenData { header, claims }) } } } /// Decode a JWT without any signature verification/validations and return its [Header](struct.Header.html). /// /// If the token has an invalid format (ie 3 parts separated by a `.`), it will return an error. /// /// ```rust /// use jsonwebtoken::decode_header; /// /// let token = "a.jwt.token".to_string(); /// let header = decode_header(&token); /// ``` pub fn decode_header(token: &str) -> Result<Header> { let (_, message) = expect_two!(token.rsplitn(2, '.')); let (_, header) = expect_two!(message.rsplitn(2, '.')); Header::from_encoded(header) }
TokenData
identifier_name
decoding.rs
use serde::de::DeserializeOwned; use crate::algorithms::AlgorithmFamily; use crate::crypto::verify; use crate::errors::{new_error, ErrorKind, Result}; use crate::header::Header; #[cfg(feature = "use_pem")] use crate::pem::decoder::PemEncodedKey; use crate::serialization::{b64_decode, DecodedJwtPartClaims}; use crate::validation::{validate, Validation}; /// The return type of a successful call to [decode](fn.decode.html). #[derive(Debug)] pub struct TokenData<T> { /// The decoded JWT header pub header: Header, /// The decoded JWT claims pub claims: T, } /// Takes the result of a rsplit and ensure we only get 2 parts /// Errors if we don't macro_rules! expect_two { ($iter:expr) => {{ let mut i = $iter; match (i.next(), i.next(), i.next()) { (Some(first), Some(second), None) => (first, second), _ => return Err(new_error(ErrorKind::InvalidToken)), } }}; } #[derive(Clone)] pub(crate) enum DecodingKeyKind { SecretOrDer(Vec<u8>), RsaModulusExponent { n: Vec<u8>, e: Vec<u8> }, } /// All the different kind of keys we can use to decode a JWT /// This key can be re-used so make sure you only initialize it once if you can for better performance #[derive(Clone)] pub struct DecodingKey { pub(crate) family: AlgorithmFamily, pub(crate) kind: DecodingKeyKind, } impl DecodingKey { /// If you're using HMAC, use this. pub fn from_secret(secret: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Hmac, kind: DecodingKeyKind::SecretOrDer(secret.to_vec()), } } /// If you're using HMAC with a base64 encoded secret, use this. pub fn from_base64_secret(secret: &str) -> Result<Self> { let out = base64::decode(&secret)?; Ok(DecodingKey { family: AlgorithmFamily::Hmac, kind: DecodingKeyKind::SecretOrDer(out) }) } /// If you are loading a public RSA key in a PEM format, use this. /// Only exists if the feature `use_pem` is enabled. #[cfg(feature = "use_pem")] pub fn from_rsa_pem(key: &[u8]) -> Result<Self> { let pem_key = PemEncodedKey::new(key)?; let content = pem_key.as_rsa_key()?; Ok(DecodingKey { family: AlgorithmFamily::Rsa, kind: DecodingKeyKind::SecretOrDer(content.to_vec()), }) } /// If you have (n, e) RSA public key components as strings, use this. pub fn from_rsa_components(modulus: &str, exponent: &str) -> Result<Self> { let n = b64_decode(modulus)?; let e = b64_decode(exponent)?; Ok(DecodingKey { family: AlgorithmFamily::Rsa, kind: DecodingKeyKind::RsaModulusExponent { n, e }, }) } /// If you have (n, e) RSA public key components already decoded, use this. pub fn from_rsa_raw_components(modulus: &[u8], exponent: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Rsa, kind: DecodingKeyKind::RsaModulusExponent { n: modulus.to_vec(), e: exponent.to_vec() }, } } /// If you have a ECDSA public key in PEM format, use this. /// Only exists if the feature `use_pem` is enabled. #[cfg(feature = "use_pem")] pub fn from_ec_pem(key: &[u8]) -> Result<Self> { let pem_key = PemEncodedKey::new(key)?; let content = pem_key.as_ec_public_key()?; Ok(DecodingKey { family: AlgorithmFamily::Ec, kind: DecodingKeyKind::SecretOrDer(content.to_vec()), }) } /// If you have a EdDSA public key in PEM format, use this. /// Only exists if the feature `use_pem` is enabled. #[cfg(feature = "use_pem")] pub fn from_ed_pem(key: &[u8]) -> Result<Self> { let pem_key = PemEncodedKey::new(key)?; let content = pem_key.as_ed_public_key()?; Ok(DecodingKey { family: AlgorithmFamily::Ed, kind: DecodingKeyKind::SecretOrDer(content.to_vec()), }) } /// If you know what you're doing and have a RSA DER encoded public key, use this. pub fn from_rsa_der(der: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Rsa, kind: DecodingKeyKind::SecretOrDer(der.to_vec()), } } /// If you know what you're doing and have a RSA EC encoded public key, use this. pub fn from_ec_der(der: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Ec, kind: DecodingKeyKind::SecretOrDer(der.to_vec()), } } /// If you know what you're doing and have a Ed DER encoded public key, use this. pub fn from_ed_der(der: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Ed, kind: DecodingKeyKind::SecretOrDer(der.to_vec()), } } pub(crate) fn as_bytes(&self) -> &[u8] { match &self.kind { DecodingKeyKind::SecretOrDer(b) => b, DecodingKeyKind::RsaModulusExponent {.. } => unreachable!(), } } } /// Verify signature of a JWT, and return header object and raw payload /// /// If the token or its signature is invalid, it will return an error. fn verify_signature<'a>( token: &'a str, key: &DecodingKey, validation: &Validation, ) -> Result<(Header, &'a str)> { if validation.validate_signature && validation.algorithms.is_empty() { return Err(new_error(ErrorKind::MissingAlgorithm)); } if validation.validate_signature { for alg in &validation.algorithms { if key.family!= alg.family() { return Err(new_error(ErrorKind::InvalidAlgorithm)); } } } let (signature, message) = expect_two!(token.rsplitn(2, '.')); let (payload, header) = expect_two!(message.rsplitn(2, '.')); let header = Header::from_encoded(header)?; if validation.validate_signature &&!validation.algorithms.contains(&header.alg) { return Err(new_error(ErrorKind::InvalidAlgorithm)); } if validation.validate_signature &&!verify(signature, message.as_bytes(), key, header.alg)? { return Err(new_error(ErrorKind::InvalidSignature)); } Ok((header, payload)) } /// Decode and validate a JWT /// /// If the token or its signature is invalid or the claims fail validation, it will return an error. /// /// ```rust /// use serde::{Deserialize, Serialize}; /// use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm}; /// /// #[derive(Debug, Serialize, Deserialize)] /// struct Claims { /// sub: String, /// company: String /// } ///
/// let token_message = decode::<Claims>(&token, &DecodingKey::from_secret("secret".as_ref()), &Validation::new(Algorithm::HS256)); /// ``` pub fn decode<T: DeserializeOwned>( token: &str, key: &DecodingKey, validation: &Validation, ) -> Result<TokenData<T>> { match verify_signature(token, key, validation) { Err(e) => Err(e), Ok((header, claims)) => { let decoded_claims = DecodedJwtPartClaims::from_jwt_part_claims(claims)?; let claims = decoded_claims.deserialize()?; validate(decoded_claims.deserialize()?, validation)?; Ok(TokenData { header, claims }) } } } /// Decode a JWT without any signature verification/validations and return its [Header](struct.Header.html). /// /// If the token has an invalid format (ie 3 parts separated by a `.`), it will return an error. /// /// ```rust /// use jsonwebtoken::decode_header; /// /// let token = "a.jwt.token".to_string(); /// let header = decode_header(&token); /// ``` pub fn decode_header(token: &str) -> Result<Header> { let (_, message) = expect_two!(token.rsplitn(2, '.')); let (_, header) = expect_two!(message.rsplitn(2, '.')); Header::from_encoded(header) }
/// let token = "a.jwt.token".to_string(); /// // Claims is a struct that implements Deserialize
random_line_split
decoding.rs
use serde::de::DeserializeOwned; use crate::algorithms::AlgorithmFamily; use crate::crypto::verify; use crate::errors::{new_error, ErrorKind, Result}; use crate::header::Header; #[cfg(feature = "use_pem")] use crate::pem::decoder::PemEncodedKey; use crate::serialization::{b64_decode, DecodedJwtPartClaims}; use crate::validation::{validate, Validation}; /// The return type of a successful call to [decode](fn.decode.html). #[derive(Debug)] pub struct TokenData<T> { /// The decoded JWT header pub header: Header, /// The decoded JWT claims pub claims: T, } /// Takes the result of a rsplit and ensure we only get 2 parts /// Errors if we don't macro_rules! expect_two { ($iter:expr) => {{ let mut i = $iter; match (i.next(), i.next(), i.next()) { (Some(first), Some(second), None) => (first, second), _ => return Err(new_error(ErrorKind::InvalidToken)), } }}; } #[derive(Clone)] pub(crate) enum DecodingKeyKind { SecretOrDer(Vec<u8>), RsaModulusExponent { n: Vec<u8>, e: Vec<u8> }, } /// All the different kind of keys we can use to decode a JWT /// This key can be re-used so make sure you only initialize it once if you can for better performance #[derive(Clone)] pub struct DecodingKey { pub(crate) family: AlgorithmFamily, pub(crate) kind: DecodingKeyKind, } impl DecodingKey { /// If you're using HMAC, use this. pub fn from_secret(secret: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Hmac, kind: DecodingKeyKind::SecretOrDer(secret.to_vec()), } } /// If you're using HMAC with a base64 encoded secret, use this. pub fn from_base64_secret(secret: &str) -> Result<Self> { let out = base64::decode(&secret)?; Ok(DecodingKey { family: AlgorithmFamily::Hmac, kind: DecodingKeyKind::SecretOrDer(out) }) } /// If you are loading a public RSA key in a PEM format, use this. /// Only exists if the feature `use_pem` is enabled. #[cfg(feature = "use_pem")] pub fn from_rsa_pem(key: &[u8]) -> Result<Self> { let pem_key = PemEncodedKey::new(key)?; let content = pem_key.as_rsa_key()?; Ok(DecodingKey { family: AlgorithmFamily::Rsa, kind: DecodingKeyKind::SecretOrDer(content.to_vec()), }) } /// If you have (n, e) RSA public key components as strings, use this. pub fn from_rsa_components(modulus: &str, exponent: &str) -> Result<Self> { let n = b64_decode(modulus)?; let e = b64_decode(exponent)?; Ok(DecodingKey { family: AlgorithmFamily::Rsa, kind: DecodingKeyKind::RsaModulusExponent { n, e }, }) } /// If you have (n, e) RSA public key components already decoded, use this. pub fn from_rsa_raw_components(modulus: &[u8], exponent: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Rsa, kind: DecodingKeyKind::RsaModulusExponent { n: modulus.to_vec(), e: exponent.to_vec() }, } } /// If you have a ECDSA public key in PEM format, use this. /// Only exists if the feature `use_pem` is enabled. #[cfg(feature = "use_pem")] pub fn from_ec_pem(key: &[u8]) -> Result<Self> { let pem_key = PemEncodedKey::new(key)?; let content = pem_key.as_ec_public_key()?; Ok(DecodingKey { family: AlgorithmFamily::Ec, kind: DecodingKeyKind::SecretOrDer(content.to_vec()), }) } /// If you have a EdDSA public key in PEM format, use this. /// Only exists if the feature `use_pem` is enabled. #[cfg(feature = "use_pem")] pub fn from_ed_pem(key: &[u8]) -> Result<Self> { let pem_key = PemEncodedKey::new(key)?; let content = pem_key.as_ed_public_key()?; Ok(DecodingKey { family: AlgorithmFamily::Ed, kind: DecodingKeyKind::SecretOrDer(content.to_vec()), }) } /// If you know what you're doing and have a RSA DER encoded public key, use this. pub fn from_rsa_der(der: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Rsa, kind: DecodingKeyKind::SecretOrDer(der.to_vec()), } } /// If you know what you're doing and have a RSA EC encoded public key, use this. pub fn from_ec_der(der: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Ec, kind: DecodingKeyKind::SecretOrDer(der.to_vec()), } } /// If you know what you're doing and have a Ed DER encoded public key, use this. pub fn from_ed_der(der: &[u8]) -> Self { DecodingKey { family: AlgorithmFamily::Ed, kind: DecodingKeyKind::SecretOrDer(der.to_vec()), } } pub(crate) fn as_bytes(&self) -> &[u8]
} /// Verify signature of a JWT, and return header object and raw payload /// /// If the token or its signature is invalid, it will return an error. fn verify_signature<'a>( token: &'a str, key: &DecodingKey, validation: &Validation, ) -> Result<(Header, &'a str)> { if validation.validate_signature && validation.algorithms.is_empty() { return Err(new_error(ErrorKind::MissingAlgorithm)); } if validation.validate_signature { for alg in &validation.algorithms { if key.family!= alg.family() { return Err(new_error(ErrorKind::InvalidAlgorithm)); } } } let (signature, message) = expect_two!(token.rsplitn(2, '.')); let (payload, header) = expect_two!(message.rsplitn(2, '.')); let header = Header::from_encoded(header)?; if validation.validate_signature &&!validation.algorithms.contains(&header.alg) { return Err(new_error(ErrorKind::InvalidAlgorithm)); } if validation.validate_signature &&!verify(signature, message.as_bytes(), key, header.alg)? { return Err(new_error(ErrorKind::InvalidSignature)); } Ok((header, payload)) } /// Decode and validate a JWT /// /// If the token or its signature is invalid or the claims fail validation, it will return an error. /// /// ```rust /// use serde::{Deserialize, Serialize}; /// use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm}; /// /// #[derive(Debug, Serialize, Deserialize)] /// struct Claims { /// sub: String, /// company: String /// } /// /// let token = "a.jwt.token".to_string(); /// // Claims is a struct that implements Deserialize /// let token_message = decode::<Claims>(&token, &DecodingKey::from_secret("secret".as_ref()), &Validation::new(Algorithm::HS256)); /// ``` pub fn decode<T: DeserializeOwned>( token: &str, key: &DecodingKey, validation: &Validation, ) -> Result<TokenData<T>> { match verify_signature(token, key, validation) { Err(e) => Err(e), Ok((header, claims)) => { let decoded_claims = DecodedJwtPartClaims::from_jwt_part_claims(claims)?; let claims = decoded_claims.deserialize()?; validate(decoded_claims.deserialize()?, validation)?; Ok(TokenData { header, claims }) } } } /// Decode a JWT without any signature verification/validations and return its [Header](struct.Header.html). /// /// If the token has an invalid format (ie 3 parts separated by a `.`), it will return an error. /// /// ```rust /// use jsonwebtoken::decode_header; /// /// let token = "a.jwt.token".to_string(); /// let header = decode_header(&token); /// ``` pub fn decode_header(token: &str) -> Result<Header> { let (_, message) = expect_two!(token.rsplitn(2, '.')); let (_, header) = expect_two!(message.rsplitn(2, '.')); Header::from_encoded(header) }
{ match &self.kind { DecodingKeyKind::SecretOrDer(b) => b, DecodingKeyKind::RsaModulusExponent { .. } => unreachable!(), } }
identifier_body
trait-with-bounds-default.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. pub trait Clone2 { /// Returns a copy of the value. The contents of owned pointers /// are copied to maintain uniqueness, while the contents of /// managed pointers are not copied. fn clone(&self) -> Self; } trait Getter<T: Clone> { fn do_get(&self) -> T; fn do_get2(&self) -> (T, T) { let x = self.do_get(); (x.clone(), x.clone()) } } impl Getter<int> for int { fn do_get(&self) -> int { *self } } impl<T: Clone> Getter<T> for Option<T> { fn
(&self) -> T { self.get_ref().clone() } } pub fn main() { assert_eq!(3.do_get2(), (3, 3)); assert_eq!(Some(~"hi").do_get2(), (~"hi", ~"hi")); }
do_get
identifier_name
trait-with-bounds-default.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. pub trait Clone2 { /// Returns a copy of the value. The contents of owned pointers /// are copied to maintain uniqueness, while the contents of /// managed pointers are not copied. fn clone(&self) -> Self; } trait Getter<T: Clone> { fn do_get(&self) -> T; fn do_get2(&self) -> (T, T) { let x = self.do_get(); (x.clone(), x.clone()) } } impl Getter<int> for int { fn do_get(&self) -> int
} impl<T: Clone> Getter<T> for Option<T> { fn do_get(&self) -> T { self.get_ref().clone() } } pub fn main() { assert_eq!(3.do_get2(), (3, 3)); assert_eq!(Some(~"hi").do_get2(), (~"hi", ~"hi")); }
{ *self }
identifier_body
trait-with-bounds-default.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. pub trait Clone2 { /// Returns a copy of the value. The contents of owned pointers /// are copied to maintain uniqueness, while the contents of /// managed pointers are not copied. fn clone(&self) -> Self; } trait Getter<T: Clone> { fn do_get(&self) -> T; fn do_get2(&self) -> (T, T) { let x = self.do_get(); (x.clone(), x.clone()) } } impl Getter<int> for int { fn do_get(&self) -> int { *self }
pub fn main() { assert_eq!(3.do_get2(), (3, 3)); assert_eq!(Some(~"hi").do_get2(), (~"hi", ~"hi")); }
} impl<T: Clone> Getter<T> for Option<T> { fn do_get(&self) -> T { self.get_ref().clone() } }
random_line_split
pass-by-copy.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. extern crate debug;
use std::gc::{GC, Gc}; fn magic(x: A) { println!("{:?}", x); } fn magic2(x: Gc<int>) { println!("{:?}", x); } struct A { a: Gc<int> } pub fn main() { let a = A {a: box(GC) 10}; let b = box(GC) 10; magic(a); magic(A {a: box(GC) 20}); magic2(b); magic2(box(GC) 20); }
random_line_split
pass-by-copy.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. extern crate debug; use std::gc::{GC, Gc}; fn magic(x: A) { println!("{:?}", x); } fn magic2(x: Gc<int>) { println!("{:?}", x); } struct A { a: Gc<int> } pub fn main()
{ let a = A {a: box(GC) 10}; let b = box(GC) 10; magic(a); magic(A {a: box(GC) 20}); magic2(b); magic2(box(GC) 20); }
identifier_body
pass-by-copy.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. extern crate debug; use std::gc::{GC, Gc}; fn
(x: A) { println!("{:?}", x); } fn magic2(x: Gc<int>) { println!("{:?}", x); } struct A { a: Gc<int> } pub fn main() { let a = A {a: box(GC) 10}; let b = box(GC) 10; magic(a); magic(A {a: box(GC) 20}); magic2(b); magic2(box(GC) 20); }
magic
identifier_name
lib.rs
extern crate bazel_protos; extern crate bytes; extern crate digest; extern crate hashing; extern crate protobuf; extern crate sha2; use bytes::Bytes; use std::io::Write; use std::os::unix::fs::PermissionsExt; use std::path::Path; pub mod data; pub mod file; pub fn owned_string_vec(args: &[&str]) -> Vec<String> { args.into_iter().map(|s| s.to_string()).collect() } pub fn as_byte_owned_vec(str: &str) -> Vec<u8>
pub fn as_bytes(str: &str) -> Bytes { Bytes::from(str.as_bytes()) } pub fn make_file(path: &Path, contents: &[u8], mode: u32) { let mut file = std::fs::File::create(&path).unwrap(); file.write(contents).unwrap(); let mut permissions = std::fs::metadata(path).unwrap().permissions(); permissions.set_mode(mode); file.set_permissions(permissions).unwrap(); }
{ Vec::from(str.as_bytes()) }
identifier_body
lib.rs
extern crate bazel_protos; extern crate bytes; extern crate digest; extern crate hashing; extern crate protobuf; extern crate sha2; use bytes::Bytes; use std::io::Write; use std::os::unix::fs::PermissionsExt; use std::path::Path; pub mod data;
pub fn owned_string_vec(args: &[&str]) -> Vec<String> { args.into_iter().map(|s| s.to_string()).collect() } pub fn as_byte_owned_vec(str: &str) -> Vec<u8> { Vec::from(str.as_bytes()) } pub fn as_bytes(str: &str) -> Bytes { Bytes::from(str.as_bytes()) } pub fn make_file(path: &Path, contents: &[u8], mode: u32) { let mut file = std::fs::File::create(&path).unwrap(); file.write(contents).unwrap(); let mut permissions = std::fs::metadata(path).unwrap().permissions(); permissions.set_mode(mode); file.set_permissions(permissions).unwrap(); }
pub mod file;
random_line_split
lib.rs
extern crate bazel_protos; extern crate bytes; extern crate digest; extern crate hashing; extern crate protobuf; extern crate sha2; use bytes::Bytes; use std::io::Write; use std::os::unix::fs::PermissionsExt; use std::path::Path; pub mod data; pub mod file; pub fn owned_string_vec(args: &[&str]) -> Vec<String> { args.into_iter().map(|s| s.to_string()).collect() } pub fn as_byte_owned_vec(str: &str) -> Vec<u8> { Vec::from(str.as_bytes()) } pub fn
(str: &str) -> Bytes { Bytes::from(str.as_bytes()) } pub fn make_file(path: &Path, contents: &[u8], mode: u32) { let mut file = std::fs::File::create(&path).unwrap(); file.write(contents).unwrap(); let mut permissions = std::fs::metadata(path).unwrap().permissions(); permissions.set_mode(mode); file.set_permissions(permissions).unwrap(); }
as_bytes
identifier_name
offer_011_xuan_zhuan_shu_zu_de_zui_xiao_shu_zi_lcof.rs
struct Solution; impl Solution { pub fn min_array(numbers: Vec<i32>) -> i32 { // 使用二分法 let (mut left, mut right) = (0, numbers.len() - 1); while left < right { let mid = (left + right) / 2; // 如果 mid 比 left 大,说明最小值在 [mid+1, right] 之间,也可能就是 left。 // 如果 mid 比 left 小,说明最小值在 [left+1, mid] 之间。 // 如果 mid 比 right 小,说明最小值在 [left, mid] 之间。 // 如果 mid 比 right 大,说明最小值在 [left, mid] 之间。 // 上面这个判断不出应该怎么缩小范围。 // 可以判断 mid 是在较小的那块上还是在较大的那块上吗? // 如果 mid > left && mid > right, 说明 mid 是在较大的那块上,否则就是在较小的那块上。 // 如果 mid 就是最小值呢?那么有:mid < left && mid < right. 但反过来不一定。 // 还是有点繁琐。 // 如果 mid 比 right 大,是不是就说明 mid 在较大的那块上了。如果 mid <= right,那说明 mid 在小块上。 // 如果 mid == right,那么 mid 可能在大块上,也可能在小块上。参考单测4. // 看了官方题解,当相等时直接把 right 减一 😳,这样就没有二分了呀。。。 if numbers[mid] > numbers[right] { left = mid + 1; } else if numbers[mid] < numbers[right] { right = mid; } else { right -= 1; } } numbers[left] } } #[cfg(test)] mod tests { use super::*; #[test] fn test_min_array1() { assert_eq!(Solution::min_array(vec![3, 4, 5, 1, 2]), 1); } #[test] fn test_min_array2() { assert_eq!(Solution::min_array(vec![2, 2, 2, 0, 1]), 0); } #[test] fn test_min_array3() { assert_eq!(Solution::min_array(vec![1, 1]), 1);
fn test_min_array4() { assert_eq!(Solution::min_array(vec![3, 3, 1, 3]), 1); } }
} #[test]
random_line_split
offer_011_xuan_zhuan_shu_zu_de_zui_xiao_shu_zi_lcof.rs
struct Solution; impl Solution { pub fn min_array(numbers: Vec<i32>) -> i32 { // 使用二分法 let (mut left, mut right) = (0, numbers.len() - 1); while left < right { let mid = (left + right) / 2; // 如果 mid 比 left 大,说明最小值在 [mid+1, right] 之间,也可能就是 left。 // 如果 mid 比 left 小,说明最小值在 [left+1, mid] 之间。 // 如果 mid 比 right 小,说明最小值在 [left, mid] 之间。 // 如果 mid 比 right 大,说明最小值在 [left, mid] 之间。 // 上面这个判断不出应该怎么缩小范围。 // 可以判断 mid 是在较小的那块上还是在较大的那块上吗? // 如果 mid > left && mid > right, 说明 mid 是在较大的那块上,否则就是在较小的那块上。 // 如果 mid 就是最小值呢?那么有:mid < left && mid < right. 但反过来不一定。 // 还是有点繁琐。 // 如果 mid 比 right 大,是不是就说明 mid 在较大的那块上了。如果 mid <= right,那说明 mid 在小块上。 // 如果 mid == right,那么 mid 可能在大块上,也可能在小块上。参考单测4. // 看了官方题解,当相等时直接把 right 减一 😳,这样就没有二分了呀。。。 if numbers[mid] > numbers[right] { left = mid + 1; } else if numbers[mid] < numbers[right] { right = mid; } else { right -= 1; } } numbers[left] } } #[cfg(test)] mod tests { use super::*; #[test] fn test_min_array1() { assert_eq!(Solution::min_array(vec![3, 4, 5, 1, 2]), 1); } #[test] fn test_min_array2() { assert_eq!(Solution::min_array(vec![2, 2, 2, 0, 1]), 0); } #[test] fn test_min_array3() { assert_eq!(Solution::min_array(vec![1, 1]),
y4() { assert_eq!(Solution::min_array(vec![3, 3, 1, 3]), 1); } }
1); } #[test] fn test_min_arra
conditional_block
offer_011_xuan_zhuan_shu_zu_de_zui_xiao_shu_zi_lcof.rs
struct
; impl Solution { pub fn min_array(numbers: Vec<i32>) -> i32 { // 使用二分法 let (mut left, mut right) = (0, numbers.len() - 1); while left < right { let mid = (left + right) / 2; // 如果 mid 比 left 大,说明最小值在 [mid+1, right] 之间,也可能就是 left。 // 如果 mid 比 left 小,说明最小值在 [left+1, mid] 之间。 // 如果 mid 比 right 小,说明最小值在 [left, mid] 之间。 // 如果 mid 比 right 大,说明最小值在 [left, mid] 之间。 // 上面这个判断不出应该怎么缩小范围。 // 可以判断 mid 是在较小的那块上还是在较大的那块上吗? // 如果 mid > left && mid > right, 说明 mid 是在较大的那块上,否则就是在较小的那块上。 // 如果 mid 就是最小值呢?那么有:mid < left && mid < right. 但反过来不一定。 // 还是有点繁琐。 // 如果 mid 比 right 大,是不是就说明 mid 在较大的那块上了。如果 mid <= right,那说明 mid 在小块上。 // 如果 mid == right,那么 mid 可能在大块上,也可能在小块上。参考单测4. // 看了官方题解,当相等时直接把 right 减一 😳,这样就没有二分了呀。。。 if numbers[mid] > numbers[right] { left = mid + 1; } else if numbers[mid] < numbers[right] { right = mid; } else { right -= 1; } } numbers[left] } } #[cfg(test)] mod tests { use super::*; #[test] fn test_min_array1() { assert_eq!(Solution::min_array(vec![3, 4, 5, 1, 2]), 1); } #[test] fn test_min_array2() { assert_eq!(Solution::min_array(vec![2, 2, 2, 0, 1]), 0); } #[test] fn test_min_array3() { assert_eq!(Solution::min_array(vec![1, 1]), 1); } #[test] fn test_min_array4() { assert_eq!(Solution::min_array(vec![3, 3, 1, 3]), 1); } }
Solution
identifier_name
offer_011_xuan_zhuan_shu_zu_de_zui_xiao_shu_zi_lcof.rs
struct Solution; impl Solution { pub fn min_array(numbers: Vec<i32>) -> i32 { // 使用二分法 let (mut left, mut right) = (0, numbers.len() - 1); while left < right { let mid = (left + right) / 2; // 如果 mid 比 left 大,说明最小值在 [mid+1, right] 之间,也可能就是 left。 // 如果 mid 比 left 小,说明最小值在 [left+1, mid] 之间。 // 如果 mid 比 right 小,说明最小值在 [left, mid] 之间。 // 如果 mid 比 right 大,说明最小值在 [left, mid] 之间。 // 上面这个判断不出应该怎么缩小范围。 // 可以判断 mid 是在较小的那块上还是在较大的那块上吗? // 如果 mid > left && mid > right, 说明 mid 是在较大的那块上,否则就是在较小的那块上。 // 如果 mid 就是最小值呢?那么有:mid < left && mid < right. 但反过来不一定。 // 还是有点繁琐。 // 如果 mid 比 right 大,是不是就说明 mid 在较大的那块上了。如果 mid <= right,那说明 mid 在小块上。 // 如果 mid == right,那么 mid 可能在大块上,也可能在小块上。参考单测4. // 看了官方题解,当相等时直接把 right 减一 😳,这样就没有二分了呀。。。 if numbers[mid] > numbers[right] { left = mid + 1; } else if numbers[mid] < numbers[right] { right = mid; } else { right -= 1; } } numbers[left] } } #[cfg(test)] mod tests { use super::*; #[test] fn test_min_array1() { assert_eq!(Solution::min_array(vec![3, 4, 5, 1, 2]), 1); } #[test] fn test_min_array2() { assert_eq!(Solution::min_array(vec![2, 2, 2, 0, 1]), 0); } #[test] fn test_min_array3() { assert_eq!(Solution::min_array(vec![1, 1]), 1); } #[test] fn test_min_array4() { assert_eq!(Solution::min_array(vec![3, 3, 1, 3]), 1); } }
identifier_body
font.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use geom::{Point2D, Rect, Size2D}; use std::mem; use std::string; use std::rc::Rc; use std::cell::RefCell; use servo_util::cache::{Cache, HashCache}; use style::computed_values::{font_weight, font_style};
use platform::font_context::FontContextHandle; use platform::font::{FontHandle, FontTable}; use text::glyph::{GlyphStore, GlyphId}; use text::shaping::ShaperMethods; use text::{Shaper, TextRun}; use font_template::FontTemplateDescriptor; use platform::font_template::FontTemplateData; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<f64>) -> Result<Self,()>; fn get_template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> String; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel; fn get_metrics(&self) -> FontMetrics; fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; pub trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { unsafe { let reversed = string::raw::from_buf_len(mem::transmute(self), 4); return String::from_chars([reversed.as_slice().char_at(3), reversed.as_slice().char_at(2), reversed.as_slice().char_at(1), reversed.as_slice().char_at(0)]); } } } pub trait FontTableMethods { fn with_buffer(&self, |*const u8, uint|); } #[deriving(Clone)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub line_gap: Au, } // TODO(Issue #179): eventually this will be split into the specified // and used font styles. specified contains uninterpreted CSS font // property values, while 'used' is attached to gfx::Font to descript // the instance's properties. // // For now, the cases are differentiated with a typedef #[deriving(Clone, PartialEq)] pub struct FontStyle { pub pt_size: f64, pub weight: font_weight::T, pub style: font_style::T, pub families: Vec<String>, // TODO(Issue #198): font-stretch, text-decoration, font-variant, size-adjust } pub type SpecifiedFontStyle = FontStyle; pub type UsedFontStyle = FontStyle; pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub descriptor: FontTemplateDescriptor, pub pt_size: f64, pub shaper: Option<Shaper>, pub shape_cache: HashCache<String, Arc<GlyphStore>>, pub glyph_advance_cache: HashCache<u32, FractionalPixel>, } impl Font { pub fn shape_text(&mut self, text: String, is_whitespace: bool) -> Arc<GlyphStore> { self.make_shaper(); let shaper = &self.shaper; self.shape_cache.find_or_create(&text, |txt| { let mut glyphs = GlyphStore::new(text.as_slice().char_len() as int, is_whitespace); shaper.as_ref().unwrap().shape_text(txt.as_slice(), &mut glyphs); Arc::new(glyphs) }) } fn make_shaper<'a>(&'a mut self) -> &'a Shaper { // fast path: already created a shaper match self.shaper { Some(ref shaper) => { let s: &'a Shaper = shaper; return s; }, None => {} } let shaper = Shaper::new(self); self.shaper = Some(shaper); self.shaper.as_ref().unwrap() } pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.get_table_for_tag(tag); let status = if result.is_some() { "Found" } else { "Didn't find" }; debug!("{:s} font table[{:s}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name()); return result; } pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel { let handle = &self.handle; self.glyph_advance_cache.find_or_create(&glyph, |glyph| { match handle.glyph_h_advance(*glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } pub struct FontGroup { pub fonts: Vec<Rc<RefCell<Font>>>, } impl FontGroup { pub fn new(fonts: Vec<Rc<RefCell<Font>>>) -> FontGroup { FontGroup { fonts: fonts } } pub fn create_textrun(&self, text: String) -> TextRun { assert!(self.fonts.len() > 0); // TODO(Issue #177): Actually fall back through the FontGroup when a font is unsuitable. TextRun::new(&mut *self.fonts[0].borrow_mut(), text.clone()) } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero // this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au> } impl RunMetrics { pub fn new(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect(Point2D(Au(0), -ascent), Size2D(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box. RunMetrics { advance_width: advance, bounding_box: bounds, ascent: ascent, descent: descent, } } }
use sync::Arc; use servo_util::geometry::Au;
random_line_split
font.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use geom::{Point2D, Rect, Size2D}; use std::mem; use std::string; use std::rc::Rc; use std::cell::RefCell; use servo_util::cache::{Cache, HashCache}; use style::computed_values::{font_weight, font_style}; use sync::Arc; use servo_util::geometry::Au; use platform::font_context::FontContextHandle; use platform::font::{FontHandle, FontTable}; use text::glyph::{GlyphStore, GlyphId}; use text::shaping::ShaperMethods; use text::{Shaper, TextRun}; use font_template::FontTemplateDescriptor; use platform::font_template::FontTemplateData; // FontHandle encapsulates access to the platform's font API, // e.g. quartz, FreeType. It provides access to metrics and tables // needed by the text shaper as well as access to the underlying font // resources needed by the graphics layer to draw glyphs. pub trait FontHandleMethods { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<f64>) -> Result<Self,()>; fn get_template(&self) -> Arc<FontTemplateData>; fn family_name(&self) -> String; fn face_name(&self) -> String; fn is_italic(&self) -> bool; fn boldness(&self) -> font_weight::T; fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, GlyphId, GlyphId) -> FractionalPixel; fn get_metrics(&self) -> FontMetrics; fn get_table_for_tag(&self, FontTableTag) -> Option<FontTable>; } // Used to abstract over the shaper's choice of fixed int representation. pub type FractionalPixel = f64; pub type FontTableTag = u32; pub trait FontTableTagConversions { fn tag_to_str(&self) -> String; } impl FontTableTagConversions for FontTableTag { fn tag_to_str(&self) -> String { unsafe { let reversed = string::raw::from_buf_len(mem::transmute(self), 4); return String::from_chars([reversed.as_slice().char_at(3), reversed.as_slice().char_at(2), reversed.as_slice().char_at(1), reversed.as_slice().char_at(0)]); } } } pub trait FontTableMethods { fn with_buffer(&self, |*const u8, uint|); } #[deriving(Clone)] pub struct FontMetrics { pub underline_size: Au, pub underline_offset: Au, pub strikeout_size: Au, pub strikeout_offset: Au, pub leading: Au, pub x_height: Au, pub em_size: Au, pub ascent: Au, pub descent: Au, pub max_advance: Au, pub line_gap: Au, } // TODO(Issue #179): eventually this will be split into the specified // and used font styles. specified contains uninterpreted CSS font // property values, while 'used' is attached to gfx::Font to descript // the instance's properties. // // For now, the cases are differentiated with a typedef #[deriving(Clone, PartialEq)] pub struct FontStyle { pub pt_size: f64, pub weight: font_weight::T, pub style: font_style::T, pub families: Vec<String>, // TODO(Issue #198): font-stretch, text-decoration, font-variant, size-adjust } pub type SpecifiedFontStyle = FontStyle; pub type UsedFontStyle = FontStyle; pub struct Font { pub handle: FontHandle, pub metrics: FontMetrics, pub descriptor: FontTemplateDescriptor, pub pt_size: f64, pub shaper: Option<Shaper>, pub shape_cache: HashCache<String, Arc<GlyphStore>>, pub glyph_advance_cache: HashCache<u32, FractionalPixel>, } impl Font { pub fn shape_text(&mut self, text: String, is_whitespace: bool) -> Arc<GlyphStore> { self.make_shaper(); let shaper = &self.shaper; self.shape_cache.find_or_create(&text, |txt| { let mut glyphs = GlyphStore::new(text.as_slice().char_len() as int, is_whitespace); shaper.as_ref().unwrap().shape_text(txt.as_slice(), &mut glyphs); Arc::new(glyphs) }) } fn make_shaper<'a>(&'a mut self) -> &'a Shaper { // fast path: already created a shaper match self.shaper { Some(ref shaper) => { let s: &'a Shaper = shaper; return s; }, None => {} } let shaper = Shaper::new(self); self.shaper = Some(shaper); self.shaper.as_ref().unwrap() } pub fn get_table_for_tag(&self, tag: FontTableTag) -> Option<FontTable> { let result = self.handle.get_table_for_tag(tag); let status = if result.is_some() { "Found" } else { "Didn't find" }; debug!("{:s} font table[{:s}] with family={}, face={}", status, tag.tag_to_str(), self.handle.family_name(), self.handle.face_name()); return result; } pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> { self.handle.glyph_index(codepoint) } pub fn glyph_h_kerning(&mut self, first_glyph: GlyphId, second_glyph: GlyphId) -> FractionalPixel { self.handle.glyph_h_kerning(first_glyph, second_glyph) } pub fn glyph_h_advance(&mut self, glyph: GlyphId) -> FractionalPixel { let handle = &self.handle; self.glyph_advance_cache.find_or_create(&glyph, |glyph| { match handle.glyph_h_advance(*glyph) { Some(adv) => adv, None => 10f64 as FractionalPixel // FIXME: Need fallback strategy } }) } } pub struct FontGroup { pub fonts: Vec<Rc<RefCell<Font>>>, } impl FontGroup { pub fn new(fonts: Vec<Rc<RefCell<Font>>>) -> FontGroup { FontGroup { fonts: fonts } } pub fn create_textrun(&self, text: String) -> TextRun { assert!(self.fonts.len() > 0); // TODO(Issue #177): Actually fall back through the FontGroup when a font is unsuitable. TextRun::new(&mut *self.fonts[0].borrow_mut(), text.clone()) } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub advance_width: Au, pub ascent: Au, // nonzero pub descent: Au, // nonzero // this bounding box is relative to the left origin baseline. // so, bounding_box.position.y = -ascent pub bounding_box: Rect<Au> } impl RunMetrics { pub fn
(advance: Au, ascent: Au, descent: Au) -> RunMetrics { let bounds = Rect(Point2D(Au(0), -ascent), Size2D(advance, ascent + descent)); // TODO(Issue #125): support loose and tight bounding boxes; using the // ascent+descent and advance is sometimes too generous and // looking at actual glyph extents can yield a tighter box. RunMetrics { advance_width: advance, bounding_box: bounds, ascent: ascent, descent: descent, } } }
new
identifier_name
tests.rs
use std::cmp::Ordering; use super::print_item::compare_names; use super::{AllTypes, Buffer}; #[test] fn test_compare_names()
assert_eq!(compare_names("u32", "u16"), Ordering::Greater); assert_eq!(compare_names("u8_to_f64", "u16_to_f64"), Ordering::Less); assert_eq!(compare_names("u32_to_f64", "u16_to_f64"), Ordering::Greater); assert_eq!(compare_names("u16_to_f64", "u16_to_f64"), Ordering::Equal); assert_eq!(compare_names("u16_to_f32", "u16_to_f64"), Ordering::Less); } #[test] fn test_name_sorting() { let names = [ "Apple", "Banana", "Fruit", "Fruit0", "Fruit00", "Fruit01", "Fruit1", "Fruit02", "Fruit2", "Fruit20", "Fruit30x", "Fruit100", "Pear", ]; let mut sorted = names.to_owned(); sorted.sort_by(|&l, r| compare_names(l, r)); assert_eq!(names, sorted); } #[test] fn test_all_types_prints_header_once() { // Regression test for #82477 let all_types = AllTypes::new(); let mut buffer = Buffer::new(); all_types.print(&mut buffer); assert_eq!(1, buffer.into_inner().matches("List of all items").count()); }
{ for &(a, b) in &[ ("hello", "world"), ("", "world"), ("123", "hello"), ("123", ""), ("123test", "123"), ("hello", ""), ("hello", "hello"), ("hello123", "hello123"), ("hello123", "hello12"), ("hello12", "hello123"), ("hello01abc", "hello01xyz"), ("hello0abc", "hello0"), ("hello0", "hello0abc"), ("01", "1"), ] { assert_eq!(compare_names(a, b), a.cmp(b), "{:?} - {:?}", a, b); } assert_eq!(compare_names("u8", "u16"), Ordering::Less);
identifier_body
tests.rs
use std::cmp::Ordering; use super::print_item::compare_names; use super::{AllTypes, Buffer}; #[test] fn test_compare_names() { for &(a, b) in &[ ("hello", "world"), ("", "world"), ("123", "hello"), ("123", ""), ("123test", "123"), ("hello", ""), ("hello", "hello"), ("hello123", "hello123"), ("hello123", "hello12"), ("hello12", "hello123"), ("hello01abc", "hello01xyz"), ("hello0abc", "hello0"), ("hello0", "hello0abc"), ("01", "1"), ] { assert_eq!(compare_names(a, b), a.cmp(b), "{:?} - {:?}", a, b); } assert_eq!(compare_names("u8", "u16"), Ordering::Less); assert_eq!(compare_names("u32", "u16"), Ordering::Greater); assert_eq!(compare_names("u8_to_f64", "u16_to_f64"), Ordering::Less); assert_eq!(compare_names("u32_to_f64", "u16_to_f64"), Ordering::Greater); assert_eq!(compare_names("u16_to_f64", "u16_to_f64"), Ordering::Equal); assert_eq!(compare_names("u16_to_f32", "u16_to_f64"), Ordering::Less); } #[test] fn test_name_sorting() { let names = [ "Apple", "Banana", "Fruit", "Fruit0", "Fruit00", "Fruit01", "Fruit1", "Fruit02", "Fruit2", "Fruit20", "Fruit30x", "Fruit100", "Pear", ]; let mut sorted = names.to_owned(); sorted.sort_by(|&l, r| compare_names(l, r)); assert_eq!(names, sorted); } #[test] fn
() { // Regression test for #82477 let all_types = AllTypes::new(); let mut buffer = Buffer::new(); all_types.print(&mut buffer); assert_eq!(1, buffer.into_inner().matches("List of all items").count()); }
test_all_types_prints_header_once
identifier_name
tests.rs
use std::cmp::Ordering; use super::print_item::compare_names; use super::{AllTypes, Buffer}; #[test] fn test_compare_names() { for &(a, b) in &[ ("hello", "world"), ("", "world"), ("123", "hello"), ("123", ""), ("123test", "123"), ("hello", ""), ("hello", "hello"), ("hello123", "hello123"),
("hello01abc", "hello01xyz"), ("hello0abc", "hello0"), ("hello0", "hello0abc"), ("01", "1"), ] { assert_eq!(compare_names(a, b), a.cmp(b), "{:?} - {:?}", a, b); } assert_eq!(compare_names("u8", "u16"), Ordering::Less); assert_eq!(compare_names("u32", "u16"), Ordering::Greater); assert_eq!(compare_names("u8_to_f64", "u16_to_f64"), Ordering::Less); assert_eq!(compare_names("u32_to_f64", "u16_to_f64"), Ordering::Greater); assert_eq!(compare_names("u16_to_f64", "u16_to_f64"), Ordering::Equal); assert_eq!(compare_names("u16_to_f32", "u16_to_f64"), Ordering::Less); } #[test] fn test_name_sorting() { let names = [ "Apple", "Banana", "Fruit", "Fruit0", "Fruit00", "Fruit01", "Fruit1", "Fruit02", "Fruit2", "Fruit20", "Fruit30x", "Fruit100", "Pear", ]; let mut sorted = names.to_owned(); sorted.sort_by(|&l, r| compare_names(l, r)); assert_eq!(names, sorted); } #[test] fn test_all_types_prints_header_once() { // Regression test for #82477 let all_types = AllTypes::new(); let mut buffer = Buffer::new(); all_types.print(&mut buffer); assert_eq!(1, buffer.into_inner().matches("List of all items").count()); }
("hello123", "hello12"), ("hello12", "hello123"),
random_line_split
rt-set-exit-status.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. // error-pattern:whatever #![feature(rustc_private, exit_status)] #[macro_use] extern crate log; use std::env; fn main() { error!("whatever"); // 101 is the code the runtime uses on thread panic and the value // compiletest expects run-fail tests to return. env::set_exit_status(101); }
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
random_line_split
rt-set-exit-status.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:whatever #![feature(rustc_private, exit_status)] #[macro_use] extern crate log; use std::env; fn main()
{ error!("whatever"); // 101 is the code the runtime uses on thread panic and the value // compiletest expects run-fail tests to return. env::set_exit_status(101); }
identifier_body
rt-set-exit-status.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:whatever #![feature(rustc_private, exit_status)] #[macro_use] extern crate log; use std::env; fn
() { error!("whatever"); // 101 is the code the runtime uses on thread panic and the value // compiletest expects run-fail tests to return. env::set_exit_status(101); }
main
identifier_name
main.rs
use std::thread; fn test1() { let v = vec![1, 2, 3]; let handle = thread::spawn(move || { println!("Here's a vector: {:?}", v); }); handle.join().unwrap(); } use std::sync::mpsc; fn test2() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("[sender say]> hi"); println!("[sender] before send: {}", val); tx.send(val).unwrap(); // println!("[sender] before send: {}", val); //value borrowed here after move }); let received = rx.recv().unwrap(); println!("[receiver] Got: {}", received); } // use std::sync::mpsc; // use std::thread; use std::time::Duration; fn test3() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("sub-thread"), ]; for val in vals { tx.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); for received in rx { println!("Got: {}", received); } } fn test4() { let (tx, rx) = mpsc::channel(); let tx1 = mpsc::Sender::clone(&tx); thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("sub-thread"), ]; for val in vals { tx1.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); thread::spawn(move || { let vals = vec![ String::from("more"), String::from("messages"), String::from("for"), String::from("you"), ]; for val in vals { tx.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); for received in rx { println!("Got: {}", received); } } use std::sync::{Arc, Mutex}; fn test5() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 2; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Result: {}", *counter.lock().unwrap()); } //test entry fn
() { println!("main; -enter"); test5(); println!("main; -exit"); }
main
identifier_name
main.rs
use std::thread; fn test1() { let v = vec![1, 2, 3]; let handle = thread::spawn(move || { println!("Here's a vector: {:?}", v); }); handle.join().unwrap(); } use std::sync::mpsc; fn test2()
// use std::sync::mpsc; // use std::thread; use std::time::Duration; fn test3() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("sub-thread"), ]; for val in vals { tx.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); for received in rx { println!("Got: {}", received); } } fn test4() { let (tx, rx) = mpsc::channel(); let tx1 = mpsc::Sender::clone(&tx); thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("sub-thread"), ]; for val in vals { tx1.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); thread::spawn(move || { let vals = vec![ String::from("more"), String::from("messages"), String::from("for"), String::from("you"), ]; for val in vals { tx.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); for received in rx { println!("Got: {}", received); } } use std::sync::{Arc, Mutex}; fn test5() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 2; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Result: {}", *counter.lock().unwrap()); } //test entry fn main() { println!("main; -enter"); test5(); println!("main; -exit"); }
{ let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("[sender say]> hi"); println!("[sender] before send: {}", val); tx.send(val).unwrap(); // println!("[sender] before send: {}", val); //value borrowed here after move }); let received = rx.recv().unwrap(); println!("[receiver] Got: {}", received); }
identifier_body
main.rs
use std::thread; fn test1() { let v = vec![1, 2, 3]; let handle = thread::spawn(move || { println!("Here's a vector: {:?}", v); }); handle.join().unwrap(); } use std::sync::mpsc; fn test2() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("[sender say]> hi"); println!("[sender] before send: {}", val); tx.send(val).unwrap(); // println!("[sender] before send: {}", val); //value borrowed here after move }); let received = rx.recv().unwrap(); println!("[receiver] Got: {}", received); } // use std::sync::mpsc; // use std::thread; use std::time::Duration; fn test3() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("sub-thread"), ]; for val in vals { tx.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); for received in rx { println!("Got: {}", received); } } fn test4() { let (tx, rx) = mpsc::channel(); let tx1 = mpsc::Sender::clone(&tx); thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("sub-thread"), ]; for val in vals { tx1.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); thread::spawn(move || { let vals = vec![ String::from("more"), String::from("messages"), String::from("for"), String::from("you"), ];
thread::sleep(Duration::from_secs(1)); } }); for received in rx { println!("Got: {}", received); } } use std::sync::{Arc, Mutex}; fn test5() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 2; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Result: {}", *counter.lock().unwrap()); } //test entry fn main() { println!("main; -enter"); test5(); println!("main; -exit"); }
for val in vals { tx.send(val).unwrap();
random_line_split
day_6.rs
use std::borrow::Cow; use std::iter::Peekable; use std::num::ParseFloatError; use std::str::Chars; pub fn calculate<'s>(src: Cow<'s, str>) -> Result<f64, ParseFloatError> { let mut iter = src.chars().peekable(); parse_expression(&mut iter) } fn parse_expression(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut ret = parse_term(iter.by_ref()); loop { match iter.peek().cloned() { Some('+') => { iter.next(); ret = ret.and_then(|ret| parse_term(iter.by_ref()).map(|num| ret + num)) }, Some('-') => { iter.next(); ret = ret.and_then(|ret| parse_term(iter.by_ref()).map(|num| ret - num)) } _ => break } } ret } fn parse_term(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut ret = parse_num(iter.by_ref()); loop { match iter.peek().cloned() { Some('×') => { iter.next(); ret = ret.and_then(|ret| parse_num(iter.by_ref()).map(|num| ret * num)) }, Some('÷') => { iter.next();
} ret } fn parse_num(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut num = String::new(); loop { match iter.peek().cloned() { Some('+') | Some('×') | Some('÷') | Some(')') | None => break, Some('-') if!num.is_empty() => break, Some('(') => { iter.next(); let ret = parse_expression(iter.by_ref()); iter.next(); return ret; } Some(d) => num.push(d) } iter.next(); } num.parse() } #[cfg(test)] mod tests { use super::*; #[test] fn evaluate_negative_number() { assert_eq!(calculate(Cow::Borrowed("-54")), Ok(-54.0)); } #[test] fn evaluate_addition() { assert_eq!(calculate(Cow::Borrowed("14+23")), Ok(37.0)); } #[test] fn evaluate_subtraction() { assert_eq!(calculate(Cow::Borrowed("3-45")), Ok(-42.0)); } #[test] fn evaluate_multiplication() { assert_eq!(calculate(Cow::Borrowed("4×9")), Ok(36.0)); } #[test] fn evaluate_division() { assert_eq!(calculate(Cow::Borrowed("21÷3")), Ok(7.0)); } #[test] fn evaluate_many_operations() { assert_eq!(calculate(Cow::Borrowed("3+12÷2-3×7+2")), Ok(-10.0)); } #[test] fn evaluate_operation_with_parenthesis() { assert_eq!(calculate(Cow::Borrowed("3+18÷(2-(3+7)×2)")), Ok(2.0)) } }
ret = ret.and_then(|ret| parse_num(iter.by_ref()).map(|num| ret / num)) } _ => break }
random_line_split
day_6.rs
use std::borrow::Cow; use std::iter::Peekable; use std::num::ParseFloatError; use std::str::Chars; pub fn calculate<'s>(src: Cow<'s, str>) -> Result<f64, ParseFloatError> { let mut iter = src.chars().peekable(); parse_expression(&mut iter) } fn parse_expression(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut ret = parse_term(iter.by_ref()); loop { match iter.peek().cloned() { Some('+') => { iter.next(); ret = ret.and_then(|ret| parse_term(iter.by_ref()).map(|num| ret + num)) }, Some('-') => { iter.next(); ret = ret.and_then(|ret| parse_term(iter.by_ref()).map(|num| ret - num)) } _ => break } } ret } fn parse_term(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut ret = parse_num(iter.by_ref()); loop { match iter.peek().cloned() { Some('×') => { iter.next(); ret = ret.and_then(|ret| parse_num(iter.by_ref()).map(|num| ret * num)) }, Some('÷') => { iter.next(); ret = ret.and_then(|ret| parse_num(iter.by_ref()).map(|num| ret / num)) } _ => break } } ret } fn pa
ter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut num = String::new(); loop { match iter.peek().cloned() { Some('+') | Some('×') | Some('÷') | Some(')') | None => break, Some('-') if!num.is_empty() => break, Some('(') => { iter.next(); let ret = parse_expression(iter.by_ref()); iter.next(); return ret; } Some(d) => num.push(d) } iter.next(); } num.parse() } #[cfg(test)] mod tests { use super::*; #[test] fn evaluate_negative_number() { assert_eq!(calculate(Cow::Borrowed("-54")), Ok(-54.0)); } #[test] fn evaluate_addition() { assert_eq!(calculate(Cow::Borrowed("14+23")), Ok(37.0)); } #[test] fn evaluate_subtraction() { assert_eq!(calculate(Cow::Borrowed("3-45")), Ok(-42.0)); } #[test] fn evaluate_multiplication() { assert_eq!(calculate(Cow::Borrowed("4×9")), Ok(36.0)); } #[test] fn evaluate_division() { assert_eq!(calculate(Cow::Borrowed("21÷3")), Ok(7.0)); } #[test] fn evaluate_many_operations() { assert_eq!(calculate(Cow::Borrowed("3+12÷2-3×7+2")), Ok(-10.0)); } #[test] fn evaluate_operation_with_parenthesis() { assert_eq!(calculate(Cow::Borrowed("3+18÷(2-(3+7)×2)")), Ok(2.0)) } }
rse_num(i
identifier_name
day_6.rs
use std::borrow::Cow; use std::iter::Peekable; use std::num::ParseFloatError; use std::str::Chars; pub fn calculate<'s>(src: Cow<'s, str>) -> Result<f64, ParseFloatError> { let mut iter = src.chars().peekable(); parse_expression(&mut iter) } fn parse_expression(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut ret = parse_term(iter.by_ref()); loop { match iter.peek().cloned() { Some('+') => { iter.next(); ret = ret.and_then(|ret| parse_term(iter.by_ref()).map(|num| ret + num)) }, Some('-') => { iter.next(); ret = ret.and_then(|ret| parse_term(iter.by_ref()).map(|num| ret - num)) } _ => break } } ret } fn parse_term(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut ret = parse_num(iter.by_ref()); loop { match iter.peek().cloned() { Some('×') => {
Some('÷') => { iter.next(); ret = ret.and_then(|ret| parse_num(iter.by_ref()).map(|num| ret / num)) } _ => break } } ret } fn parse_num(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut num = String::new(); loop { match iter.peek().cloned() { Some('+') | Some('×') | Some('÷') | Some(')') | None => break, Some('-') if!num.is_empty() => break, Some('(') => { iter.next(); let ret = parse_expression(iter.by_ref()); iter.next(); return ret; } Some(d) => num.push(d) } iter.next(); } num.parse() } #[cfg(test)] mod tests { use super::*; #[test] fn evaluate_negative_number() { assert_eq!(calculate(Cow::Borrowed("-54")), Ok(-54.0)); } #[test] fn evaluate_addition() { assert_eq!(calculate(Cow::Borrowed("14+23")), Ok(37.0)); } #[test] fn evaluate_subtraction() { assert_eq!(calculate(Cow::Borrowed("3-45")), Ok(-42.0)); } #[test] fn evaluate_multiplication() { assert_eq!(calculate(Cow::Borrowed("4×9")), Ok(36.0)); } #[test] fn evaluate_division() { assert_eq!(calculate(Cow::Borrowed("21÷3")), Ok(7.0)); } #[test] fn evaluate_many_operations() { assert_eq!(calculate(Cow::Borrowed("3+12÷2-3×7+2")), Ok(-10.0)); } #[test] fn evaluate_operation_with_parenthesis() { assert_eq!(calculate(Cow::Borrowed("3+18÷(2-(3+7)×2)")), Ok(2.0)) } }
iter.next(); ret = ret.and_then(|ret| parse_num(iter.by_ref()).map(|num| ret * num)) },
conditional_block
day_6.rs
use std::borrow::Cow; use std::iter::Peekable; use std::num::ParseFloatError; use std::str::Chars; pub fn calculate<'s>(src: Cow<'s, str>) -> Result<f64, ParseFloatError>
fn parse_expression(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut ret = parse_term(iter.by_ref()); loop { match iter.peek().cloned() { Some('+') => { iter.next(); ret = ret.and_then(|ret| parse_term(iter.by_ref()).map(|num| ret + num)) }, Some('-') => { iter.next(); ret = ret.and_then(|ret| parse_term(iter.by_ref()).map(|num| ret - num)) } _ => break } } ret } fn parse_term(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut ret = parse_num(iter.by_ref()); loop { match iter.peek().cloned() { Some('×') => { iter.next(); ret = ret.and_then(|ret| parse_num(iter.by_ref()).map(|num| ret * num)) }, Some('÷') => { iter.next(); ret = ret.and_then(|ret| parse_num(iter.by_ref()).map(|num| ret / num)) } _ => break } } ret } fn parse_num(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> { let mut num = String::new(); loop { match iter.peek().cloned() { Some('+') | Some('×') | Some('÷') | Some(')') | None => break, Some('-') if!num.is_empty() => break, Some('(') => { iter.next(); let ret = parse_expression(iter.by_ref()); iter.next(); return ret; } Some(d) => num.push(d) } iter.next(); } num.parse() } #[cfg(test)] mod tests { use super::*; #[test] fn evaluate_negative_number() { assert_eq!(calculate(Cow::Borrowed("-54")), Ok(-54.0)); } #[test] fn evaluate_addition() { assert_eq!(calculate(Cow::Borrowed("14+23")), Ok(37.0)); } #[test] fn evaluate_subtraction() { assert_eq!(calculate(Cow::Borrowed("3-45")), Ok(-42.0)); } #[test] fn evaluate_multiplication() { assert_eq!(calculate(Cow::Borrowed("4×9")), Ok(36.0)); } #[test] fn evaluate_division() { assert_eq!(calculate(Cow::Borrowed("21÷3")), Ok(7.0)); } #[test] fn evaluate_many_operations() { assert_eq!(calculate(Cow::Borrowed("3+12÷2-3×7+2")), Ok(-10.0)); } #[test] fn evaluate_operation_with_parenthesis() { assert_eq!(calculate(Cow::Borrowed("3+18÷(2-(3+7)×2)")), Ok(2.0)) } }
{ let mut iter = src.chars().peekable(); parse_expression(&mut iter) }
identifier_body
common.rs
//! This module contains various infrastructure that is common across all assembler backends use proc_macro2::{Span, TokenTree}; use quote::ToTokens; use quote::quote; use syn::spanned::Spanned; use syn::parse; use syn::Token; use crate::parse_helpers::{ParseOpt, eat_pseudo_keyword}; use crate::serialize; /// Enum representing the result size of a value/expression/register/etc in bytes. /// Uses the NASM syntax for sizes (a word is 16 bits) #[derive(Debug, PartialOrd, PartialEq, Ord, Eq, Hash, Clone, Copy)] pub enum Size { BYTE = 1, WORD = 2, DWORD = 4, FWORD = 6, QWORD = 8, PWORD = 10, OWORD = 16, HWORD = 32, } impl Size { pub fn in_bytes(self) -> u8 { self as u8 } pub fn as_literal(self) -> syn::Ident { syn::Ident::new(match self { Size::BYTE => "i8", Size::WORD => "i16", Size::DWORD => "i32", Size::FWORD => "i48", Size::QWORD => "i64", Size::PWORD => "i80", Size::OWORD => "i128", Size::HWORD => "i256" }, Span::mixed_site()) } } /** * Jump types */ #[derive(Debug, Clone)] pub struct Jump { pub kind: JumpKind, pub offset: Option<syn::Expr> } #[derive(Debug, Clone)] pub enum JumpKind { // note: these symbol choices try to avoid stuff that is a valid starting symbol for parse_expr // in order to allow the full range of expressions to be used. the only currently existing ambiguity is // with the symbol <, as this symbol is also the starting symbol for the universal calling syntax <Type as Trait>.method(args) Global(syn::Ident), // -> label (["+" "-"] offset)? Backward(syn::Ident), // > label (["+" "-"] offset)? Forward(syn::Ident), // < label (["+" "-"] offset)? Dynamic(syn::Expr), // =>expr | => (expr) (["+" "-"] offset)? Bare(syn::Expr) // jump to this address } impl ParseOpt for Jump { fn parse(input: parse::ParseStream) -> parse::Result<Option<Jump>> { // extern label if eat_pseudo_keyword(input, "extern") { let expr: syn::Expr = input.parse()?; return Ok(Some(Jump { kind: JumpKind::Bare(expr), offset: None })); } // -> global_label let kind = if input.peek(Token![->]) { let _: Token![->] = input.parse()?; let name: syn::Ident = input.parse()?; JumpKind::Global(name) // > forward_label } else if input.peek(Token![>]) { let _: Token![>] = input.parse()?; let name: syn::Ident = input.parse()?; JumpKind::Forward(name) // < backwards_label } else if input.peek(Token![<]) { let _: Token![<] = input.parse()?; let name: syn::Ident = input.parse()?; JumpKind::Backward(name) // => dynamic_label } else if input.peek(Token![=>]) { let _: Token![=>] = input.parse()?; let expr: syn::Expr = if input.peek(syn::token::Paren) { let inner; let _ = syn::parenthesized!(inner in input); let inner = &inner; inner.parse()? } else { input.parse()? }; JumpKind::Dynamic(expr) // nothing } else { return Ok(None); }; // parse optional offset let offset = if input.peek(Token![-]) || input.peek(Token![+]) { if input.peek(Token![+]) { let _: Token![+] = input.parse()?; } let expr: syn::Expr = input.parse()?; Some(expr) } else { None }; Ok(Some(Jump::new(kind, offset))) } } impl Jump { pub fn new(kind: JumpKind, offset: Option<syn::Expr>) -> Jump { Jump { kind, offset } } /// Takes a jump and encodes it as a relocation starting `start_offset` bytes ago, relative to `ref_offset`. /// Any data detailing the type of relocation emitted should be contained in `data`, which is emitted as a tuple of u8's. pub fn encode(self, field_offset: u8, ref_offset: u8, data: &[u8]) -> Stmt { let span = self.span(); let target_offset = delimited(if let Some(offset) = self.offset { quote!(#offset) } else { quote!(0isize) }); // Create a relocation descriptor, containing all information about the actual jump except for the target itself. let relocation = Relocation { target_offset, field_offset, ref_offset, kind: serialize::expr_tuple_of_u8s(span, data) }; match self.kind { JumpKind::Global(ident) => Stmt::GlobalJumpTarget(ident, relocation), JumpKind::Backward(ident) => Stmt::BackwardJumpTarget(ident, relocation), JumpKind::Forward(ident) => Stmt::ForwardJumpTarget(ident, relocation), JumpKind::Dynamic(expr) => Stmt::DynamicJumpTarget(delimited(expr), relocation), JumpKind::Bare(expr) => Stmt::BareJumpTarget(delimited(expr), relocation), } } pub fn span(&self) -> Span { match &self.kind { JumpKind::Global(ident) => ident.span(), JumpKind::Backward(ident) => ident.span(), JumpKind::Forward(ident) => ident.span(), JumpKind::Dynamic(expr) => expr.span(), JumpKind::Bare(expr) => expr.span(), } } } /// A relocation entry description #[derive(Debug, Clone)] pub struct Relocation { pub target_offset: TokenTree, pub field_offset: u8, pub ref_offset: u8, pub kind: TokenTree, } /// An abstract representation of a dynasm runtime statement to be emitted #[derive(Debug, Clone)] pub enum Stmt { // simply push data into the instruction stream. unsigned Const(u64, Size), // push data that is stored inside of an expression. unsigned ExprUnsigned(TokenTree, Size), // push signed data into the instruction stream. signed ExprSigned(TokenTree, Size), // extend the instruction stream with unsigned bytes Extend(Vec<u8>), // extend the instruction stream with unsigned bytes ExprExtend(TokenTree), // align the instruction stream to some alignment Align(TokenTree, TokenTree), // label declarations GlobalLabel(syn::Ident), LocalLabel(syn::Ident), DynamicLabel(TokenTree), // and their respective relocations (as expressions as they differ per assembler). GlobalJumpTarget(syn::Ident, Relocation), ForwardJumpTarget(syn::Ident, Relocation), BackwardJumpTarget(syn::Ident, Relocation), DynamicJumpTarget(TokenTree, Relocation), BareJumpTarget(TokenTree, Relocation), // a statement that provides some information for the next statement, // and should therefore not be reordered with it PrefixStmt(TokenTree), // a random statement that has to be inserted between assembly hunks Stmt(TokenTree) } // convenience methods impl Stmt { #![allow(dead_code)] pub fn u8(value: u8) -> Stmt { Stmt::Const(u64::from(value), Size::BYTE) } pub fn
(value: u16) -> Stmt { Stmt::Const(u64::from(value), Size::WORD) } pub fn u32(value: u32) -> Stmt { Stmt::Const(u64::from(value), Size::DWORD) } pub fn u64(value: u64) -> Stmt { Stmt::Const(value, Size::QWORD) } } // Makes a None-delimited TokenTree item out of anything that can be converted to tokens. // This is a useful shortcut to escape issues around not-properly delimited tokenstreams // because it is guaranteed to be parsed back properly to its source ast at type-level. pub fn delimited<T: ToTokens>(expr: T) -> TokenTree { let span = expr.span(); let mut group = proc_macro2::Group::new( proc_macro2::Delimiter::None, expr.into_token_stream() ); group.set_span(span); proc_macro2::TokenTree::Group(group) } /// Create a bitmask with `scale` bits set pub fn bitmask(scale: u8) -> u32 { 1u32.checked_shl(u32::from(scale)).unwrap_or(0).wrapping_sub(1) } /// Create a bitmask with `scale` bits set pub fn bitmask64(scale: u8) -> u64 { 1u64.checked_shl(u32::from(scale)).unwrap_or(0).wrapping_sub(1) }
u16
identifier_name
common.rs
//! This module contains various infrastructure that is common across all assembler backends use proc_macro2::{Span, TokenTree}; use quote::ToTokens; use quote::quote; use syn::spanned::Spanned; use syn::parse; use syn::Token; use crate::parse_helpers::{ParseOpt, eat_pseudo_keyword}; use crate::serialize; /// Enum representing the result size of a value/expression/register/etc in bytes. /// Uses the NASM syntax for sizes (a word is 16 bits) #[derive(Debug, PartialOrd, PartialEq, Ord, Eq, Hash, Clone, Copy)] pub enum Size { BYTE = 1, WORD = 2, DWORD = 4, FWORD = 6, QWORD = 8, PWORD = 10, OWORD = 16, HWORD = 32, } impl Size { pub fn in_bytes(self) -> u8 { self as u8 } pub fn as_literal(self) -> syn::Ident { syn::Ident::new(match self { Size::BYTE => "i8", Size::WORD => "i16", Size::DWORD => "i32", Size::FWORD => "i48",
} } /** * Jump types */ #[derive(Debug, Clone)] pub struct Jump { pub kind: JumpKind, pub offset: Option<syn::Expr> } #[derive(Debug, Clone)] pub enum JumpKind { // note: these symbol choices try to avoid stuff that is a valid starting symbol for parse_expr // in order to allow the full range of expressions to be used. the only currently existing ambiguity is // with the symbol <, as this symbol is also the starting symbol for the universal calling syntax <Type as Trait>.method(args) Global(syn::Ident), // -> label (["+" "-"] offset)? Backward(syn::Ident), // > label (["+" "-"] offset)? Forward(syn::Ident), // < label (["+" "-"] offset)? Dynamic(syn::Expr), // =>expr | => (expr) (["+" "-"] offset)? Bare(syn::Expr) // jump to this address } impl ParseOpt for Jump { fn parse(input: parse::ParseStream) -> parse::Result<Option<Jump>> { // extern label if eat_pseudo_keyword(input, "extern") { let expr: syn::Expr = input.parse()?; return Ok(Some(Jump { kind: JumpKind::Bare(expr), offset: None })); } // -> global_label let kind = if input.peek(Token![->]) { let _: Token![->] = input.parse()?; let name: syn::Ident = input.parse()?; JumpKind::Global(name) // > forward_label } else if input.peek(Token![>]) { let _: Token![>] = input.parse()?; let name: syn::Ident = input.parse()?; JumpKind::Forward(name) // < backwards_label } else if input.peek(Token![<]) { let _: Token![<] = input.parse()?; let name: syn::Ident = input.parse()?; JumpKind::Backward(name) // => dynamic_label } else if input.peek(Token![=>]) { let _: Token![=>] = input.parse()?; let expr: syn::Expr = if input.peek(syn::token::Paren) { let inner; let _ = syn::parenthesized!(inner in input); let inner = &inner; inner.parse()? } else { input.parse()? }; JumpKind::Dynamic(expr) // nothing } else { return Ok(None); }; // parse optional offset let offset = if input.peek(Token![-]) || input.peek(Token![+]) { if input.peek(Token![+]) { let _: Token![+] = input.parse()?; } let expr: syn::Expr = input.parse()?; Some(expr) } else { None }; Ok(Some(Jump::new(kind, offset))) } } impl Jump { pub fn new(kind: JumpKind, offset: Option<syn::Expr>) -> Jump { Jump { kind, offset } } /// Takes a jump and encodes it as a relocation starting `start_offset` bytes ago, relative to `ref_offset`. /// Any data detailing the type of relocation emitted should be contained in `data`, which is emitted as a tuple of u8's. pub fn encode(self, field_offset: u8, ref_offset: u8, data: &[u8]) -> Stmt { let span = self.span(); let target_offset = delimited(if let Some(offset) = self.offset { quote!(#offset) } else { quote!(0isize) }); // Create a relocation descriptor, containing all information about the actual jump except for the target itself. let relocation = Relocation { target_offset, field_offset, ref_offset, kind: serialize::expr_tuple_of_u8s(span, data) }; match self.kind { JumpKind::Global(ident) => Stmt::GlobalJumpTarget(ident, relocation), JumpKind::Backward(ident) => Stmt::BackwardJumpTarget(ident, relocation), JumpKind::Forward(ident) => Stmt::ForwardJumpTarget(ident, relocation), JumpKind::Dynamic(expr) => Stmt::DynamicJumpTarget(delimited(expr), relocation), JumpKind::Bare(expr) => Stmt::BareJumpTarget(delimited(expr), relocation), } } pub fn span(&self) -> Span { match &self.kind { JumpKind::Global(ident) => ident.span(), JumpKind::Backward(ident) => ident.span(), JumpKind::Forward(ident) => ident.span(), JumpKind::Dynamic(expr) => expr.span(), JumpKind::Bare(expr) => expr.span(), } } } /// A relocation entry description #[derive(Debug, Clone)] pub struct Relocation { pub target_offset: TokenTree, pub field_offset: u8, pub ref_offset: u8, pub kind: TokenTree, } /// An abstract representation of a dynasm runtime statement to be emitted #[derive(Debug, Clone)] pub enum Stmt { // simply push data into the instruction stream. unsigned Const(u64, Size), // push data that is stored inside of an expression. unsigned ExprUnsigned(TokenTree, Size), // push signed data into the instruction stream. signed ExprSigned(TokenTree, Size), // extend the instruction stream with unsigned bytes Extend(Vec<u8>), // extend the instruction stream with unsigned bytes ExprExtend(TokenTree), // align the instruction stream to some alignment Align(TokenTree, TokenTree), // label declarations GlobalLabel(syn::Ident), LocalLabel(syn::Ident), DynamicLabel(TokenTree), // and their respective relocations (as expressions as they differ per assembler). GlobalJumpTarget(syn::Ident, Relocation), ForwardJumpTarget(syn::Ident, Relocation), BackwardJumpTarget(syn::Ident, Relocation), DynamicJumpTarget(TokenTree, Relocation), BareJumpTarget(TokenTree, Relocation), // a statement that provides some information for the next statement, // and should therefore not be reordered with it PrefixStmt(TokenTree), // a random statement that has to be inserted between assembly hunks Stmt(TokenTree) } // convenience methods impl Stmt { #![allow(dead_code)] pub fn u8(value: u8) -> Stmt { Stmt::Const(u64::from(value), Size::BYTE) } pub fn u16(value: u16) -> Stmt { Stmt::Const(u64::from(value), Size::WORD) } pub fn u32(value: u32) -> Stmt { Stmt::Const(u64::from(value), Size::DWORD) } pub fn u64(value: u64) -> Stmt { Stmt::Const(value, Size::QWORD) } } // Makes a None-delimited TokenTree item out of anything that can be converted to tokens. // This is a useful shortcut to escape issues around not-properly delimited tokenstreams // because it is guaranteed to be parsed back properly to its source ast at type-level. pub fn delimited<T: ToTokens>(expr: T) -> TokenTree { let span = expr.span(); let mut group = proc_macro2::Group::new( proc_macro2::Delimiter::None, expr.into_token_stream() ); group.set_span(span); proc_macro2::TokenTree::Group(group) } /// Create a bitmask with `scale` bits set pub fn bitmask(scale: u8) -> u32 { 1u32.checked_shl(u32::from(scale)).unwrap_or(0).wrapping_sub(1) } /// Create a bitmask with `scale` bits set pub fn bitmask64(scale: u8) -> u64 { 1u64.checked_shl(u32::from(scale)).unwrap_or(0).wrapping_sub(1) }
Size::QWORD => "i64", Size::PWORD => "i80", Size::OWORD => "i128", Size::HWORD => "i256" }, Span::mixed_site())
random_line_split
vector.rs
/* * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::marker::PhantomData; use std::mem::size_of; use std::slice::from_raw_parts; use std::str::from_utf8_unchecked; use endian_scalar::{EndianScalar, read_scalar}; use follow::Follow; use primitives::*; #[derive(Debug)] pub struct
<'a, T: 'a>(&'a [u8], usize, PhantomData<T>); impl<'a, T: 'a> Vector<'a, T> { #[inline(always)] pub fn new(buf: &'a [u8], loc: usize) -> Self { Vector { 0: buf, 1: loc, 2: PhantomData, } } #[inline(always)] pub fn len(&self) -> usize { read_scalar::<UOffsetT>(&self.0[self.1 as usize..]) as usize } } impl<'a, T: Follow<'a> + 'a> Vector<'a, T> { #[inline(always)] pub fn get(&self, idx: usize) -> T::Inner { debug_assert!(idx < read_scalar::<u32>(&self.0[self.1 as usize..]) as usize); let sz = size_of::<T>(); debug_assert!(sz > 0); T::follow(self.0, self.1 as usize + SIZE_UOFFSET + sz * idx) } } pub trait SafeSliceAccess {} impl<'a, T: SafeSliceAccess + 'a> Vector<'a, T> { pub fn safe_slice(self) -> &'a [T] { let buf = self.0; let loc = self.1; let sz = size_of::<T>(); debug_assert!(sz > 0); let len = read_scalar::<UOffsetT>(&buf[loc..loc + SIZE_UOFFSET]) as usize; let data_buf = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len * sz]; let ptr = data_buf.as_ptr() as *const T; let s: &'a [T] = unsafe { from_raw_parts(ptr, len) }; s } } impl SafeSliceAccess for u8 {} impl SafeSliceAccess for i8 {} impl SafeSliceAccess for bool {} #[cfg(target_endian = "little")] mod le_safe_slice_impls { impl super::SafeSliceAccess for u16 {} impl super::SafeSliceAccess for u32 {} impl super::SafeSliceAccess for u64 {} impl super::SafeSliceAccess for i16 {} impl super::SafeSliceAccess for i32 {} impl super::SafeSliceAccess for i64 {} impl super::SafeSliceAccess for f32 {} impl super::SafeSliceAccess for f64 {} } pub use self::le_safe_slice_impls::*; pub fn follow_cast_ref<'a, T: Sized + 'a>(buf: &'a [u8], loc: usize) -> &'a T { let sz = size_of::<T>(); let buf = &buf[loc..loc + sz]; let ptr = buf.as_ptr() as *const T; unsafe { &*ptr } } impl<'a> Follow<'a> for &'a str { type Inner = &'a str; fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { let len = read_scalar::<UOffsetT>(&buf[loc..loc + SIZE_UOFFSET]) as usize; let slice = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len]; let s = unsafe { from_utf8_unchecked(slice) }; s } } fn follow_slice_helper<T>(buf: &[u8], loc: usize) -> &[T] { let sz = size_of::<T>(); debug_assert!(sz > 0); let len = read_scalar::<UOffsetT>(&buf[loc..loc + SIZE_UOFFSET]) as usize; let data_buf = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len * sz]; let ptr = data_buf.as_ptr() as *const T; let s: &[T] = unsafe { from_raw_parts(ptr, len) }; s } /// Implement direct slice access if the host is little-endian. #[cfg(target_endian = "little")] impl<'a, T: EndianScalar> Follow<'a> for &'a [T] { type Inner = &'a [T]; fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { follow_slice_helper::<T>(buf, loc) } } /// Implement Follow for all possible Vectors that have Follow-able elements. impl<'a, T: Follow<'a> + 'a> Follow<'a> for Vector<'a, T> { type Inner = Vector<'a, T>; fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { Vector::new(buf, loc) } }
Vector
identifier_name
vector.rs
/* * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::marker::PhantomData; use std::mem::size_of; use std::slice::from_raw_parts; use std::str::from_utf8_unchecked; use endian_scalar::{EndianScalar, read_scalar}; use follow::Follow; use primitives::*; #[derive(Debug)] pub struct Vector<'a, T: 'a>(&'a [u8], usize, PhantomData<T>); impl<'a, T: 'a> Vector<'a, T> { #[inline(always)] pub fn new(buf: &'a [u8], loc: usize) -> Self { Vector { 0: buf, 1: loc, 2: PhantomData, } } #[inline(always)] pub fn len(&self) -> usize { read_scalar::<UOffsetT>(&self.0[self.1 as usize..]) as usize } } impl<'a, T: Follow<'a> + 'a> Vector<'a, T> { #[inline(always)] pub fn get(&self, idx: usize) -> T::Inner { debug_assert!(idx < read_scalar::<u32>(&self.0[self.1 as usize..]) as usize); let sz = size_of::<T>(); debug_assert!(sz > 0); T::follow(self.0, self.1 as usize + SIZE_UOFFSET + sz * idx) } } pub trait SafeSliceAccess {} impl<'a, T: SafeSliceAccess + 'a> Vector<'a, T> { pub fn safe_slice(self) -> &'a [T] { let buf = self.0; let loc = self.1; let sz = size_of::<T>(); debug_assert!(sz > 0); let len = read_scalar::<UOffsetT>(&buf[loc..loc + SIZE_UOFFSET]) as usize; let data_buf = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len * sz]; let ptr = data_buf.as_ptr() as *const T; let s: &'a [T] = unsafe { from_raw_parts(ptr, len) }; s } } impl SafeSliceAccess for u8 {} impl SafeSliceAccess for i8 {} impl SafeSliceAccess for bool {} #[cfg(target_endian = "little")] mod le_safe_slice_impls { impl super::SafeSliceAccess for u16 {} impl super::SafeSliceAccess for u32 {} impl super::SafeSliceAccess for u64 {} impl super::SafeSliceAccess for i16 {} impl super::SafeSliceAccess for i32 {} impl super::SafeSliceAccess for i64 {} impl super::SafeSliceAccess for f32 {} impl super::SafeSliceAccess for f64 {} } pub use self::le_safe_slice_impls::*; pub fn follow_cast_ref<'a, T: Sized + 'a>(buf: &'a [u8], loc: usize) -> &'a T
impl<'a> Follow<'a> for &'a str { type Inner = &'a str; fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { let len = read_scalar::<UOffsetT>(&buf[loc..loc + SIZE_UOFFSET]) as usize; let slice = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len]; let s = unsafe { from_utf8_unchecked(slice) }; s } } fn follow_slice_helper<T>(buf: &[u8], loc: usize) -> &[T] { let sz = size_of::<T>(); debug_assert!(sz > 0); let len = read_scalar::<UOffsetT>(&buf[loc..loc + SIZE_UOFFSET]) as usize; let data_buf = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len * sz]; let ptr = data_buf.as_ptr() as *const T; let s: &[T] = unsafe { from_raw_parts(ptr, len) }; s } /// Implement direct slice access if the host is little-endian. #[cfg(target_endian = "little")] impl<'a, T: EndianScalar> Follow<'a> for &'a [T] { type Inner = &'a [T]; fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { follow_slice_helper::<T>(buf, loc) } } /// Implement Follow for all possible Vectors that have Follow-able elements. impl<'a, T: Follow<'a> + 'a> Follow<'a> for Vector<'a, T> { type Inner = Vector<'a, T>; fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { Vector::new(buf, loc) } }
{ let sz = size_of::<T>(); let buf = &buf[loc..loc + sz]; let ptr = buf.as_ptr() as *const T; unsafe { &*ptr } }
identifier_body
vector.rs
/* * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::marker::PhantomData; use std::mem::size_of; use std::slice::from_raw_parts; use std::str::from_utf8_unchecked;
use primitives::*; #[derive(Debug)] pub struct Vector<'a, T: 'a>(&'a [u8], usize, PhantomData<T>); impl<'a, T: 'a> Vector<'a, T> { #[inline(always)] pub fn new(buf: &'a [u8], loc: usize) -> Self { Vector { 0: buf, 1: loc, 2: PhantomData, } } #[inline(always)] pub fn len(&self) -> usize { read_scalar::<UOffsetT>(&self.0[self.1 as usize..]) as usize } } impl<'a, T: Follow<'a> + 'a> Vector<'a, T> { #[inline(always)] pub fn get(&self, idx: usize) -> T::Inner { debug_assert!(idx < read_scalar::<u32>(&self.0[self.1 as usize..]) as usize); let sz = size_of::<T>(); debug_assert!(sz > 0); T::follow(self.0, self.1 as usize + SIZE_UOFFSET + sz * idx) } } pub trait SafeSliceAccess {} impl<'a, T: SafeSliceAccess + 'a> Vector<'a, T> { pub fn safe_slice(self) -> &'a [T] { let buf = self.0; let loc = self.1; let sz = size_of::<T>(); debug_assert!(sz > 0); let len = read_scalar::<UOffsetT>(&buf[loc..loc + SIZE_UOFFSET]) as usize; let data_buf = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len * sz]; let ptr = data_buf.as_ptr() as *const T; let s: &'a [T] = unsafe { from_raw_parts(ptr, len) }; s } } impl SafeSliceAccess for u8 {} impl SafeSliceAccess for i8 {} impl SafeSliceAccess for bool {} #[cfg(target_endian = "little")] mod le_safe_slice_impls { impl super::SafeSliceAccess for u16 {} impl super::SafeSliceAccess for u32 {} impl super::SafeSliceAccess for u64 {} impl super::SafeSliceAccess for i16 {} impl super::SafeSliceAccess for i32 {} impl super::SafeSliceAccess for i64 {} impl super::SafeSliceAccess for f32 {} impl super::SafeSliceAccess for f64 {} } pub use self::le_safe_slice_impls::*; pub fn follow_cast_ref<'a, T: Sized + 'a>(buf: &'a [u8], loc: usize) -> &'a T { let sz = size_of::<T>(); let buf = &buf[loc..loc + sz]; let ptr = buf.as_ptr() as *const T; unsafe { &*ptr } } impl<'a> Follow<'a> for &'a str { type Inner = &'a str; fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { let len = read_scalar::<UOffsetT>(&buf[loc..loc + SIZE_UOFFSET]) as usize; let slice = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len]; let s = unsafe { from_utf8_unchecked(slice) }; s } } fn follow_slice_helper<T>(buf: &[u8], loc: usize) -> &[T] { let sz = size_of::<T>(); debug_assert!(sz > 0); let len = read_scalar::<UOffsetT>(&buf[loc..loc + SIZE_UOFFSET]) as usize; let data_buf = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len * sz]; let ptr = data_buf.as_ptr() as *const T; let s: &[T] = unsafe { from_raw_parts(ptr, len) }; s } /// Implement direct slice access if the host is little-endian. #[cfg(target_endian = "little")] impl<'a, T: EndianScalar> Follow<'a> for &'a [T] { type Inner = &'a [T]; fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { follow_slice_helper::<T>(buf, loc) } } /// Implement Follow for all possible Vectors that have Follow-able elements. impl<'a, T: Follow<'a> + 'a> Follow<'a> for Vector<'a, T> { type Inner = Vector<'a, T>; fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { Vector::new(buf, loc) } }
use endian_scalar::{EndianScalar, read_scalar}; use follow::Follow;
random_line_split
numbers.rs
//! Functions operating on numbers. use std::sync::Mutex; use rand::{StdRng, Rng, SeedableRng}; use lisp::LispObject; use remacs_sys::{EmacsInt, INTMASK}; use remacs_macros::lisp_fn; lazy_static! { static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap()); } /// Return t if OBJECT is a floating point number. #[lisp_fn] fn floatp(object: LispObject) -> LispObject { LispObject::from_bool(object.is_float()) } /// Return t if OBJECT is an integer. #[lisp_fn] fn integerp(object: LispObject) -> LispObject { LispObject::from_bool(object.is_integer()) } /// Return t if OBJECT is an integer or a marker (editor pointer). #[lisp_fn] fn integer_or_marker_p(object: LispObject) -> LispObject { LispObject::from_bool(object.is_marker() || object.is_integer()) } /// Return t if OBJECT is a non-negative integer. #[lisp_fn]
#[lisp_fn] fn numberp(object: LispObject) -> LispObject { LispObject::from_bool(object.is_number()) } /// Return t if OBJECT is a number or a marker (editor pointer). #[lisp_fn] fn number_or_marker_p(object: LispObject) -> LispObject { LispObject::from_bool(object.is_number() || object.is_marker()) } /// Return a pseudo-random number. /// All integers representable in Lisp, i.e. between `most-negative-fixnum' /// and `most-positive-fixnum', inclusive, are equally likely. /// /// With positive integer LIMIT, return random number in interval [0,LIMIT). /// With argument t, set the random number seed from the system's entropy /// pool if available, otherwise from less-random volatile data such as the time. /// With a string argument, set the seed based on the string's contents. /// Other values of LIMIT are ignored. /// /// See Info node `(elisp)Random Numbers' for more details. #[lisp_fn(min = "0")] fn random(limit: LispObject) -> LispObject { let mut rng = RNG.lock().unwrap(); if limit == LispObject::constant_t() { *rng = StdRng::new().unwrap(); } else if let Some(s) = limit.as_string() { let values: Vec<usize> = s.as_slice().iter().map(|&x| x as usize).collect(); rng.reseed(&values); } if let Some(limit) = limit.as_fixnum() { // Return the remainder, except reject the rare case where // get_random returns a number so close to INTMASK that the // remainder isn't random. loop { let val: EmacsInt = rng.gen(); let remainder = val.abs() % limit; if val - remainder <= INTMASK - limit + 1 { return LispObject::from_fixnum(remainder); } } } else { LispObject::from_fixnum_truncated(rng.gen()) } }
fn natnump(object: LispObject) -> LispObject { LispObject::from_bool(object.is_natnum()) } /// Return t if OBJECT is a number (floating point or integer).
random_line_split
numbers.rs
//! Functions operating on numbers. use std::sync::Mutex; use rand::{StdRng, Rng, SeedableRng}; use lisp::LispObject; use remacs_sys::{EmacsInt, INTMASK}; use remacs_macros::lisp_fn; lazy_static! { static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap()); } /// Return t if OBJECT is a floating point number. #[lisp_fn] fn
(object: LispObject) -> LispObject { LispObject::from_bool(object.is_float()) } /// Return t if OBJECT is an integer. #[lisp_fn] fn integerp(object: LispObject) -> LispObject { LispObject::from_bool(object.is_integer()) } /// Return t if OBJECT is an integer or a marker (editor pointer). #[lisp_fn] fn integer_or_marker_p(object: LispObject) -> LispObject { LispObject::from_bool(object.is_marker() || object.is_integer()) } /// Return t if OBJECT is a non-negative integer. #[lisp_fn] fn natnump(object: LispObject) -> LispObject { LispObject::from_bool(object.is_natnum()) } /// Return t if OBJECT is a number (floating point or integer). #[lisp_fn] fn numberp(object: LispObject) -> LispObject { LispObject::from_bool(object.is_number()) } /// Return t if OBJECT is a number or a marker (editor pointer). #[lisp_fn] fn number_or_marker_p(object: LispObject) -> LispObject { LispObject::from_bool(object.is_number() || object.is_marker()) } /// Return a pseudo-random number. /// All integers representable in Lisp, i.e. between `most-negative-fixnum' /// and `most-positive-fixnum', inclusive, are equally likely. /// /// With positive integer LIMIT, return random number in interval [0,LIMIT). /// With argument t, set the random number seed from the system's entropy /// pool if available, otherwise from less-random volatile data such as the time. /// With a string argument, set the seed based on the string's contents. /// Other values of LIMIT are ignored. /// /// See Info node `(elisp)Random Numbers' for more details. #[lisp_fn(min = "0")] fn random(limit: LispObject) -> LispObject { let mut rng = RNG.lock().unwrap(); if limit == LispObject::constant_t() { *rng = StdRng::new().unwrap(); } else if let Some(s) = limit.as_string() { let values: Vec<usize> = s.as_slice().iter().map(|&x| x as usize).collect(); rng.reseed(&values); } if let Some(limit) = limit.as_fixnum() { // Return the remainder, except reject the rare case where // get_random returns a number so close to INTMASK that the // remainder isn't random. loop { let val: EmacsInt = rng.gen(); let remainder = val.abs() % limit; if val - remainder <= INTMASK - limit + 1 { return LispObject::from_fixnum(remainder); } } } else { LispObject::from_fixnum_truncated(rng.gen()) } }
floatp
identifier_name
numbers.rs
//! Functions operating on numbers. use std::sync::Mutex; use rand::{StdRng, Rng, SeedableRng}; use lisp::LispObject; use remacs_sys::{EmacsInt, INTMASK}; use remacs_macros::lisp_fn; lazy_static! { static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap()); } /// Return t if OBJECT is a floating point number. #[lisp_fn] fn floatp(object: LispObject) -> LispObject { LispObject::from_bool(object.is_float()) } /// Return t if OBJECT is an integer. #[lisp_fn] fn integerp(object: LispObject) -> LispObject { LispObject::from_bool(object.is_integer()) } /// Return t if OBJECT is an integer or a marker (editor pointer). #[lisp_fn] fn integer_or_marker_p(object: LispObject) -> LispObject { LispObject::from_bool(object.is_marker() || object.is_integer()) } /// Return t if OBJECT is a non-negative integer. #[lisp_fn] fn natnump(object: LispObject) -> LispObject { LispObject::from_bool(object.is_natnum()) } /// Return t if OBJECT is a number (floating point or integer). #[lisp_fn] fn numberp(object: LispObject) -> LispObject { LispObject::from_bool(object.is_number()) } /// Return t if OBJECT is a number or a marker (editor pointer). #[lisp_fn] fn number_or_marker_p(object: LispObject) -> LispObject { LispObject::from_bool(object.is_number() || object.is_marker()) } /// Return a pseudo-random number. /// All integers representable in Lisp, i.e. between `most-negative-fixnum' /// and `most-positive-fixnum', inclusive, are equally likely. /// /// With positive integer LIMIT, return random number in interval [0,LIMIT). /// With argument t, set the random number seed from the system's entropy /// pool if available, otherwise from less-random volatile data such as the time. /// With a string argument, set the seed based on the string's contents. /// Other values of LIMIT are ignored. /// /// See Info node `(elisp)Random Numbers' for more details. #[lisp_fn(min = "0")] fn random(limit: LispObject) -> LispObject
} else { LispObject::from_fixnum_truncated(rng.gen()) } }
{ let mut rng = RNG.lock().unwrap(); if limit == LispObject::constant_t() { *rng = StdRng::new().unwrap(); } else if let Some(s) = limit.as_string() { let values: Vec<usize> = s.as_slice().iter().map(|&x| x as usize).collect(); rng.reseed(&values); } if let Some(limit) = limit.as_fixnum() { // Return the remainder, except reject the rare case where // get_random returns a number so close to INTMASK that the // remainder isn't random. loop { let val: EmacsInt = rng.gen(); let remainder = val.abs() % limit; if val - remainder <= INTMASK - limit + 1 { return LispObject::from_fixnum(remainder); } }
identifier_body
numbers.rs
//! Functions operating on numbers. use std::sync::Mutex; use rand::{StdRng, Rng, SeedableRng}; use lisp::LispObject; use remacs_sys::{EmacsInt, INTMASK}; use remacs_macros::lisp_fn; lazy_static! { static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap()); } /// Return t if OBJECT is a floating point number. #[lisp_fn] fn floatp(object: LispObject) -> LispObject { LispObject::from_bool(object.is_float()) } /// Return t if OBJECT is an integer. #[lisp_fn] fn integerp(object: LispObject) -> LispObject { LispObject::from_bool(object.is_integer()) } /// Return t if OBJECT is an integer or a marker (editor pointer). #[lisp_fn] fn integer_or_marker_p(object: LispObject) -> LispObject { LispObject::from_bool(object.is_marker() || object.is_integer()) } /// Return t if OBJECT is a non-negative integer. #[lisp_fn] fn natnump(object: LispObject) -> LispObject { LispObject::from_bool(object.is_natnum()) } /// Return t if OBJECT is a number (floating point or integer). #[lisp_fn] fn numberp(object: LispObject) -> LispObject { LispObject::from_bool(object.is_number()) } /// Return t if OBJECT is a number or a marker (editor pointer). #[lisp_fn] fn number_or_marker_p(object: LispObject) -> LispObject { LispObject::from_bool(object.is_number() || object.is_marker()) } /// Return a pseudo-random number. /// All integers representable in Lisp, i.e. between `most-negative-fixnum' /// and `most-positive-fixnum', inclusive, are equally likely. /// /// With positive integer LIMIT, return random number in interval [0,LIMIT). /// With argument t, set the random number seed from the system's entropy /// pool if available, otherwise from less-random volatile data such as the time. /// With a string argument, set the seed based on the string's contents. /// Other values of LIMIT are ignored. /// /// See Info node `(elisp)Random Numbers' for more details. #[lisp_fn(min = "0")] fn random(limit: LispObject) -> LispObject { let mut rng = RNG.lock().unwrap(); if limit == LispObject::constant_t() { *rng = StdRng::new().unwrap(); } else if let Some(s) = limit.as_string() { let values: Vec<usize> = s.as_slice().iter().map(|&x| x as usize).collect(); rng.reseed(&values); } if let Some(limit) = limit.as_fixnum() { // Return the remainder, except reject the rare case where // get_random returns a number so close to INTMASK that the // remainder isn't random. loop { let val: EmacsInt = rng.gen(); let remainder = val.abs() % limit; if val - remainder <= INTMASK - limit + 1 { return LispObject::from_fixnum(remainder); } } } else
}
{ LispObject::from_fixnum_truncated(rng.gen()) }
conditional_block
imp.rs
// Copyright (C) 2019 Guillaume Desmottes <[email protected]> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use glib::subclass; use glib::subclass::prelude::*; use gst::subclass::prelude::*; use gst::{gst_debug, gst_element_error}; use gst_video::prelude::VideoDecoderExtManual; use gst_video::prelude::*; use gst_video::subclass::prelude::*; use image::GenericImageView; use once_cell::sync::Lazy; use std::sync::Mutex; use crate::constants::{CDG_HEIGHT, CDG_WIDTH}; static CAT: Lazy<gst::DebugCategory> = Lazy::new(|| { gst::DebugCategory::new("cdgdec", gst::DebugColorFlags::empty(), Some("CDG decoder")) }); pub struct CdgDec { cdg_inter: Mutex<Box<cdg_renderer::CdgInterpreter>>, output_info: Mutex<Option<gst_video::VideoInfo>>, } impl ObjectSubclass for CdgDec { const NAME: &'static str = "CdgDec"; type Type = super::CdgDec; type ParentType = gst_video::VideoDecoder; type Instance = gst::subclass::ElementInstanceStruct<Self>; type Class = subclass::simple::ClassStruct<Self>; glib::glib_object_subclass!(); fn new() -> Self { Self { cdg_inter: Mutex::new(Box::new(cdg_renderer::CdgInterpreter::new())), output_info: Mutex::new(None), } } fn class_init(klass: &mut Self::Class) { klass.set_metadata(
"Decoder/Video", "CDG decoder", "Guillaume Desmottes <[email protected]>", ); let sink_caps = gst::Caps::new_simple("video/x-cdg", &[("parsed", &true)]); let sink_pad_template = gst::PadTemplate::new( "sink", gst::PadDirection::Sink, gst::PadPresence::Always, &sink_caps, ) .unwrap(); klass.add_pad_template(sink_pad_template); let src_caps = gst::Caps::new_simple( "video/x-raw", &[ ("format", &gst_video::VideoFormat::Rgba.to_str()), ("width", &(CDG_WIDTH as i32)), ("height", &(CDG_HEIGHT as i32)), ("framerate", &gst::Fraction::new(0, 1)), ], ); let src_pad_template = gst::PadTemplate::new( "src", gst::PadDirection::Src, gst::PadPresence::Always, &src_caps, ) .unwrap(); klass.add_pad_template(src_pad_template); } } impl ObjectImpl for CdgDec {} impl ElementImpl for CdgDec {} impl VideoDecoderImpl for CdgDec { fn start(&self, element: &Self::Type) -> Result<(), gst::ErrorMessage> { let mut out_info = self.output_info.lock().unwrap(); *out_info = None; self.parent_start(element) } fn stop(&self, element: &Self::Type) -> Result<(), gst::ErrorMessage> { { let mut cdg_inter = self.cdg_inter.lock().unwrap(); cdg_inter.reset(true); } self.parent_stop(element) } fn handle_frame( &self, element: &Self::Type, mut frame: gst_video::VideoCodecFrame, ) -> Result<gst::FlowSuccess, gst::FlowError> { { let mut out_info = self.output_info.lock().unwrap(); if out_info.is_none() { let output_state = element.set_output_state( gst_video::VideoFormat::Rgba, CDG_WIDTH, CDG_HEIGHT, None, )?; element.negotiate(output_state)?; let out_state = element.get_output_state().unwrap(); *out_info = Some(out_state.get_info()); } } let cmd = { let input = frame.get_input_buffer().unwrap(); let map = input.map_readable().map_err(|_| { gst_element_error!( element, gst::CoreError::Failed, ["Failed to map input buffer readable"] ); gst::FlowError::Error })?; let data = map.as_slice(); cdg::decode_subchannel_cmd(&data) }; let cmd = match cmd { Some(cmd) => cmd, None => { // Not a CDG command element.release_frame(frame); return Ok(gst::FlowSuccess::Ok); } }; let mut cdg_inter = self.cdg_inter.lock().unwrap(); cdg_inter.handle_cmd(cmd); element.allocate_output_frame(&mut frame, None)?; { let output = frame.get_output_buffer_mut().unwrap(); let info = self.output_info.lock().unwrap(); let mut out_frame = gst_video::VideoFrameRef::from_buffer_ref_writable(output, info.as_ref().unwrap()) .map_err(|_| { gst_element_error!( element, gst::CoreError::Failed, ["Failed to map output buffer writable"] ); gst::FlowError::Error })?; let out_stride = out_frame.plane_stride()[0] as usize; for (y, line) in out_frame .plane_data_mut(0) .unwrap() .chunks_exact_mut(out_stride) .take(CDG_HEIGHT as usize) .enumerate() { for (x, pixel) in line .chunks_exact_mut(4) .take(CDG_WIDTH as usize) .enumerate() { let p = cdg_inter.get_pixel(x as u32, y as u32); pixel.copy_from_slice(&p.0); } } } gst_debug!(CAT, obj: element, "Finish frame pts={}", frame.get_pts()); element.finish_frame(frame) } fn decide_allocation( &self, element: &Self::Type, query: &mut gst::QueryRef, ) -> Result<(), gst::ErrorMessage> { if let gst::query::QueryView::Allocation(allocation) = query.view() { if allocation .find_allocation_meta::<gst_video::VideoMeta>() .is_some() { let pools = allocation.get_allocation_pools(); if let Some((ref pool, _, _, _)) = pools.first() { if let Some(pool) = pool { let mut config = pool.get_config(); config.add_option(&gst_video::BUFFER_POOL_OPTION_VIDEO_META); pool.set_config(config).map_err(|e| { gst::gst_error_msg!(gst::CoreError::Negotiation, [&e.message]) })?; } } } } self.parent_decide_allocation(element, query) } fn flush(&self, element: &Self::Type) -> bool { gst_debug!(CAT, obj: element, "flushing, reset CDG interpreter"); let mut cdg_inter = self.cdg_inter.lock().unwrap(); cdg_inter.reset(false); true } }
"CDG decoder",
random_line_split
imp.rs
// Copyright (C) 2019 Guillaume Desmottes <[email protected]> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use glib::subclass; use glib::subclass::prelude::*; use gst::subclass::prelude::*; use gst::{gst_debug, gst_element_error}; use gst_video::prelude::VideoDecoderExtManual; use gst_video::prelude::*; use gst_video::subclass::prelude::*; use image::GenericImageView; use once_cell::sync::Lazy; use std::sync::Mutex; use crate::constants::{CDG_HEIGHT, CDG_WIDTH}; static CAT: Lazy<gst::DebugCategory> = Lazy::new(|| { gst::DebugCategory::new("cdgdec", gst::DebugColorFlags::empty(), Some("CDG decoder")) }); pub struct CdgDec { cdg_inter: Mutex<Box<cdg_renderer::CdgInterpreter>>, output_info: Mutex<Option<gst_video::VideoInfo>>, } impl ObjectSubclass for CdgDec { const NAME: &'static str = "CdgDec"; type Type = super::CdgDec; type ParentType = gst_video::VideoDecoder; type Instance = gst::subclass::ElementInstanceStruct<Self>; type Class = subclass::simple::ClassStruct<Self>; glib::glib_object_subclass!(); fn new() -> Self { Self { cdg_inter: Mutex::new(Box::new(cdg_renderer::CdgInterpreter::new())), output_info: Mutex::new(None), } } fn class_init(klass: &mut Self::Class) { klass.set_metadata( "CDG decoder", "Decoder/Video", "CDG decoder", "Guillaume Desmottes <[email protected]>", ); let sink_caps = gst::Caps::new_simple("video/x-cdg", &[("parsed", &true)]); let sink_pad_template = gst::PadTemplate::new( "sink", gst::PadDirection::Sink, gst::PadPresence::Always, &sink_caps, ) .unwrap(); klass.add_pad_template(sink_pad_template); let src_caps = gst::Caps::new_simple( "video/x-raw", &[ ("format", &gst_video::VideoFormat::Rgba.to_str()), ("width", &(CDG_WIDTH as i32)), ("height", &(CDG_HEIGHT as i32)), ("framerate", &gst::Fraction::new(0, 1)), ], ); let src_pad_template = gst::PadTemplate::new( "src", gst::PadDirection::Src, gst::PadPresence::Always, &src_caps, ) .unwrap(); klass.add_pad_template(src_pad_template); } } impl ObjectImpl for CdgDec {} impl ElementImpl for CdgDec {} impl VideoDecoderImpl for CdgDec { fn start(&self, element: &Self::Type) -> Result<(), gst::ErrorMessage> { let mut out_info = self.output_info.lock().unwrap(); *out_info = None; self.parent_start(element) } fn stop(&self, element: &Self::Type) -> Result<(), gst::ErrorMessage> { { let mut cdg_inter = self.cdg_inter.lock().unwrap(); cdg_inter.reset(true); } self.parent_stop(element) } fn handle_frame( &self, element: &Self::Type, mut frame: gst_video::VideoCodecFrame, ) -> Result<gst::FlowSuccess, gst::FlowError> { { let mut out_info = self.output_info.lock().unwrap(); if out_info.is_none() { let output_state = element.set_output_state( gst_video::VideoFormat::Rgba, CDG_WIDTH, CDG_HEIGHT, None, )?; element.negotiate(output_state)?; let out_state = element.get_output_state().unwrap(); *out_info = Some(out_state.get_info()); } } let cmd = { let input = frame.get_input_buffer().unwrap(); let map = input.map_readable().map_err(|_| { gst_element_error!( element, gst::CoreError::Failed, ["Failed to map input buffer readable"] ); gst::FlowError::Error })?; let data = map.as_slice(); cdg::decode_subchannel_cmd(&data) }; let cmd = match cmd { Some(cmd) => cmd, None => { // Not a CDG command element.release_frame(frame); return Ok(gst::FlowSuccess::Ok); } }; let mut cdg_inter = self.cdg_inter.lock().unwrap(); cdg_inter.handle_cmd(cmd); element.allocate_output_frame(&mut frame, None)?; { let output = frame.get_output_buffer_mut().unwrap(); let info = self.output_info.lock().unwrap(); let mut out_frame = gst_video::VideoFrameRef::from_buffer_ref_writable(output, info.as_ref().unwrap()) .map_err(|_| { gst_element_error!( element, gst::CoreError::Failed, ["Failed to map output buffer writable"] ); gst::FlowError::Error })?; let out_stride = out_frame.plane_stride()[0] as usize; for (y, line) in out_frame .plane_data_mut(0) .unwrap() .chunks_exact_mut(out_stride) .take(CDG_HEIGHT as usize) .enumerate() { for (x, pixel) in line .chunks_exact_mut(4) .take(CDG_WIDTH as usize) .enumerate() { let p = cdg_inter.get_pixel(x as u32, y as u32); pixel.copy_from_slice(&p.0); } } } gst_debug!(CAT, obj: element, "Finish frame pts={}", frame.get_pts()); element.finish_frame(frame) } fn decide_allocation( &self, element: &Self::Type, query: &mut gst::QueryRef, ) -> Result<(), gst::ErrorMessage> { if let gst::query::QueryView::Allocation(allocation) = query.view() { if allocation .find_allocation_meta::<gst_video::VideoMeta>() .is_some() { let pools = allocation.get_allocation_pools(); if let Some((ref pool, _, _, _)) = pools.first() { if let Some(pool) = pool { let mut config = pool.get_config(); config.add_option(&gst_video::BUFFER_POOL_OPTION_VIDEO_META); pool.set_config(config).map_err(|e| { gst::gst_error_msg!(gst::CoreError::Negotiation, [&e.message]) })?; } } } } self.parent_decide_allocation(element, query) } fn
(&self, element: &Self::Type) -> bool { gst_debug!(CAT, obj: element, "flushing, reset CDG interpreter"); let mut cdg_inter = self.cdg_inter.lock().unwrap(); cdg_inter.reset(false); true } }
flush
identifier_name
imp.rs
// Copyright (C) 2019 Guillaume Desmottes <[email protected]> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use glib::subclass; use glib::subclass::prelude::*; use gst::subclass::prelude::*; use gst::{gst_debug, gst_element_error}; use gst_video::prelude::VideoDecoderExtManual; use gst_video::prelude::*; use gst_video::subclass::prelude::*; use image::GenericImageView; use once_cell::sync::Lazy; use std::sync::Mutex; use crate::constants::{CDG_HEIGHT, CDG_WIDTH}; static CAT: Lazy<gst::DebugCategory> = Lazy::new(|| { gst::DebugCategory::new("cdgdec", gst::DebugColorFlags::empty(), Some("CDG decoder")) }); pub struct CdgDec { cdg_inter: Mutex<Box<cdg_renderer::CdgInterpreter>>, output_info: Mutex<Option<gst_video::VideoInfo>>, } impl ObjectSubclass for CdgDec { const NAME: &'static str = "CdgDec"; type Type = super::CdgDec; type ParentType = gst_video::VideoDecoder; type Instance = gst::subclass::ElementInstanceStruct<Self>; type Class = subclass::simple::ClassStruct<Self>; glib::glib_object_subclass!(); fn new() -> Self { Self { cdg_inter: Mutex::new(Box::new(cdg_renderer::CdgInterpreter::new())), output_info: Mutex::new(None), } } fn class_init(klass: &mut Self::Class)
&[ ("format", &gst_video::VideoFormat::Rgba.to_str()), ("width", &(CDG_WIDTH as i32)), ("height", &(CDG_HEIGHT as i32)), ("framerate", &gst::Fraction::new(0, 1)), ], ); let src_pad_template = gst::PadTemplate::new( "src", gst::PadDirection::Src, gst::PadPresence::Always, &src_caps, ) .unwrap(); klass.add_pad_template(src_pad_template); } } impl ObjectImpl for CdgDec {} impl ElementImpl for CdgDec {} impl VideoDecoderImpl for CdgDec { fn start(&self, element: &Self::Type) -> Result<(), gst::ErrorMessage> { let mut out_info = self.output_info.lock().unwrap(); *out_info = None; self.parent_start(element) } fn stop(&self, element: &Self::Type) -> Result<(), gst::ErrorMessage> { { let mut cdg_inter = self.cdg_inter.lock().unwrap(); cdg_inter.reset(true); } self.parent_stop(element) } fn handle_frame( &self, element: &Self::Type, mut frame: gst_video::VideoCodecFrame, ) -> Result<gst::FlowSuccess, gst::FlowError> { { let mut out_info = self.output_info.lock().unwrap(); if out_info.is_none() { let output_state = element.set_output_state( gst_video::VideoFormat::Rgba, CDG_WIDTH, CDG_HEIGHT, None, )?; element.negotiate(output_state)?; let out_state = element.get_output_state().unwrap(); *out_info = Some(out_state.get_info()); } } let cmd = { let input = frame.get_input_buffer().unwrap(); let map = input.map_readable().map_err(|_| { gst_element_error!( element, gst::CoreError::Failed, ["Failed to map input buffer readable"] ); gst::FlowError::Error })?; let data = map.as_slice(); cdg::decode_subchannel_cmd(&data) }; let cmd = match cmd { Some(cmd) => cmd, None => { // Not a CDG command element.release_frame(frame); return Ok(gst::FlowSuccess::Ok); } }; let mut cdg_inter = self.cdg_inter.lock().unwrap(); cdg_inter.handle_cmd(cmd); element.allocate_output_frame(&mut frame, None)?; { let output = frame.get_output_buffer_mut().unwrap(); let info = self.output_info.lock().unwrap(); let mut out_frame = gst_video::VideoFrameRef::from_buffer_ref_writable(output, info.as_ref().unwrap()) .map_err(|_| { gst_element_error!( element, gst::CoreError::Failed, ["Failed to map output buffer writable"] ); gst::FlowError::Error })?; let out_stride = out_frame.plane_stride()[0] as usize; for (y, line) in out_frame .plane_data_mut(0) .unwrap() .chunks_exact_mut(out_stride) .take(CDG_HEIGHT as usize) .enumerate() { for (x, pixel) in line .chunks_exact_mut(4) .take(CDG_WIDTH as usize) .enumerate() { let p = cdg_inter.get_pixel(x as u32, y as u32); pixel.copy_from_slice(&p.0); } } } gst_debug!(CAT, obj: element, "Finish frame pts={}", frame.get_pts()); element.finish_frame(frame) } fn decide_allocation( &self, element: &Self::Type, query: &mut gst::QueryRef, ) -> Result<(), gst::ErrorMessage> { if let gst::query::QueryView::Allocation(allocation) = query.view() { if allocation .find_allocation_meta::<gst_video::VideoMeta>() .is_some() { let pools = allocation.get_allocation_pools(); if let Some((ref pool, _, _, _)) = pools.first() { if let Some(pool) = pool { let mut config = pool.get_config(); config.add_option(&gst_video::BUFFER_POOL_OPTION_VIDEO_META); pool.set_config(config).map_err(|e| { gst::gst_error_msg!(gst::CoreError::Negotiation, [&e.message]) })?; } } } } self.parent_decide_allocation(element, query) } fn flush(&self, element: &Self::Type) -> bool { gst_debug!(CAT, obj: element, "flushing, reset CDG interpreter"); let mut cdg_inter = self.cdg_inter.lock().unwrap(); cdg_inter.reset(false); true } }
{ klass.set_metadata( "CDG decoder", "Decoder/Video", "CDG decoder", "Guillaume Desmottes <[email protected]>", ); let sink_caps = gst::Caps::new_simple("video/x-cdg", &[("parsed", &true)]); let sink_pad_template = gst::PadTemplate::new( "sink", gst::PadDirection::Sink, gst::PadPresence::Always, &sink_caps, ) .unwrap(); klass.add_pad_template(sink_pad_template); let src_caps = gst::Caps::new_simple( "video/x-raw",
identifier_body
url.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::URLBinding::{self, URLMethods}; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{DomRoot, MutNullableDom}; use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::blob::Blob; use crate::dom::globalscope::GlobalScope; use crate::dom::urlhelper::UrlHelper; use crate::dom::urlsearchparams::URLSearchParams; use dom_struct::dom_struct; use net_traits::blob_url_store::{get_blob_origin, parse_blob_url}; use net_traits::filemanager_thread::FileManagerThreadMsg; use net_traits::{CoreResourceMsg, IpcSend}; use profile_traits::ipc; use servo_url::ServoUrl; use std::default::Default; use uuid::Uuid; // https://url.spec.whatwg.org/#url #[dom_struct] pub struct URL { reflector_: Reflector, // https://url.spec.whatwg.org/#concept-url-url url: DomRefCell<ServoUrl>, // https://url.spec.whatwg.org/#dom-url-searchparams search_params: MutNullableDom<URLSearchParams>, } impl URL { fn new_inherited(url: ServoUrl) -> URL { URL { reflector_: Reflector::new(), url: DomRefCell::new(url), search_params: Default::default(), } } pub fn new(global: &GlobalScope, url: ServoUrl) -> DomRoot<URL> { reflect_dom_object(Box::new(URL::new_inherited(url)), global, URLBinding::Wrap) } pub fn query_pairs(&self) -> Vec<(String, String)> { self.url .borrow() .as_url() .query_pairs() .into_owned() .collect() } pub fn set_query_pairs(&self, pairs: &[(String, String)]) { let mut url = self.url.borrow_mut(); if pairs.is_empty() { url.as_mut_url().set_query(None); } else { url.as_mut_url() .query_pairs_mut() .clear() .extend_pairs(pairs); } } } impl URL { // https://url.spec.whatwg.org/#constructors pub fn Constructor( global: &GlobalScope, url: USVString, base: Option<USVString>, ) -> Fallible<DomRoot<URL>> { let parsed_base = match base { None => { // Step 1. None }, Some(base) => // Step 2.1. { match ServoUrl::parse(&base.0) { Ok(base) => Some(base), Err(error) => { // Step 2.2. return Err(Error::Type(format!("could not parse base: {}", error))); }, } } }; // Step 3. let parsed_url = match ServoUrl::parse_with_base(parsed_base.as_ref(), &url.0) { Ok(url) => url, Err(error) => { // Step 4. return Err(Error::Type(format!("could not parse URL: {}", error))); }, }; // Step 5: Skip (see step 8 below). // Steps 6-7. let result = URL::new(global, parsed_url); // Step 8: Instead of construcing a new `URLSearchParams` object here, construct it // on-demand inside `URL::SearchParams`. // Step 9. Ok(result) } // https://w3c.github.io/FileAPI/#dfn-createObjectURL pub fn CreateObjectURL(global: &GlobalScope, blob: &Blob) -> DOMString { // XXX: Second field is an unicode-serialized Origin, it is a temporary workaround // and should not be trusted. See issue https://github.com/servo/servo/issues/11722 let origin = get_blob_origin(&global.get_url()); let id = blob.get_blob_url_id(); DOMString::from(URL::unicode_serialization_blob_url(&origin, &id)) } // https://w3c.github.io/FileAPI/#dfn-revokeObjectURL pub fn RevokeObjectURL(global: &GlobalScope, url: DOMString) { // If the value provided for the url argument is not a Blob URL OR // if the value provided for the url argument does not have an entry in the Blob URL Store, // this method call does nothing. User agents may display a message on the error console. let origin = get_blob_origin(&global.get_url()); if let Ok(url) = ServoUrl::parse(&url) { if let Ok((id, _)) = parse_blob_url(&url) { let resource_threads = global.resource_threads(); let (tx, rx) = ipc::channel(global.time_profiler_chan().clone()).unwrap(); let msg = FileManagerThreadMsg::RevokeBlobURL(id, origin, tx); let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)); let _ = rx.recv().unwrap(); } } } // https://w3c.github.io/FileAPI/#unicodeSerializationOfBlobURL fn unicode_serialization_blob_url(origin: &str, id: &Uuid) -> String { // Step 1, 2 let mut result = "blob:".to_string(); // Step 3 result.push_str(origin); // Step 4 result.push('/'); // Step 5 result.push_str(&id.to_simple().to_string()); result } } impl URLMethods for URL { // https://url.spec.whatwg.org/#dom-url-hash fn Hash(&self) -> USVString { UrlHelper::Hash(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-hash fn SetHash(&self, value: USVString) { UrlHelper::SetHash(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-host fn Host(&self) -> USVString { UrlHelper::Host(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-host fn SetHost(&self, value: USVString) { UrlHelper::SetHost(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-hostname fn Hostname(&self) -> USVString { UrlHelper::Hostname(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-hostname fn SetHostname(&self, value: USVString) { UrlHelper::SetHostname(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-href fn Href(&self) -> USVString { UrlHelper::Href(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-href fn SetHref(&self, value: USVString) -> ErrorResult { match ServoUrl::parse(&value.0) { Ok(url) => { *self.url.borrow_mut() = url; self.search_params.set(None); // To be re-initialized in the SearchParams getter. Ok(()) }, Err(error) => Err(Error::Type(format!("could not parse URL: {}", error))), } } // https://url.spec.whatwg.org/#dom-url-password fn Password(&self) -> USVString { UrlHelper::Password(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-password fn SetPassword(&self, value: USVString) { UrlHelper::SetPassword(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-pathname fn Pathname(&self) -> USVString { UrlHelper::Pathname(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-pathname fn SetPathname(&self, value: USVString) { UrlHelper::SetPathname(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-port fn Port(&self) -> USVString { UrlHelper::Port(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-port fn SetPort(&self, value: USVString) { UrlHelper::SetPort(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-protocol fn Protocol(&self) -> USVString { UrlHelper::Protocol(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-protocol fn SetProtocol(&self, value: USVString) { UrlHelper::SetProtocol(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-origin fn Origin(&self) -> USVString { UrlHelper::Origin(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-search fn Search(&self) -> USVString { UrlHelper::Search(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-search fn SetSearch(&self, value: USVString) { UrlHelper::SetSearch(&mut self.url.borrow_mut(), value); if let Some(search_params) = self.search_params.get()
} // https://url.spec.whatwg.org/#dom-url-searchparams fn SearchParams(&self) -> DomRoot<URLSearchParams> { self.search_params .or_init(|| URLSearchParams::new(&self.global(), Some(self))) } // https://url.spec.whatwg.org/#dom-url-href fn Stringifier(&self) -> DOMString { DOMString::from(self.Href().0) } // https://url.spec.whatwg.org/#dom-url-username fn Username(&self) -> USVString { UrlHelper::Username(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-username fn SetUsername(&self, value: USVString) { UrlHelper::SetUsername(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-tojson fn ToJSON(&self) -> USVString { self.Href() } }
{ search_params.set_list(self.query_pairs()); }
conditional_block
url.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::URLBinding::{self, URLMethods}; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{DomRoot, MutNullableDom}; use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::blob::Blob; use crate::dom::globalscope::GlobalScope; use crate::dom::urlhelper::UrlHelper; use crate::dom::urlsearchparams::URLSearchParams; use dom_struct::dom_struct; use net_traits::blob_url_store::{get_blob_origin, parse_blob_url}; use net_traits::filemanager_thread::FileManagerThreadMsg; use net_traits::{CoreResourceMsg, IpcSend}; use profile_traits::ipc; use servo_url::ServoUrl; use std::default::Default; use uuid::Uuid; // https://url.spec.whatwg.org/#url #[dom_struct] pub struct URL { reflector_: Reflector, // https://url.spec.whatwg.org/#concept-url-url url: DomRefCell<ServoUrl>, // https://url.spec.whatwg.org/#dom-url-searchparams search_params: MutNullableDom<URLSearchParams>, } impl URL { fn new_inherited(url: ServoUrl) -> URL { URL { reflector_: Reflector::new(), url: DomRefCell::new(url), search_params: Default::default(), } } pub fn new(global: &GlobalScope, url: ServoUrl) -> DomRoot<URL> { reflect_dom_object(Box::new(URL::new_inherited(url)), global, URLBinding::Wrap) } pub fn query_pairs(&self) -> Vec<(String, String)> { self.url .borrow() .as_url() .query_pairs() .into_owned() .collect() } pub fn set_query_pairs(&self, pairs: &[(String, String)]) { let mut url = self.url.borrow_mut(); if pairs.is_empty() { url.as_mut_url().set_query(None); } else { url.as_mut_url() .query_pairs_mut() .clear() .extend_pairs(pairs); } } } impl URL { // https://url.spec.whatwg.org/#constructors pub fn Constructor( global: &GlobalScope, url: USVString, base: Option<USVString>, ) -> Fallible<DomRoot<URL>> { let parsed_base = match base { None => { // Step 1. None }, Some(base) => // Step 2.1.
Err(error) => { // Step 2.2. return Err(Error::Type(format!("could not parse base: {}", error))); }, } } }; // Step 3. let parsed_url = match ServoUrl::parse_with_base(parsed_base.as_ref(), &url.0) { Ok(url) => url, Err(error) => { // Step 4. return Err(Error::Type(format!("could not parse URL: {}", error))); }, }; // Step 5: Skip (see step 8 below). // Steps 6-7. let result = URL::new(global, parsed_url); // Step 8: Instead of construcing a new `URLSearchParams` object here, construct it // on-demand inside `URL::SearchParams`. // Step 9. Ok(result) } // https://w3c.github.io/FileAPI/#dfn-createObjectURL pub fn CreateObjectURL(global: &GlobalScope, blob: &Blob) -> DOMString { // XXX: Second field is an unicode-serialized Origin, it is a temporary workaround // and should not be trusted. See issue https://github.com/servo/servo/issues/11722 let origin = get_blob_origin(&global.get_url()); let id = blob.get_blob_url_id(); DOMString::from(URL::unicode_serialization_blob_url(&origin, &id)) } // https://w3c.github.io/FileAPI/#dfn-revokeObjectURL pub fn RevokeObjectURL(global: &GlobalScope, url: DOMString) { // If the value provided for the url argument is not a Blob URL OR // if the value provided for the url argument does not have an entry in the Blob URL Store, // this method call does nothing. User agents may display a message on the error console. let origin = get_blob_origin(&global.get_url()); if let Ok(url) = ServoUrl::parse(&url) { if let Ok((id, _)) = parse_blob_url(&url) { let resource_threads = global.resource_threads(); let (tx, rx) = ipc::channel(global.time_profiler_chan().clone()).unwrap(); let msg = FileManagerThreadMsg::RevokeBlobURL(id, origin, tx); let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)); let _ = rx.recv().unwrap(); } } } // https://w3c.github.io/FileAPI/#unicodeSerializationOfBlobURL fn unicode_serialization_blob_url(origin: &str, id: &Uuid) -> String { // Step 1, 2 let mut result = "blob:".to_string(); // Step 3 result.push_str(origin); // Step 4 result.push('/'); // Step 5 result.push_str(&id.to_simple().to_string()); result } } impl URLMethods for URL { // https://url.spec.whatwg.org/#dom-url-hash fn Hash(&self) -> USVString { UrlHelper::Hash(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-hash fn SetHash(&self, value: USVString) { UrlHelper::SetHash(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-host fn Host(&self) -> USVString { UrlHelper::Host(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-host fn SetHost(&self, value: USVString) { UrlHelper::SetHost(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-hostname fn Hostname(&self) -> USVString { UrlHelper::Hostname(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-hostname fn SetHostname(&self, value: USVString) { UrlHelper::SetHostname(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-href fn Href(&self) -> USVString { UrlHelper::Href(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-href fn SetHref(&self, value: USVString) -> ErrorResult { match ServoUrl::parse(&value.0) { Ok(url) => { *self.url.borrow_mut() = url; self.search_params.set(None); // To be re-initialized in the SearchParams getter. Ok(()) }, Err(error) => Err(Error::Type(format!("could not parse URL: {}", error))), } } // https://url.spec.whatwg.org/#dom-url-password fn Password(&self) -> USVString { UrlHelper::Password(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-password fn SetPassword(&self, value: USVString) { UrlHelper::SetPassword(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-pathname fn Pathname(&self) -> USVString { UrlHelper::Pathname(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-pathname fn SetPathname(&self, value: USVString) { UrlHelper::SetPathname(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-port fn Port(&self) -> USVString { UrlHelper::Port(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-port fn SetPort(&self, value: USVString) { UrlHelper::SetPort(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-protocol fn Protocol(&self) -> USVString { UrlHelper::Protocol(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-protocol fn SetProtocol(&self, value: USVString) { UrlHelper::SetProtocol(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-origin fn Origin(&self) -> USVString { UrlHelper::Origin(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-search fn Search(&self) -> USVString { UrlHelper::Search(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-search fn SetSearch(&self, value: USVString) { UrlHelper::SetSearch(&mut self.url.borrow_mut(), value); if let Some(search_params) = self.search_params.get() { search_params.set_list(self.query_pairs()); } } // https://url.spec.whatwg.org/#dom-url-searchparams fn SearchParams(&self) -> DomRoot<URLSearchParams> { self.search_params .or_init(|| URLSearchParams::new(&self.global(), Some(self))) } // https://url.spec.whatwg.org/#dom-url-href fn Stringifier(&self) -> DOMString { DOMString::from(self.Href().0) } // https://url.spec.whatwg.org/#dom-url-username fn Username(&self) -> USVString { UrlHelper::Username(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-username fn SetUsername(&self, value: USVString) { UrlHelper::SetUsername(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-tojson fn ToJSON(&self) -> USVString { self.Href() } }
{ match ServoUrl::parse(&base.0) { Ok(base) => Some(base),
random_line_split
url.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::URLBinding::{self, URLMethods}; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{DomRoot, MutNullableDom}; use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::blob::Blob; use crate::dom::globalscope::GlobalScope; use crate::dom::urlhelper::UrlHelper; use crate::dom::urlsearchparams::URLSearchParams; use dom_struct::dom_struct; use net_traits::blob_url_store::{get_blob_origin, parse_blob_url}; use net_traits::filemanager_thread::FileManagerThreadMsg; use net_traits::{CoreResourceMsg, IpcSend}; use profile_traits::ipc; use servo_url::ServoUrl; use std::default::Default; use uuid::Uuid; // https://url.spec.whatwg.org/#url #[dom_struct] pub struct URL { reflector_: Reflector, // https://url.spec.whatwg.org/#concept-url-url url: DomRefCell<ServoUrl>, // https://url.spec.whatwg.org/#dom-url-searchparams search_params: MutNullableDom<URLSearchParams>, } impl URL { fn new_inherited(url: ServoUrl) -> URL { URL { reflector_: Reflector::new(), url: DomRefCell::new(url), search_params: Default::default(), } } pub fn new(global: &GlobalScope, url: ServoUrl) -> DomRoot<URL> { reflect_dom_object(Box::new(URL::new_inherited(url)), global, URLBinding::Wrap) } pub fn query_pairs(&self) -> Vec<(String, String)> { self.url .borrow() .as_url() .query_pairs() .into_owned() .collect() } pub fn set_query_pairs(&self, pairs: &[(String, String)]) { let mut url = self.url.borrow_mut(); if pairs.is_empty() { url.as_mut_url().set_query(None); } else { url.as_mut_url() .query_pairs_mut() .clear() .extend_pairs(pairs); } } } impl URL { // https://url.spec.whatwg.org/#constructors pub fn Constructor( global: &GlobalScope, url: USVString, base: Option<USVString>, ) -> Fallible<DomRoot<URL>> { let parsed_base = match base { None => { // Step 1. None }, Some(base) => // Step 2.1. { match ServoUrl::parse(&base.0) { Ok(base) => Some(base), Err(error) => { // Step 2.2. return Err(Error::Type(format!("could not parse base: {}", error))); }, } } }; // Step 3. let parsed_url = match ServoUrl::parse_with_base(parsed_base.as_ref(), &url.0) { Ok(url) => url, Err(error) => { // Step 4. return Err(Error::Type(format!("could not parse URL: {}", error))); }, }; // Step 5: Skip (see step 8 below). // Steps 6-7. let result = URL::new(global, parsed_url); // Step 8: Instead of construcing a new `URLSearchParams` object here, construct it // on-demand inside `URL::SearchParams`. // Step 9. Ok(result) } // https://w3c.github.io/FileAPI/#dfn-createObjectURL pub fn CreateObjectURL(global: &GlobalScope, blob: &Blob) -> DOMString { // XXX: Second field is an unicode-serialized Origin, it is a temporary workaround // and should not be trusted. See issue https://github.com/servo/servo/issues/11722 let origin = get_blob_origin(&global.get_url()); let id = blob.get_blob_url_id(); DOMString::from(URL::unicode_serialization_blob_url(&origin, &id)) } // https://w3c.github.io/FileAPI/#dfn-revokeObjectURL pub fn RevokeObjectURL(global: &GlobalScope, url: DOMString) { // If the value provided for the url argument is not a Blob URL OR // if the value provided for the url argument does not have an entry in the Blob URL Store, // this method call does nothing. User agents may display a message on the error console. let origin = get_blob_origin(&global.get_url()); if let Ok(url) = ServoUrl::parse(&url) { if let Ok((id, _)) = parse_blob_url(&url) { let resource_threads = global.resource_threads(); let (tx, rx) = ipc::channel(global.time_profiler_chan().clone()).unwrap(); let msg = FileManagerThreadMsg::RevokeBlobURL(id, origin, tx); let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)); let _ = rx.recv().unwrap(); } } } // https://w3c.github.io/FileAPI/#unicodeSerializationOfBlobURL fn unicode_serialization_blob_url(origin: &str, id: &Uuid) -> String { // Step 1, 2 let mut result = "blob:".to_string(); // Step 3 result.push_str(origin); // Step 4 result.push('/'); // Step 5 result.push_str(&id.to_simple().to_string()); result } } impl URLMethods for URL { // https://url.spec.whatwg.org/#dom-url-hash fn Hash(&self) -> USVString { UrlHelper::Hash(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-hash fn SetHash(&self, value: USVString) { UrlHelper::SetHash(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-host fn Host(&self) -> USVString { UrlHelper::Host(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-host fn
(&self, value: USVString) { UrlHelper::SetHost(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-hostname fn Hostname(&self) -> USVString { UrlHelper::Hostname(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-hostname fn SetHostname(&self, value: USVString) { UrlHelper::SetHostname(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-href fn Href(&self) -> USVString { UrlHelper::Href(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-href fn SetHref(&self, value: USVString) -> ErrorResult { match ServoUrl::parse(&value.0) { Ok(url) => { *self.url.borrow_mut() = url; self.search_params.set(None); // To be re-initialized in the SearchParams getter. Ok(()) }, Err(error) => Err(Error::Type(format!("could not parse URL: {}", error))), } } // https://url.spec.whatwg.org/#dom-url-password fn Password(&self) -> USVString { UrlHelper::Password(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-password fn SetPassword(&self, value: USVString) { UrlHelper::SetPassword(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-pathname fn Pathname(&self) -> USVString { UrlHelper::Pathname(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-pathname fn SetPathname(&self, value: USVString) { UrlHelper::SetPathname(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-port fn Port(&self) -> USVString { UrlHelper::Port(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-port fn SetPort(&self, value: USVString) { UrlHelper::SetPort(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-protocol fn Protocol(&self) -> USVString { UrlHelper::Protocol(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-protocol fn SetProtocol(&self, value: USVString) { UrlHelper::SetProtocol(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-origin fn Origin(&self) -> USVString { UrlHelper::Origin(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-search fn Search(&self) -> USVString { UrlHelper::Search(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-search fn SetSearch(&self, value: USVString) { UrlHelper::SetSearch(&mut self.url.borrow_mut(), value); if let Some(search_params) = self.search_params.get() { search_params.set_list(self.query_pairs()); } } // https://url.spec.whatwg.org/#dom-url-searchparams fn SearchParams(&self) -> DomRoot<URLSearchParams> { self.search_params .or_init(|| URLSearchParams::new(&self.global(), Some(self))) } // https://url.spec.whatwg.org/#dom-url-href fn Stringifier(&self) -> DOMString { DOMString::from(self.Href().0) } // https://url.spec.whatwg.org/#dom-url-username fn Username(&self) -> USVString { UrlHelper::Username(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-username fn SetUsername(&self, value: USVString) { UrlHelper::SetUsername(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-tojson fn ToJSON(&self) -> USVString { self.Href() } }
SetHost
identifier_name
url.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::URLBinding::{self, URLMethods}; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{DomRoot, MutNullableDom}; use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::blob::Blob; use crate::dom::globalscope::GlobalScope; use crate::dom::urlhelper::UrlHelper; use crate::dom::urlsearchparams::URLSearchParams; use dom_struct::dom_struct; use net_traits::blob_url_store::{get_blob_origin, parse_blob_url}; use net_traits::filemanager_thread::FileManagerThreadMsg; use net_traits::{CoreResourceMsg, IpcSend}; use profile_traits::ipc; use servo_url::ServoUrl; use std::default::Default; use uuid::Uuid; // https://url.spec.whatwg.org/#url #[dom_struct] pub struct URL { reflector_: Reflector, // https://url.spec.whatwg.org/#concept-url-url url: DomRefCell<ServoUrl>, // https://url.spec.whatwg.org/#dom-url-searchparams search_params: MutNullableDom<URLSearchParams>, } impl URL { fn new_inherited(url: ServoUrl) -> URL
pub fn new(global: &GlobalScope, url: ServoUrl) -> DomRoot<URL> { reflect_dom_object(Box::new(URL::new_inherited(url)), global, URLBinding::Wrap) } pub fn query_pairs(&self) -> Vec<(String, String)> { self.url .borrow() .as_url() .query_pairs() .into_owned() .collect() } pub fn set_query_pairs(&self, pairs: &[(String, String)]) { let mut url = self.url.borrow_mut(); if pairs.is_empty() { url.as_mut_url().set_query(None); } else { url.as_mut_url() .query_pairs_mut() .clear() .extend_pairs(pairs); } } } impl URL { // https://url.spec.whatwg.org/#constructors pub fn Constructor( global: &GlobalScope, url: USVString, base: Option<USVString>, ) -> Fallible<DomRoot<URL>> { let parsed_base = match base { None => { // Step 1. None }, Some(base) => // Step 2.1. { match ServoUrl::parse(&base.0) { Ok(base) => Some(base), Err(error) => { // Step 2.2. return Err(Error::Type(format!("could not parse base: {}", error))); }, } } }; // Step 3. let parsed_url = match ServoUrl::parse_with_base(parsed_base.as_ref(), &url.0) { Ok(url) => url, Err(error) => { // Step 4. return Err(Error::Type(format!("could not parse URL: {}", error))); }, }; // Step 5: Skip (see step 8 below). // Steps 6-7. let result = URL::new(global, parsed_url); // Step 8: Instead of construcing a new `URLSearchParams` object here, construct it // on-demand inside `URL::SearchParams`. // Step 9. Ok(result) } // https://w3c.github.io/FileAPI/#dfn-createObjectURL pub fn CreateObjectURL(global: &GlobalScope, blob: &Blob) -> DOMString { // XXX: Second field is an unicode-serialized Origin, it is a temporary workaround // and should not be trusted. See issue https://github.com/servo/servo/issues/11722 let origin = get_blob_origin(&global.get_url()); let id = blob.get_blob_url_id(); DOMString::from(URL::unicode_serialization_blob_url(&origin, &id)) } // https://w3c.github.io/FileAPI/#dfn-revokeObjectURL pub fn RevokeObjectURL(global: &GlobalScope, url: DOMString) { // If the value provided for the url argument is not a Blob URL OR // if the value provided for the url argument does not have an entry in the Blob URL Store, // this method call does nothing. User agents may display a message on the error console. let origin = get_blob_origin(&global.get_url()); if let Ok(url) = ServoUrl::parse(&url) { if let Ok((id, _)) = parse_blob_url(&url) { let resource_threads = global.resource_threads(); let (tx, rx) = ipc::channel(global.time_profiler_chan().clone()).unwrap(); let msg = FileManagerThreadMsg::RevokeBlobURL(id, origin, tx); let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)); let _ = rx.recv().unwrap(); } } } // https://w3c.github.io/FileAPI/#unicodeSerializationOfBlobURL fn unicode_serialization_blob_url(origin: &str, id: &Uuid) -> String { // Step 1, 2 let mut result = "blob:".to_string(); // Step 3 result.push_str(origin); // Step 4 result.push('/'); // Step 5 result.push_str(&id.to_simple().to_string()); result } } impl URLMethods for URL { // https://url.spec.whatwg.org/#dom-url-hash fn Hash(&self) -> USVString { UrlHelper::Hash(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-hash fn SetHash(&self, value: USVString) { UrlHelper::SetHash(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-host fn Host(&self) -> USVString { UrlHelper::Host(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-host fn SetHost(&self, value: USVString) { UrlHelper::SetHost(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-hostname fn Hostname(&self) -> USVString { UrlHelper::Hostname(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-hostname fn SetHostname(&self, value: USVString) { UrlHelper::SetHostname(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-href fn Href(&self) -> USVString { UrlHelper::Href(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-href fn SetHref(&self, value: USVString) -> ErrorResult { match ServoUrl::parse(&value.0) { Ok(url) => { *self.url.borrow_mut() = url; self.search_params.set(None); // To be re-initialized in the SearchParams getter. Ok(()) }, Err(error) => Err(Error::Type(format!("could not parse URL: {}", error))), } } // https://url.spec.whatwg.org/#dom-url-password fn Password(&self) -> USVString { UrlHelper::Password(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-password fn SetPassword(&self, value: USVString) { UrlHelper::SetPassword(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-pathname fn Pathname(&self) -> USVString { UrlHelper::Pathname(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-pathname fn SetPathname(&self, value: USVString) { UrlHelper::SetPathname(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-port fn Port(&self) -> USVString { UrlHelper::Port(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-port fn SetPort(&self, value: USVString) { UrlHelper::SetPort(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-protocol fn Protocol(&self) -> USVString { UrlHelper::Protocol(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-protocol fn SetProtocol(&self, value: USVString) { UrlHelper::SetProtocol(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-origin fn Origin(&self) -> USVString { UrlHelper::Origin(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-search fn Search(&self) -> USVString { UrlHelper::Search(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-search fn SetSearch(&self, value: USVString) { UrlHelper::SetSearch(&mut self.url.borrow_mut(), value); if let Some(search_params) = self.search_params.get() { search_params.set_list(self.query_pairs()); } } // https://url.spec.whatwg.org/#dom-url-searchparams fn SearchParams(&self) -> DomRoot<URLSearchParams> { self.search_params .or_init(|| URLSearchParams::new(&self.global(), Some(self))) } // https://url.spec.whatwg.org/#dom-url-href fn Stringifier(&self) -> DOMString { DOMString::from(self.Href().0) } // https://url.spec.whatwg.org/#dom-url-username fn Username(&self) -> USVString { UrlHelper::Username(&self.url.borrow()) } // https://url.spec.whatwg.org/#dom-url-username fn SetUsername(&self, value: USVString) { UrlHelper::SetUsername(&mut self.url.borrow_mut(), value); } // https://url.spec.whatwg.org/#dom-url-tojson fn ToJSON(&self) -> USVString { self.Href() } }
{ URL { reflector_: Reflector::new(), url: DomRefCell::new(url), search_params: Default::default(), } }
identifier_body
mod.rs
//! Generators for file formats that can be derived from the intercom //! libraries. use std::collections::HashMap; use intercom::type_system::TypeSystemName; use intercom::typelib::{Interface, TypeInfo, TypeLib}; /// A common error type for all the generators. #[derive(Fail, Debug)] pub enum GeneratorError { #[fail(display = "IoError: {}", _0)] IoError(#[cause] ::std::io::Error), #[fail(display = "Invalid type library: {}", _0)] LibraryError(String), } impl From<::std::io::Error> for GeneratorError { fn from(e: ::std::io::Error) -> GeneratorError { GeneratorError::IoError(e) } } impl From<String> for GeneratorError { fn from(s: String) -> GeneratorError { GeneratorError::LibraryError(s) } } pub struct ModelOptions { pub type_systems: Vec<TypeSystemOptions>, } pub struct TypeSystemOptions { pub ts: TypeSystemName, pub use_full_name: bool, } pub struct LibraryContext<'a> { pub itfs_by_ref: HashMap<String, &'a Interface>, pub itfs_by_name: HashMap<String, &'a Interface>, } impl<'a> LibraryContext<'a> { fn try_from(lib: &'a TypeLib) -> Result<LibraryContext<'a>, GeneratorError> { let itfs_by_name: HashMap<String, &Interface> = lib .types .iter() .filter_map(|t| match t { TypeInfo::Interface(itf) => Some(itf), _ => None, }) .map(|itf| (itf.as_ref().name.to_string(), &**(itf.as_ref()))) .collect(); let itfs_by_ref: HashMap<String, &Interface> = lib .types .iter() .filter_map(|t| match t { TypeInfo::Class(cls) => Some(cls), _ => None, }) .flat_map(|cls| &cls.as_ref().interfaces) .map(|itf_ref| { ( itf_ref.name.to_string(), itfs_by_name[itf_ref.name.as_ref()], ) }) .collect(); Ok(LibraryContext { itfs_by_name, itfs_by_ref, }) } } /// Convert the Rust identifier from `snake_case` to `PascalCase` pub fn pascal_case<T: AsRef<str>>(input: T) -> String { let input = input.as_ref(); // Allocate the output string. We'll never increase the amount of // characters so we can reserve string buffer using the input string length. let mut output = String::new(); output.reserve(input.len()); // Process each character from the input. let mut capitalize = true; for c in input.chars() { // Check the capitalization requirement. if c == '_' { // Skip '_' but capitalize the following character. capitalize = true; } else if capitalize { // Capitalize. Add the uppercase characters. for c_up in c.to_uppercase() { output.push(c_up) } // No need to capitalize any more. capitalize = false; } else { // No need to capitalize. Just add the character as is. output.push(c); } } output }
pub mod idl;
pub mod cpp;
random_line_split
mod.rs
//! Generators for file formats that can be derived from the intercom //! libraries. use std::collections::HashMap; use intercom::type_system::TypeSystemName; use intercom::typelib::{Interface, TypeInfo, TypeLib}; /// A common error type for all the generators. #[derive(Fail, Debug)] pub enum GeneratorError { #[fail(display = "IoError: {}", _0)] IoError(#[cause] ::std::io::Error), #[fail(display = "Invalid type library: {}", _0)] LibraryError(String), } impl From<::std::io::Error> for GeneratorError { fn from(e: ::std::io::Error) -> GeneratorError { GeneratorError::IoError(e) } } impl From<String> for GeneratorError { fn from(s: String) -> GeneratorError { GeneratorError::LibraryError(s) } } pub struct ModelOptions { pub type_systems: Vec<TypeSystemOptions>, } pub struct TypeSystemOptions { pub ts: TypeSystemName, pub use_full_name: bool, } pub struct
<'a> { pub itfs_by_ref: HashMap<String, &'a Interface>, pub itfs_by_name: HashMap<String, &'a Interface>, } impl<'a> LibraryContext<'a> { fn try_from(lib: &'a TypeLib) -> Result<LibraryContext<'a>, GeneratorError> { let itfs_by_name: HashMap<String, &Interface> = lib .types .iter() .filter_map(|t| match t { TypeInfo::Interface(itf) => Some(itf), _ => None, }) .map(|itf| (itf.as_ref().name.to_string(), &**(itf.as_ref()))) .collect(); let itfs_by_ref: HashMap<String, &Interface> = lib .types .iter() .filter_map(|t| match t { TypeInfo::Class(cls) => Some(cls), _ => None, }) .flat_map(|cls| &cls.as_ref().interfaces) .map(|itf_ref| { ( itf_ref.name.to_string(), itfs_by_name[itf_ref.name.as_ref()], ) }) .collect(); Ok(LibraryContext { itfs_by_name, itfs_by_ref, }) } } /// Convert the Rust identifier from `snake_case` to `PascalCase` pub fn pascal_case<T: AsRef<str>>(input: T) -> String { let input = input.as_ref(); // Allocate the output string. We'll never increase the amount of // characters so we can reserve string buffer using the input string length. let mut output = String::new(); output.reserve(input.len()); // Process each character from the input. let mut capitalize = true; for c in input.chars() { // Check the capitalization requirement. if c == '_' { // Skip '_' but capitalize the following character. capitalize = true; } else if capitalize { // Capitalize. Add the uppercase characters. for c_up in c.to_uppercase() { output.push(c_up) } // No need to capitalize any more. capitalize = false; } else { // No need to capitalize. Just add the character as is. output.push(c); } } output } pub mod cpp; pub mod idl;
LibraryContext
identifier_name
floatf.rs
//! formatter for %f %F common-notation floating-point subs use super::super::format_field::FormatField; use super::super::formatter::{InPrefix, FormatPrimitive, Formatter}; use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common}; pub struct Floatf { as_num: f64, } impl Floatf { pub fn new() -> Floatf { Floatf { as_num: 0.0 } } } impl Formatter for Floatf { fn get_primitive(&self, field: &FormatField, inprefix: &InPrefix, str_in: &str) -> Option<FormatPrimitive> { let second_field = field.second_field.unwrap_or(6) + 1; let analysis = FloatAnalysis::analyze(&str_in, inprefix, None, Some(second_field as usize), false); let f = get_primitive_dec(inprefix, &str_in[inprefix.offset..], &analysis, second_field as usize, None); Some(f) } fn
(&self, prim: &FormatPrimitive, field: FormatField) -> String { primitive_to_str_common(prim, &field) } }
primitive_to_str
identifier_name
floatf.rs
//! formatter for %f %F common-notation floating-point subs use super::super::format_field::FormatField; use super::super::formatter::{InPrefix, FormatPrimitive, Formatter}; use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common}; pub struct Floatf { as_num: f64, } impl Floatf { pub fn new() -> Floatf { Floatf { as_num: 0.0 } } } impl Formatter for Floatf { fn get_primitive(&self, field: &FormatField, inprefix: &InPrefix, str_in: &str) -> Option<FormatPrimitive> { let second_field = field.second_field.unwrap_or(6) + 1; let analysis = FloatAnalysis::analyze(&str_in, inprefix, None, Some(second_field as usize), false); let f = get_primitive_dec(inprefix, &str_in[inprefix.offset..], &analysis, second_field as usize, None); Some(f) } fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String
}
{ primitive_to_str_common(prim, &field) }
identifier_body
floatf.rs
//! formatter for %f %F common-notation floating-point subs use super::super::format_field::FormatField; use super::super::formatter::{InPrefix, FormatPrimitive, Formatter}; use super::float_common::{FloatAnalysis, get_primitive_dec, primitive_to_str_common}; pub struct Floatf { as_num: f64, } impl Floatf { pub fn new() -> Floatf { Floatf { as_num: 0.0 } } } impl Formatter for Floatf { fn get_primitive(&self, field: &FormatField, inprefix: &InPrefix, str_in: &str) -> Option<FormatPrimitive> { let second_field = field.second_field.unwrap_or(6) + 1; let analysis = FloatAnalysis::analyze(&str_in,
&str_in[inprefix.offset..], &analysis, second_field as usize, None); Some(f) } fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String { primitive_to_str_common(prim, &field) } }
inprefix, None, Some(second_field as usize), false); let f = get_primitive_dec(inprefix,
random_line_split
ihex_writer.rs
// // Copyright 2016 The c8s Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>. // All files in the project carrying such notice may not be copied, modified, or // distributed except according to those terms. // use std::cell::RefCell; use ihex::record::Record; use ihex::writer; use assembler::data_range; use assembler::data_range::DataRange; // MARK: - Public API /** Converts the provided data ranges into a single Intel HEX record. These data ranges cannot overlap and still yield a valid ihex record. It is the responsibility of the caller to ensure this does not happen. @param ranges The data ranges to convert to ihex format. @return The complete ihex record (including EOF) of the given data ranges. */ pub fn ihex_representation_of_data_ranges<'a>(ranges: &'a [DataRange]) -> String { assert!(data_range::find_overlapping_ranges(ranges).len() == 0); // All records are collected into a list. let mut records = Vec::<Record>::new(); for range in ranges.iter() { // The range will be sub-divded into chunks of up to 16 bytes, so sub-address must be tracked. let record_address = RefCell::new(u16::from(range.address_range().start)); // Sub-divide the range into 16-byte Record::Data objects. records.append( &mut range // Inspect the data in the range. .data() // As a u8 slice. .as_slice() // In groups of 16 bytes. .chunks(16) // Create a tuple of (Length, Record). .map(|chunk| { (chunk.len() as u16, Record::Data { offset: *record_address.borrow(), value: Vec::from(chunk) }) }) // Increment the address counter by the number of bytes incorporated into the record. .inspect(|&(length, _)| { *record_address.borrow_mut() += length; }) // Discard the length from the tuple. .map(|(_, record)| record) // Collect the records into a Vec<Record>. .collect::<Vec<_>>() ); } // All ihex files end in an EOF marker. records.push(Record::EndOfFile); // Obtain the formatted representation of each record and join with newlines for display. writer::create_object_file_representation(records.as_slice()).unwrap() + &"\n" } // MARK: - Tests #[cfg(test)] mod tests { use twelve_bit::u12::*; use assembler::data_range::DataRange; use super::ihex_representation_of_data_ranges; #[test] fn test_ihex_representation_of_data_ranges_no_ranges() { // An empty set of data ranges yields just an EOF marker. assert_eq!(ihex_representation_of_data_ranges(&[]), String::from(":00000001FF\n")); } #[test] fn test_ihex_representation_of_data_ranges_one_range() { // Build an average-case ihex record. let mut data_range = DataRange::new(u12![0x100]); data_range.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19,0x01]); data_range.append(&vec![0x21,0x46,0x01,0x7E,0x17,0xC2,0x00,0x01,0xFF,0x5F,0x16,0x00,0x21,0x48,0x01,0x19]); data_range.append(&vec![0x19,0x4E,0x79,0x23,0x46,0x23,0x96,0x57,0x78,0x23,0x9E,0xDA,0x3F,0x01,0xB2,0xCA]); data_range.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,0x2B,0x73,0x21,0x46,0x01,0x34,0x21]); // Validate the average case yielded the anticipated result. let ihex_rep_average = ihex_representation_of_data_ranges(&[data_range]); let expected_ihex_rep_average = String::new() + &":10010000214601360121470136007EFE09D2190140\n" + &":100110002146017E17C20001FF5F16002148011928\n" + &":10012000194E79234623965778239EDA3F01B2CAA7\n" + &":100130003F0156702B5E712B722B732146013421C7\n" + &":00000001FF\n"; assert_eq!(ihex_rep_average, expected_ihex_rep_average); } #[test] fn test_ihex_representation_of_data_ranges_adjacent_ranges() { // Build a pair of adjacent data ranges. let mut range_a = DataRange::new(u12![0x100]); range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19,0x01]); let mut range_b = DataRange::new(u12![0x110]); range_b.append(&vec![0x21,0x46,0x01,0x7E,0x17,0xC2,0x00,0x01,0xFF,0x5F,0x16,0x00,0x21,0x48,0x01,0x19]); // Validate the average case yielded the anticipated result. let ihex_rep_adjacent = ihex_representation_of_data_ranges(&[range_a, range_b]); let expected_ihex_rep_adjacent = String::new() + &":10010000214601360121470136007EFE09D2190140\n" + &":100110002146017E17C20001FF5F16002148011928\n" + &":00000001FF\n"; assert_eq!(ihex_rep_adjacent, expected_ihex_rep_adjacent); } #[test] fn test_ihex_representation_of_data_ranges_disjoint_ranges() { // Build an disjoint pair of data ranges. let mut range_a = DataRange::new(u12![0x100]); range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19,0x01]); let mut range_b = DataRange::new(u12![0x130]); range_b.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,0x2B,0x73,0x21,0x46,0x01,0x34,0x21]); // Validate the average case yielded the anticipated result. let ihex_rep_disjoint = ihex_representation_of_data_ranges(&[range_a, range_b]); let expected_ihex_rep_disjoint = String::new() + &":10010000214601360121470136007EFE09D2190140\n" + &":100130003F0156702B5E712B722B732146013421C7\n" + &":00000001FF\n"; assert_eq!(ihex_rep_disjoint, expected_ihex_rep_disjoint); } #[test] fn test_ihex_representation_of_data_ranges_uneven_ranges() { // Build an uneven set of data ranges. let mut range_a = DataRange::new(u12![0x100]); range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19]); let mut range_b = DataRange::new(u12![0x130]);
// Validate the average case yielded the anticipated result. let ihex_rep = ihex_representation_of_data_ranges(&[range_a, range_b, range_c]); let expected_ihex_rep = String::new() + &":0F010000214601360121470136007EFE09D21942\n" + &":100130003F0156702B5E712B722B732146013421C7\n" + &":01014000229C\n" + &":010200003FBE\n" + &":00000001FF\n"; assert_eq!(ihex_rep, expected_ihex_rep); } #[test] #[should_panic] fn test_ihex_representation_of_data_ranges_panics_when_overlapping() { // Build an overlapping pair of ranges. let mut range_a = DataRange::new(u12![0x100]); range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19,0x01]); let mut range_b = DataRange::new(u12![0x101]); range_b.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,0x2B,0x73,0x21,0x46,0x01,0x34,0x21]); ihex_representation_of_data_ranges(&[range_a, range_b]); } }
range_b.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,0x2B,0x73,0x21,0x46,0x01,0x34,0x21,0x22]); let mut range_c = DataRange::new(u12![0x200]); range_c.append(&vec![0x3F]);
random_line_split
ihex_writer.rs
// // Copyright 2016 The c8s Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>. // All files in the project carrying such notice may not be copied, modified, or // distributed except according to those terms. // use std::cell::RefCell; use ihex::record::Record; use ihex::writer; use assembler::data_range; use assembler::data_range::DataRange; // MARK: - Public API /** Converts the provided data ranges into a single Intel HEX record. These data ranges cannot overlap and still yield a valid ihex record. It is the responsibility of the caller to ensure this does not happen. @param ranges The data ranges to convert to ihex format. @return The complete ihex record (including EOF) of the given data ranges. */ pub fn ihex_representation_of_data_ranges<'a>(ranges: &'a [DataRange]) -> String { assert!(data_range::find_overlapping_ranges(ranges).len() == 0); // All records are collected into a list. let mut records = Vec::<Record>::new(); for range in ranges.iter() { // The range will be sub-divded into chunks of up to 16 bytes, so sub-address must be tracked. let record_address = RefCell::new(u16::from(range.address_range().start)); // Sub-divide the range into 16-byte Record::Data objects. records.append( &mut range // Inspect the data in the range. .data() // As a u8 slice. .as_slice() // In groups of 16 bytes. .chunks(16) // Create a tuple of (Length, Record). .map(|chunk| { (chunk.len() as u16, Record::Data { offset: *record_address.borrow(), value: Vec::from(chunk) }) }) // Increment the address counter by the number of bytes incorporated into the record. .inspect(|&(length, _)| { *record_address.borrow_mut() += length; }) // Discard the length from the tuple. .map(|(_, record)| record) // Collect the records into a Vec<Record>. .collect::<Vec<_>>() ); } // All ihex files end in an EOF marker. records.push(Record::EndOfFile); // Obtain the formatted representation of each record and join with newlines for display. writer::create_object_file_representation(records.as_slice()).unwrap() + &"\n" } // MARK: - Tests #[cfg(test)] mod tests { use twelve_bit::u12::*; use assembler::data_range::DataRange; use super::ihex_representation_of_data_ranges; #[test] fn test_ihex_representation_of_data_ranges_no_ranges() { // An empty set of data ranges yields just an EOF marker. assert_eq!(ihex_representation_of_data_ranges(&[]), String::from(":00000001FF\n")); } #[test] fn test_ihex_representation_of_data_ranges_one_range() { // Build an average-case ihex record. let mut data_range = DataRange::new(u12![0x100]); data_range.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19,0x01]); data_range.append(&vec![0x21,0x46,0x01,0x7E,0x17,0xC2,0x00,0x01,0xFF,0x5F,0x16,0x00,0x21,0x48,0x01,0x19]); data_range.append(&vec![0x19,0x4E,0x79,0x23,0x46,0x23,0x96,0x57,0x78,0x23,0x9E,0xDA,0x3F,0x01,0xB2,0xCA]); data_range.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,0x2B,0x73,0x21,0x46,0x01,0x34,0x21]); // Validate the average case yielded the anticipated result. let ihex_rep_average = ihex_representation_of_data_ranges(&[data_range]); let expected_ihex_rep_average = String::new() + &":10010000214601360121470136007EFE09D2190140\n" + &":100110002146017E17C20001FF5F16002148011928\n" + &":10012000194E79234623965778239EDA3F01B2CAA7\n" + &":100130003F0156702B5E712B722B732146013421C7\n" + &":00000001FF\n"; assert_eq!(ihex_rep_average, expected_ihex_rep_average); } #[test] fn test_ihex_representation_of_data_ranges_adjacent_ranges() { // Build a pair of adjacent data ranges. let mut range_a = DataRange::new(u12![0x100]); range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19,0x01]); let mut range_b = DataRange::new(u12![0x110]); range_b.append(&vec![0x21,0x46,0x01,0x7E,0x17,0xC2,0x00,0x01,0xFF,0x5F,0x16,0x00,0x21,0x48,0x01,0x19]); // Validate the average case yielded the anticipated result. let ihex_rep_adjacent = ihex_representation_of_data_ranges(&[range_a, range_b]); let expected_ihex_rep_adjacent = String::new() + &":10010000214601360121470136007EFE09D2190140\n" + &":100110002146017E17C20001FF5F16002148011928\n" + &":00000001FF\n"; assert_eq!(ihex_rep_adjacent, expected_ihex_rep_adjacent); } #[test] fn test_ihex_representation_of_data_ranges_disjoint_ranges() { // Build an disjoint pair of data ranges. let mut range_a = DataRange::new(u12![0x100]); range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19,0x01]); let mut range_b = DataRange::new(u12![0x130]); range_b.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,0x2B,0x73,0x21,0x46,0x01,0x34,0x21]); // Validate the average case yielded the anticipated result. let ihex_rep_disjoint = ihex_representation_of_data_ranges(&[range_a, range_b]); let expected_ihex_rep_disjoint = String::new() + &":10010000214601360121470136007EFE09D2190140\n" + &":100130003F0156702B5E712B722B732146013421C7\n" + &":00000001FF\n"; assert_eq!(ihex_rep_disjoint, expected_ihex_rep_disjoint); } #[test] fn test_ihex_representation_of_data_ranges_uneven_ranges()
#[test] #[should_panic] fn test_ihex_representation_of_data_ranges_panics_when_overlapping() { // Build an overlapping pair of ranges. let mut range_a = DataRange::new(u12![0x100]); range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19,0x01]); let mut range_b = DataRange::new(u12![0x101]); range_b.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,0x2B,0x73,0x21,0x46,0x01,0x34,0x21]); ihex_representation_of_data_ranges(&[range_a, range_b]); } }
{ // Build an uneven set of data ranges. let mut range_a = DataRange::new(u12![0x100]); range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19]); let mut range_b = DataRange::new(u12![0x130]); range_b.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,0x2B,0x73,0x21,0x46,0x01,0x34,0x21,0x22]); let mut range_c = DataRange::new(u12![0x200]); range_c.append(&vec![0x3F]); // Validate the average case yielded the anticipated result. let ihex_rep = ihex_representation_of_data_ranges(&[range_a, range_b, range_c]); let expected_ihex_rep = String::new() + &":0F010000214601360121470136007EFE09D21942\n" + &":100130003F0156702B5E712B722B732146013421C7\n" + &":01014000229C\n" + &":010200003FBE\n" + &":00000001FF\n"; assert_eq!(ihex_rep, expected_ihex_rep); }
identifier_body
ihex_writer.rs
// // Copyright 2016 The c8s Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>. // All files in the project carrying such notice may not be copied, modified, or // distributed except according to those terms. // use std::cell::RefCell; use ihex::record::Record; use ihex::writer; use assembler::data_range; use assembler::data_range::DataRange; // MARK: - Public API /** Converts the provided data ranges into a single Intel HEX record. These data ranges cannot overlap and still yield a valid ihex record. It is the responsibility of the caller to ensure this does not happen. @param ranges The data ranges to convert to ihex format. @return The complete ihex record (including EOF) of the given data ranges. */ pub fn
<'a>(ranges: &'a [DataRange]) -> String { assert!(data_range::find_overlapping_ranges(ranges).len() == 0); // All records are collected into a list. let mut records = Vec::<Record>::new(); for range in ranges.iter() { // The range will be sub-divded into chunks of up to 16 bytes, so sub-address must be tracked. let record_address = RefCell::new(u16::from(range.address_range().start)); // Sub-divide the range into 16-byte Record::Data objects. records.append( &mut range // Inspect the data in the range. .data() // As a u8 slice. .as_slice() // In groups of 16 bytes. .chunks(16) // Create a tuple of (Length, Record). .map(|chunk| { (chunk.len() as u16, Record::Data { offset: *record_address.borrow(), value: Vec::from(chunk) }) }) // Increment the address counter by the number of bytes incorporated into the record. .inspect(|&(length, _)| { *record_address.borrow_mut() += length; }) // Discard the length from the tuple. .map(|(_, record)| record) // Collect the records into a Vec<Record>. .collect::<Vec<_>>() ); } // All ihex files end in an EOF marker. records.push(Record::EndOfFile); // Obtain the formatted representation of each record and join with newlines for display. writer::create_object_file_representation(records.as_slice()).unwrap() + &"\n" } // MARK: - Tests #[cfg(test)] mod tests { use twelve_bit::u12::*; use assembler::data_range::DataRange; use super::ihex_representation_of_data_ranges; #[test] fn test_ihex_representation_of_data_ranges_no_ranges() { // An empty set of data ranges yields just an EOF marker. assert_eq!(ihex_representation_of_data_ranges(&[]), String::from(":00000001FF\n")); } #[test] fn test_ihex_representation_of_data_ranges_one_range() { // Build an average-case ihex record. let mut data_range = DataRange::new(u12![0x100]); data_range.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19,0x01]); data_range.append(&vec![0x21,0x46,0x01,0x7E,0x17,0xC2,0x00,0x01,0xFF,0x5F,0x16,0x00,0x21,0x48,0x01,0x19]); data_range.append(&vec![0x19,0x4E,0x79,0x23,0x46,0x23,0x96,0x57,0x78,0x23,0x9E,0xDA,0x3F,0x01,0xB2,0xCA]); data_range.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,0x2B,0x73,0x21,0x46,0x01,0x34,0x21]); // Validate the average case yielded the anticipated result. let ihex_rep_average = ihex_representation_of_data_ranges(&[data_range]); let expected_ihex_rep_average = String::new() + &":10010000214601360121470136007EFE09D2190140\n" + &":100110002146017E17C20001FF5F16002148011928\n" + &":10012000194E79234623965778239EDA3F01B2CAA7\n" + &":100130003F0156702B5E712B722B732146013421C7\n" + &":00000001FF\n"; assert_eq!(ihex_rep_average, expected_ihex_rep_average); } #[test] fn test_ihex_representation_of_data_ranges_adjacent_ranges() { // Build a pair of adjacent data ranges. let mut range_a = DataRange::new(u12![0x100]); range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19,0x01]); let mut range_b = DataRange::new(u12![0x110]); range_b.append(&vec![0x21,0x46,0x01,0x7E,0x17,0xC2,0x00,0x01,0xFF,0x5F,0x16,0x00,0x21,0x48,0x01,0x19]); // Validate the average case yielded the anticipated result. let ihex_rep_adjacent = ihex_representation_of_data_ranges(&[range_a, range_b]); let expected_ihex_rep_adjacent = String::new() + &":10010000214601360121470136007EFE09D2190140\n" + &":100110002146017E17C20001FF5F16002148011928\n" + &":00000001FF\n"; assert_eq!(ihex_rep_adjacent, expected_ihex_rep_adjacent); } #[test] fn test_ihex_representation_of_data_ranges_disjoint_ranges() { // Build an disjoint pair of data ranges. let mut range_a = DataRange::new(u12![0x100]); range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19,0x01]); let mut range_b = DataRange::new(u12![0x130]); range_b.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,0x2B,0x73,0x21,0x46,0x01,0x34,0x21]); // Validate the average case yielded the anticipated result. let ihex_rep_disjoint = ihex_representation_of_data_ranges(&[range_a, range_b]); let expected_ihex_rep_disjoint = String::new() + &":10010000214601360121470136007EFE09D2190140\n" + &":100130003F0156702B5E712B722B732146013421C7\n" + &":00000001FF\n"; assert_eq!(ihex_rep_disjoint, expected_ihex_rep_disjoint); } #[test] fn test_ihex_representation_of_data_ranges_uneven_ranges() { // Build an uneven set of data ranges. let mut range_a = DataRange::new(u12![0x100]); range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19]); let mut range_b = DataRange::new(u12![0x130]); range_b.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,0x2B,0x73,0x21,0x46,0x01,0x34,0x21,0x22]); let mut range_c = DataRange::new(u12![0x200]); range_c.append(&vec![0x3F]); // Validate the average case yielded the anticipated result. let ihex_rep = ihex_representation_of_data_ranges(&[range_a, range_b, range_c]); let expected_ihex_rep = String::new() + &":0F010000214601360121470136007EFE09D21942\n" + &":100130003F0156702B5E712B722B732146013421C7\n" + &":01014000229C\n" + &":010200003FBE\n" + &":00000001FF\n"; assert_eq!(ihex_rep, expected_ihex_rep); } #[test] #[should_panic] fn test_ihex_representation_of_data_ranges_panics_when_overlapping() { // Build an overlapping pair of ranges. let mut range_a = DataRange::new(u12![0x100]); range_a.append(&vec![0x21,0x46,0x01,0x36,0x01,0x21,0x47,0x01,0x36,0x00,0x7E,0xFE,0x09,0xD2,0x19,0x01]); let mut range_b = DataRange::new(u12![0x101]); range_b.append(&vec![0x3F,0x01,0x56,0x70,0x2B,0x5E,0x71,0x2B,0x72,0x2B,0x73,0x21,0x46,0x01,0x34,0x21]); ihex_representation_of_data_ranges(&[range_a, range_b]); } }
ihex_representation_of_data_ranges
identifier_name
pmovsxbd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*;
fn pmovsxbd_1() { run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 205], OperandSize::Dword) } fn pmovsxbd_2() { run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM4)), operand2: Some(IndirectDisplaced(EDI, 977278461, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 167, 253, 21, 64, 58], OperandSize::Dword) } fn pmovsxbd_3() { run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 246], OperandSize::Qword) } fn pmovsxbd_4() { run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM5)), operand2: Some(IndirectScaledIndexedDisplaced(RDI, RBX, Two, 1709813562, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 172, 95, 58, 175, 233, 101], OperandSize::Qword) }
use ::RegScale::*;
random_line_split
pmovsxbd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pmovsxbd_1() { run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 205], OperandSize::Dword) } fn pmovsxbd_2() { run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM4)), operand2: Some(IndirectDisplaced(EDI, 977278461, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 167, 253, 21, 64, 58], OperandSize::Dword) } fn
() { run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 246], OperandSize::Qword) } fn pmovsxbd_4() { run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM5)), operand2: Some(IndirectScaledIndexedDisplaced(RDI, RBX, Two, 1709813562, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 172, 95, 58, 175, 233, 101], OperandSize::Qword) }
pmovsxbd_3
identifier_name
pmovsxbd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pmovsxbd_1() { run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 205], OperandSize::Dword) } fn pmovsxbd_2() { run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM4)), operand2: Some(IndirectDisplaced(EDI, 977278461, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 167, 253, 21, 64, 58], OperandSize::Dword) } fn pmovsxbd_3() { run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM6)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 246], OperandSize::Qword) } fn pmovsxbd_4()
{ run_test(&Instruction { mnemonic: Mnemonic::PMOVSXBD, operand1: Some(Direct(XMM5)), operand2: Some(IndirectScaledIndexedDisplaced(RDI, RBX, Two, 1709813562, Some(OperandSize::Dword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 33, 172, 95, 58, 175, 233, 101], OperandSize::Qword) }
identifier_body
13.rs
use std::fmt; use std::fs::File; use std::io::prelude::*; use std::collections::HashMap; fn get_input() -> std::io::Result<String> { let mut file = File::open("13.txt")?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } type Point = (isize, isize); type Tracks = HashMap<Point, Vec<Point>>; #[derive(Clone)] struct Cart { position: Point, direction: Point, decision: usize } impl fmt::Debug for Cart { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", (self.position, match self.direction { (-1, 0) => '<', (1, 0) => '>', (0, -1) => '^', (0, 1) => 'v', _ =>'' })) } } impl Cart { fn new(position: Point, direction: Point) -> Self { Self { position, direction, decision: 0 } } fn move_cart(&mut self, neighbors: &[Point]) { let (x, y) = self.position; let (dx, dy) = self.direction; // Left, Straight, Right let targets = [(0, -1), (1, 0), (0, 1)].into_iter() .map(|(za, zb)| (x + dx * za - dy * zb, y + dx * zb + dy * za)) .filter(|target| neighbors.contains(target)) .collect::<Vec<_>>(); let (nx, ny) = match targets.len() { 1 => targets[0], 3 => { let target = targets[self.decision]; self.decision = (self.decision + 1) % 3; target }, _ => return }; self.position = (nx, ny); self.direction = (nx - x, ny - y); } } fn
(input: &str) -> (Tracks, Vec<Cart>) { input.lines() .enumerate() .flat_map(|(j, line)| { let chars: Vec<char> = line.chars().collect(); chars.iter() .cloned() .enumerate() .filter_map(|(i, c)| { let (x, y) = (i as isize, j as isize); let horizontal_chars = ['-', '+', '<', '>']; let neighbors = match (c, chars.get(i + 1)) { ('/', Some(nc)) if horizontal_chars.contains(nc) => Some(vec![(x + 1, y), (x, y + 1)]), ('/', _) => Some(vec![(x - 1, y), (x, y - 1)]), ('\\', Some(nc)) if horizontal_chars.contains(nc) => Some(vec![(x + 1, y), (x, y - 1)]), ('\\', _) => Some(vec![(x - 1, y), (x, y + 1)]), ('+', _) => Some(vec![(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]), ('-', _) | ('<', _) | ('>', _) => Some(vec![(x - 1, y), (x + 1, y)]), ('|', _) | ('^', _) | ('v', _) => Some(vec![(x, y - 1), (x, y + 1)]), _ => None }; let cart_direction = match c { '<' => Some((-1, 0)), '>' => Some((1, 0)), '^' => Some((0, -1)), 'v' => Some((0, 1)), _ => None }; neighbors .map(|n| ((x, y), n, cart_direction.map(|d| Cart::new((x, y), d)))) }) .collect::<Vec<_>>() }) .fold((Tracks::new(), Vec::new()), |(mut tracks, mut carts), (k, v, cart)| { tracks.insert(k, v); cart.map(|c| carts.push(c)); (tracks, carts) }) } fn tick(tracks: &Tracks, carts: &mut Vec<Cart>) -> Vec<Point> { let mut collisions = Vec::new(); let mut i = 0; carts.sort_unstable_by_key(|cart| (cart.position.1, cart.position.0)); while i < carts.len() { let new_position = { let cart = carts.get_mut(i).unwrap(); let neighbors = tracks.get(&cart.position).unwrap(); cart.move_cart(neighbors); cart.position }; if let Some(j) = carts.iter().enumerate().position(|(j, cart)| j!= i && cart.position == new_position) { carts.retain(|cart| cart.position!= new_position); collisions.push(new_position); if j < i { i -= 1; } } i += 1; } collisions } fn main() { let input = get_input().unwrap(); let (tracks, mut carts) = parse(&input); let original_carts = carts.clone(); loop { let collisions = tick(&tracks, &mut carts); if let Some((x, y)) = collisions.into_iter().next() { println!("Part 1: {},{}", x, y); break; } } let mut carts = original_carts; while carts.len() > 1 { tick(&tracks, &mut carts); } carts.into_iter().next() .map(|cart| println!("Part 2: {},{}", cart.position.0, cart.position.1)); }
parse
identifier_name
13.rs
use std::fmt; use std::fs::File; use std::io::prelude::*; use std::collections::HashMap; fn get_input() -> std::io::Result<String> { let mut file = File::open("13.txt")?; let mut contents = String::new(); file.read_to_string(&mut contents)?; Ok(contents) } type Point = (isize, isize); type Tracks = HashMap<Point, Vec<Point>>; #[derive(Clone)] struct Cart { position: Point, direction: Point, decision: usize } impl fmt::Debug for Cart { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", (self.position, match self.direction { (-1, 0) => '<', (1, 0) => '>', (0, -1) => '^', (0, 1) => 'v', _ =>'' })) } } impl Cart { fn new(position: Point, direction: Point) -> Self { Self { position, direction, decision: 0 } } fn move_cart(&mut self, neighbors: &[Point]) { let (x, y) = self.position; let (dx, dy) = self.direction; // Left, Straight, Right let targets = [(0, -1), (1, 0), (0, 1)].into_iter() .map(|(za, zb)| (x + dx * za - dy * zb, y + dx * zb + dy * za)) .filter(|target| neighbors.contains(target)) .collect::<Vec<_>>(); let (nx, ny) = match targets.len() { 1 => targets[0], 3 => { let target = targets[self.decision]; self.decision = (self.decision + 1) % 3; target }, _ => return }; self.position = (nx, ny); self.direction = (nx - x, ny - y); } } fn parse(input: &str) -> (Tracks, Vec<Cart>) { input.lines() .enumerate() .flat_map(|(j, line)| { let chars: Vec<char> = line.chars().collect(); chars.iter() .cloned() .enumerate() .filter_map(|(i, c)| { let (x, y) = (i as isize, j as isize); let horizontal_chars = ['-', '+', '<', '>']; let neighbors = match (c, chars.get(i + 1)) { ('/', Some(nc)) if horizontal_chars.contains(nc) => Some(vec![(x + 1, y), (x, y + 1)]), ('/', _) => Some(vec![(x - 1, y), (x, y - 1)]), ('\\', Some(nc)) if horizontal_chars.contains(nc) => Some(vec![(x + 1, y), (x, y - 1)]), ('\\', _) => Some(vec![(x - 1, y), (x, y + 1)]), ('+', _) => Some(vec![(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]), ('-', _) | ('<', _) | ('>', _) => Some(vec![(x - 1, y), (x + 1, y)]), ('|', _) | ('^', _) | ('v', _) => Some(vec![(x, y - 1), (x, y + 1)]), _ => None
'>' => Some((1, 0)), '^' => Some((0, -1)), 'v' => Some((0, 1)), _ => None }; neighbors .map(|n| ((x, y), n, cart_direction.map(|d| Cart::new((x, y), d)))) }) .collect::<Vec<_>>() }) .fold((Tracks::new(), Vec::new()), |(mut tracks, mut carts), (k, v, cart)| { tracks.insert(k, v); cart.map(|c| carts.push(c)); (tracks, carts) }) } fn tick(tracks: &Tracks, carts: &mut Vec<Cart>) -> Vec<Point> { let mut collisions = Vec::new(); let mut i = 0; carts.sort_unstable_by_key(|cart| (cart.position.1, cart.position.0)); while i < carts.len() { let new_position = { let cart = carts.get_mut(i).unwrap(); let neighbors = tracks.get(&cart.position).unwrap(); cart.move_cart(neighbors); cart.position }; if let Some(j) = carts.iter().enumerate().position(|(j, cart)| j!= i && cart.position == new_position) { carts.retain(|cart| cart.position!= new_position); collisions.push(new_position); if j < i { i -= 1; } } i += 1; } collisions } fn main() { let input = get_input().unwrap(); let (tracks, mut carts) = parse(&input); let original_carts = carts.clone(); loop { let collisions = tick(&tracks, &mut carts); if let Some((x, y)) = collisions.into_iter().next() { println!("Part 1: {},{}", x, y); break; } } let mut carts = original_carts; while carts.len() > 1 { tick(&tracks, &mut carts); } carts.into_iter().next() .map(|cart| println!("Part 2: {},{}", cart.position.0, cart.position.1)); }
}; let cart_direction = match c { '<' => Some((-1, 0)),
random_line_split
lib.rs
Rot180 {Normal, Rotated} #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ItemTypesetting(pub DirBehavior, pub Rot180); impl ItemTypesetting { fn effective_direction(&self) -> Direction { match self.1 { Rot180::Normal => self.0. 0, Rot180::Rotated => self.0. 0.reverse() } } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MainAxis {Ltr, Rtl, Ttb, Btt} macro_rules! try_opt { ($e:expr) => (match $e {Some(x)=>x, None=>return None}) } /// contains glyphs and typesetting information #[derive(PartialEq, Clone, Copy)] pub struct FontCollection<'a>{ pub tables: TableDirectory<'a>, pub gsub: Option<GSub<'a>> } #[derive(PartialEq, Clone, Copy)] pub struct TableDirectory<'a>{ data: &'a[u8], num_tables: u16 } impl<'a> TableDirectory<'a> { fn new(data: &[u8]) -> Result<TableDirectory, CorruptFont> { if data.len() < 12 {return Err(CorruptFont(data, TableTooShort))} let version = read_u32(data); if version!= Some(0x10000) && version!= Some(0x4f54544f) {return Err(CorruptFont(data, ReservedFeature))} let num_tables = read_u16(&data[4..]).unwrap(); if data.len() < num_tables as usize*16 + 12 { Err(CorruptFont(data, TableTooShort)) } else { Ok(TableDirectory { data: data, num_tables: num_tables }) } } fn find(&self, start: u16, label: u32) -> Option<(u16, &'a[u8])> { for pos_ in start..self.num_tables { let pos = pos_ as usize; let candidate = try_opt!(read_u32(&self.data[12+16*pos..])); if candidate == label { let start = read_u32(&self.data[12+16*pos+8..]).unwrap() as usize; return Some((pos as u16, &self.data[start..read_u32(&self.data[12+16*pos+12..]).unwrap() as usize+start])); } else if candidate > label { return None } } None } } /// contains character mapping #[derive(PartialEq, Clone, Copy)] pub struct Font<'a>{ pub cmap: CMap<'a>, glyph_src: &'a FontCollection<'a> } pub fn read_u32(data: &[u8]) -> Option<u32> { if data.len() > 3 { Some((data[0] as u32) << 24 | (data[1] as u32) << 16 | (data[2] as u32) << 8 | data[3] as u32) } else { None } } pub fn read_u16(data: &[u8]) -> Option<u16> { if data.len() > 1 { Some((data[0] as u16) << 8 | data[1] as u16) } else { None } } pub fn fourcc(tag: u32) -> String { let mut s = String::with_capacity(4); s.push((tag >> 24) as u8 as char); s.push((tag >> 16) as u8 as char); s.push((tag >> 8) as u8 as char); s.push(tag as u8 as char); s } fn find_best_cmap(cmap: &[u8]) -> Option<&[u8]> { let mut bmp = None; for encoding in 0..read_u16(&cmap[2..]).unwrap() as usize { let enc_header = &(&cmap[4+8*encoding..])[..8]; let (plat, enc) = (read_u16(enc_header).unwrap(), read_u16(&enc_header[2..]).unwrap()); match (plat, enc) { (0, 3) | (3, 1) => {bmp=Some(&cmap[try_opt!(read_u32(&enc_header[4..])) as usize..]);}, (0, 4) | (3, 10) => return Some(&cmap[try_opt!(read_u32(&enc_header[4..])) as usize..]), _ => {} // unknown encoding } } bmp } #[derive(PartialEq, Clone, Copy)] pub struct CMap<'otf>(Encoding<'otf>); impl<'otf> CMap<'otf> {pub fn lookup(&self, c: char) -> Option<GlyphIndex> {self.0.lookup(c)}} #[derive(PartialEq, Clone, Copy)] enum Encoding<'a> { Fmt4(CmapFmt4<'a>) } impl<'a> Encoding<'a> { pub fn lookup(&self, c: char) -> Option<GlyphIndex> { match *self { Encoding::Fmt4 (CmapFmt4 {end, start, delta, crazy_indexing_part: range_offset}) => { if c as u32 > 0xffff {return Some(GlyphIndex(0))} let mut range = 0..end.len()/2; while range.start!= range.end { let pivot = ((range.end - range.start) &!1) + range.start*2; let pivot_val = read_u16(&end[pivot..]).unwrap(); range = if pivot_val < c as u16 { pivot/2+1..range.end } else { range.start..pivot/2 }; } let seg_offset = range.start*2; let block_start = read_u16(&start[seg_offset..]).unwrap(); if block_start > c as u16 {return Some(GlyphIndex(0))} return Some(GlyphIndex((read_u16(&delta[seg_offset..]).unwrap()).wrapping_add({ let offset = read_u16(&range_offset[seg_offset..]).unwrap(); if offset == 0 { println!("delta: {} start: {}", read_u16(&delta[seg_offset..]).unwrap(), block_start); c as u16 } else { // this path is untested because the spec is really weird and I've never seen it used let res = read_u16(&range_offset[seg_offset+(offset as usize &!1)+(c as usize - block_start as usize)..]).unwrap(); if res == 0 { return Some(GlyphIndex(0)) } else { res } } }))) } } } } #[derive(PartialEq, Clone, Copy)] struct CmapFmt4<'a> { end: &'a[u8], start: &'a[u8], delta: &'a[u8], crazy_indexing_part: &'a[u8] } fn load_enc_table(mut enc: &[u8]) -> Result<Encoding, CorruptFont> { if enc.len() < 4 {return Err(CorruptFont(enc, TableTooShort))} let format = read_u16(enc).unwrap(); match format { 4 => { let len = read_u16(&enc[2..]).unwrap() as usize; if len > enc.len() && len < 14 {return Err(CorruptFont(enc, TableTooShort))} enc = &enc[..len]; let segsX2 = read_u16(&enc[6..]).unwrap() as usize; if segsX2 % 2!= 0 {return Err(CorruptFont(enc, OddSegsX2))} if segsX2 < 2 || 4*segsX2 + 16 > len {return Err(CorruptFont(enc, CmapInvalidSegmentCount))} let end = &enc[14..14+segsX2]; if read_u16(&end[segsX2-2..]).unwrap()!= 0xffff {return Err(CorruptFont(enc, CmapMissingGuard))} Ok(Encoding::Fmt4(CmapFmt4{ end: end, start: &enc[16+segsX2..16+2*segsX2], delta: &enc[16+2*segsX2..16+3*segsX2], crazy_indexing_part: &enc[16+3*segsX2..] })) }, _ => Err(CorruptFont(enc, Unimplemented)) } } pub fn load_font_collection(data: &[u8]) -> Result<FontCollection, CorruptFont> { let tables = try!(TableDirectory::new(data)); println!("#glyphs: {:?}", tables.find(0, 0x6d617870).and_then(|x|read_u16(&x.1[4..]))); let gsub = if let Some(x) = tables.find(0, GSUB_TAG) { Some(try!(GSub::new(x.1))) } else {None}; Ok(FontCollection { gsub: gsub, tables: tables }) } static CMAP_TAG: u32 = 0x636d6170; static HHEA_TAG: u32 = 0x68686561; static GSUB_TAG: u32 = 0x47535542; pub fn load_font<'a>(collection: &'a FontCollection<'a>, font: &str) -> Result<Font<'a>, CorruptFont<'a>> { let (_pos, cmap) = try!(collection.tables.find(0, CMAP_TAG).ok_or(CorruptFont(collection.tables.data, NoCmap))); let best_enc = try!(find_best_cmap(cmap).ok_or(CorruptFont(cmap, NoCmap))); let enc = try!(load_enc_table(best_enc)); Ok(Font {cmap: CMap(enc), glyph_src: collection}) } #[derive(Debug, Clone, Copy, PartialEq)] pub struct GlyphIndex(u16); #[derive(Debug, Clone, Copy)] pub struct MappedGlyph<'text> { pub range: &'text str, pub glyph: GlyphIndex, pub dir: Direction } pub trait CharMapper { /// given the text of the cluster, the character index relative to cluster start and the position within that character, return the byte offset into the cluster, where the cursor is fn map_cursor(&self, text: &str, character: usize, pos: Fractional) -> usize; fn map_range(&self, range: Range<usize>) -> Vec<Range<usize>>; } pub trait Shaper { type CharMapper: CharMapper; /// segment the string into clusters, shape the clusters and look up the glyphs (with given callback) /// /// first result is the characters, second the pairs of (first character index of cluster, string offset of cluster start) fn shape<T, F: FnMut(char) -> Option<T>>(&self, text: &str, lookup: &mut F) -> Option<(Vec<T>, Self::CharMapper)>; } #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq)] pub struct Fractional(u32); static FRACTIONAL_CENTER: Fractional = Fractional(0x80000000); mod shaping; pub use shaping::*; trait GlyphMapper { fn new() -> Self; fn map_char_to_glyph(&self, char_idx: usize, pos: Fractional) -> Option<(usize, Fractional)>; fn map_glyph_to_char(&self, glyph_idx: usize, pos: Fractional) -> Option<(usize, Fractional)>; } trait MonotonicSubstitution { type GlyphMapper: GlyphMapper; /// performs the substitution. Returns the number of characters affected. fn substitute_mutate(&self, forward: &mut Vec<GlyphIndex>, backward: &mut Vec<GlyphIndex>, map_fwd: &mut Self::GlyphMapper, map_bwd: &mut Self::GlyphMapper) -> Option<usize>; fn substitute(&self, mut glyphs: Vec<GlyphIndex>) -> Option<(Vec<GlyphIndex>, Self::GlyphMapper)> { let (mut m1, mut m2) = (Self::GlyphMapper::new(), Self::GlyphMapper::new()); try_opt!(self.substitute_mutate(&mut glyphs, &mut Vec::new(), &mut m1, &mut m2)); Some((glyphs, m1)) } } #[derive(Clone, Copy, Debug)] enum FontCorruption { Unimplemented, ReservedFeature, TableTooShort, OffsetOutOfBounds, IncorrectDfltScript, CmapInvalidSegmentCount, OddSegsX2, CmapMissingGuard, NoCmap, UnknownTableVersion, InvalidRange, WrappingCoverageIndex } use FontCorruption::*; #[derive(Clone, Copy, Debug)] pub struct CorruptFont<'a>(&'a[u8], FontCorruption); impl<'a> Error for CorruptFont<'a> { fn description(&self) -> &str {match self.1 { Unimplemented => "The font uses a feature that is not implemented", ReservedFeature => "A reserved field differed from the default value", TableTooShort => "Unexpected end of table", OffsetOutOfBounds => "An Offset pointed outside of the respective table", IncorrectDfltScript => "'DFLT' script with missing DefaultLangSys or LangSysCount ≠ 0", CmapInvalidSegmentCount => "The segment count in the character mapping is invalid", OddSegsX2 => "The doubled segment count in the character mapping is not an even number", CmapMissingGuard => "The character mapping is missing a guard value", NoCmap => "No character mapping found", UnknownTableVersion => "The font uses a table version that is not recognised", InvalidRange => "Invalid index range (last < first) found in font", WrappingCoverageIndex => "Index could wrap in Coverage Range" }} } impl<'a> ::std::fmt::Display for CorruptFont<'a> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { write!(f, "{}", self.description()) } } mod search; use search::{AutoSearch, SearchStrategy}; pub trait Indexed:'static {} pub struct Index<T: Indexed>(pub u16, PhantomData<&'static T>); impl<T: Indexed> Index<T> {pub fn new(x: u16) -> Index<T> {Index(x, PhantomData)}} impl<T: Indexed> std::fmt::Debug for Index<T> {fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {self.0.fmt(fmt)}} pub struct LangSysTable<'a>(&'a[u8]); impl<'a> LangSysTable<'a> { pub fn new(data: &'a[u8]) -> Result<LangSysTable<'a>, CorruptFont<'a>> { if data.len() < 6 {return Err(CorruptFont(data, TableTooShort))} if read_u16(data).unwrap()!= 0 {return Err(CorruptFont(data, ReservedFeature))} let num_features = read_u16(&data[4..]).unwrap(); if data.len() - 6 < num_features as usize*2 {return Err(CorruptFont(data, TableTooShort))} Ok(LangSysTable(&data[2..num_features as usize*2 + 6])) } pub fn num_features(&self) -> u16 {(self.0.len() / 2 - 2) as u16} pub fn required_feature(&self) -> Option<Index<Feature>> { let res = read_u16(self.0).unwrap(); if res == 0xffff {None} else {Some(Index::new(res))} } pub fn get_feature(&self, idx: u16) -> Option<Index<Feature>> {read_u16(&self.0[4 + idx as usize*2..]).map(|x| Index::new(x))} pub fn features(&self) -> IndexList<'a, Feature> {IndexList(&self.0[4..], PhantomData)} } static DEFAULT_LANGSYS_TABLE: [u8; 4] = [255, 255, 0, 0]; impl<'a> Default for LangSysTable<'a> { fn default() -> LangSysTable<'a> {LangSysTable(&DEFAULT_LANGSYS_TABLE)} } #[derive(Clone, Copy, PartialEq, Eq)] pub struct LangSys; pub type ScriptTable<'a> = TagOffsetList<'a, LangSys>; impl<'a> TagListTable<'a> for LangSys { type Table = LangSysTable<'a>; fn bias() -> usize {2} fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>> {LangSysTable::new(data)} } impl Tagged for LangSys {} impl Indexed for LangSys {} impl<'a> ScriptTable<'a> { pub fn new(data: &'a[u8]) -> Result<ScriptTable<'a>, CorruptFont<'a>> {ScriptTable::new_list(data)} pub fn default_lang_sys(&self) -> Result<LangSysTable<'a>, CorruptFont<'a>> { let offset = read_u16(self.0).unwrap() as usize; println!("LS offset {:x}", offset); if offset == 0 { Ok(Default::default()) } else { if self.0.len() < offset {return Err(CorruptFont(self.0, OffsetOutOfBounds))} LangSysTable::new(&self.0[offset..]) } } pub fn validate_dflt(&self) -> Result<(), CorruptFont<'a>> { if read_u16(self.0).unwrap()!= 0 && self.num_tables() == 0 { Ok(()) } else { Err(CorruptFont(self.0, IncorrectDfltScript)) } } } use std::marker::PhantomData; pub trait TagListTable<'a>:'static + Indexed + Tagged { type Table; fn bias() -> usize {0} fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>>; } #[derive(Clone, Copy, PartialEq, Eq)] pub struct TagOffsetList<'a, Table: TagListTable<'a>>(&'a[u8], PhantomData<&'static Table>); pub trait Tagged {} pub struct Tag<Table: Tagged>(pub u32, PhantomData<Table>); impl<T: Tagged> Tag<T> {pub fn new(v: u32) -> Tag<T> {Tag(v, PhantomData)}} impl<'a, Table: TagListTable<'a>> TagOffsetList<'a, Table> { fn new_list(data: &'a[u8]) -> Result<TagOffsetList<'a, Table>, CorruptFont<'a>> { if data.len() < 2 + Table::bias() {return Err(CorruptFont(data, TableTooShort))} let res = TagOffsetList(data, PhantomData); if data.len() < res.num_tables() as usize*6 + 2 + Table::bias() {return Err(CorruptFont(data, TableTooShort))} Ok(res) } fn num_tables(&self) -> u16 {read_u16(&self.0[Table::bias()..]).unwrap()} pub fn tag(&self, Index(idx, _): Index<Table>) -> Option<Tag<Table>> {read_u32(&self.0[idx as usize*6+2+Table::bias()..]).map(|x|Tag(x, PhantomData))} pub fn table(&self, Index(index, _): Index<Table>) -> Option<Result<Table::Table, CorruptFont<'a>>> { let offset_pos = &self.0[index as usize*6 + 6 + Table::bias()..]; let offset = read_u16(offset_pos).unwrap() as usize; if self.0.len() < offset {return None} println!("offset {:x}", offset); Some(Table::new(&self.0[offset..])) } } impl<'a, Table: TagListTable<'a>> IntoIterator for TagOffsetList<'a, Table> { type Item = (Tag<Table>, Result<Table::Table, CorruptFont<'a>>); type IntoIter = TagOffsetIterator<'a, Table>; fn into_iter(self) -> TagOffsetIterator<'a, Table> {TagOffsetIterator(self, 0, PhantomData)} } #[derive(Clone, Copy)] pub struct TagOffsetIterator<'a, Table: TagListTable<'a>>(TagOffsetList<'a, Table>, u16, PhantomData<Table>); impl<'a, Table: TagListTable<'a>> Iterator for TagOffsetIterator<'a, Table> { type Item = (Tag<Table>, Result<Table::Table, CorruptFont<'a>>); fn next(&mut self) -> Option<<Self as Iterator>::Item> { if self.1 >= self.0.num_tables() { None } else { self.1 += 1; Some((self.0.tag(Index::new(self.1 - 1)).unwrap(), self.0.table(Index::new(self.1 - 1)).unwrap())) } } fn size_hint(&self) -> (usize, Option<usize>) {let res = self.0.num_tables() as usize; (res, Some(res))} } impl<'a, T: TagListTable<'a> + Tagged> ExactSizeIterator for TagOffsetIterator<'a, T> {} #[derive(Clone, Copy, PartialEq, Eq)] pub struct Script; pub type ScriptList<'a> = TagOffsetList<'a, Script>; impl<'a> TagListTable<'a> for Script {type Table = ScriptTable<'a>; fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>> {ScriptTable::new(data)}} impl Tagged for Script {} impl Indexed for Script {} impl<'a> ScriptList<'a> { pub fn new(data: &'a[u8]) -> Result<ScriptList<'a>, CorruptFont<'a>> {ScriptList::new_list(data)} pub fn features_for(&self, selector: Option<(Tag<Script>, Option<Tag<LangSys>>)>) -> Result<LangSysTable<'a>, CorruptFont<'a>> { let search = AutoSearch::new(self.num_tables() as usize*6); if let Some((script, lang_sys_opt)) = selector { match search.search(0..self.num_tables(), &mut move|&i| Ok(self.tag(Index::new(i)).unwrap().0.cmp(&script.0))) { Ok(idx) => { let script_table = try!(self.table(Index::new(idx)).unwrap()); if let Some(lang_sys) = lang_sys_opt { unimplemented!() } else { return script_table.default_lang_sys() } }, Err(Ok(_)) => {println!("default");return Ok(Default::default())}, Err(Err((_, e))) => return Err(e) } } match search.search(0..self.num_tables(), &mut move|&i| Ok(self.tag(Index::new(i)).unwrap().0.cmp(&DFLT_TAG.0))) { Ok(i) => { let script_table = try!(self.table(Index::new(i)).unwrap()); try!(script_table.validate_dflt()); script_table.default_lang_sys() }, Err(Ok(_)) => Ok(Default::default()), Err(Err((_, e))) => Err(e) } } } static DFLT_TAG: Tag<Script> = Tag(0x44464c54, PhantomData); #[derive(Clone, Copy, PartialEq, Eq)] pub struct Feature; pub type FeatureList<'a> = TagOffsetList<'a, Feature>; impl<'a> TagListTable<'a> for Feature {type Table = FeatureTable<'a>; fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>> {FeatureTable::new(data)}} impl Tagged for Feature {} impl Indexed for Feature {} impl<'a> FeatureList<'a> { fn new(data: &'a[u8]) -> Result<FeatureList<'a>, CorruptFont<'a>> {FeatureList::new_list(data)} } pub struct FeatureTable<'a>(&'a[u8]); impl<'a> FeatureTable<'a> { fn new(data: &'a[u8]) -> Result<FeatureTable<'a>, CorruptFont<'a>> { if data.len() < 4 {return Err(CorruptFont(data, TableTooShort))} if read_u16(data).unwrap()!= 0 {return Err(CorruptFont(data, ReservedFeature))} let len = read_u16(&data[2..]).unwrap(); if len as usize*2+4 > data.len() {return Err(CorruptFont(data, TableTooShort))} Ok(FeatureTable(&data[4..len as usize*2+4])) } fn lookups(&self) -> IndexList<'a, Lookup> {IndexList(&self.0[4..], PhantomData)} } pub struct IndexList<'a, T: Indexed>(&'a[u8], PhantomData<&'static T>); impl<'a, T: Indexed> IndexList<'a, T> { pub fn len(&self) -> usize {self.0.len()/2} } impl<'a, T: Indexed> ExactSizeIterator for IndexList<'a, T> {} impl<'a, T: Indexed> Iterator for IndexList<'a, T> { type Item = Index<T>; fn next(&mut self) -> Option<Index<T>> { if self.0.len() < 2 { None } else { let res = read_u16(self.0).unwrap(); self.0 = &self.0[2..]; Some(Index::new(res)) } } fn size_hint(&self) -> (usize, Option<usize>) {(self.len(), Some(self.len()))} } pub struct Lookup; impl Indexed for Lookup {} pub trait LookupContainer<'a>:'static + Sized { type Lookup; fn new_lookup(data: &'a[u8], lut: LookupList<'a, Self>) -> Result<Self::Lookup, CorruptFont<'a>>; } #[derive(Clone, Copy, PartialEq, Eq)] pub struct LookupList<'a, T: LookupContainer<'a>>(&'a[u8], PhantomData<&'static T>); impl<'a, T: LookupContainer<'a>> LookupList<'a, T> { fn new(data: &'a[u8]) -> Result<LookupList<'a, T>, CorruptFont<'a>> { if data.len() < 2 {return Err(CorruptFont(data, TableTooShort))} let res = LookupList(data, PhantomData); if data.len() < res.len() as usize*2+2 {return Err(CorruptFont(data, TableTooShort))} Ok(res) } fn len(&self) -> u16 {read_u16(self.0).unwrap()} fn get_lookup(self, Index(idx, _): Index<Lookup>) -> Option<Result<T::Lookup, CorruptFont<'a>>> { if idx >= self.len() {return None} let offset = read_u16(&self.0[2+idx as usize*2..]).unwrap(); Some(if offset as usize > self.0.len() { Err(CorruptFont(self.0, OffsetOutOfBounds)) } else { T::new_lookup(&self.0[offset as usize..], self) }) } } fn read_range(range: &[u8]) -> Result<(u16, u16, u16), CorruptFont> { let last = read_u16(&range[2..]).unwrap(); let first = read_u16(range).unwrap(); if last < first {return Err(CorruptFont(&range[..4], InvalidRange))} let offset = read_u16(&range[4..]).unwrap(); if 0xffff-(last-first) < offset {return Err(CorruptFont(range, WrappingCoverageIndex))} Ok((first, last, offset)) } pub enum Coverage<'a>{ Single(&'a[u8]), Range(&'a[u8]) } impl<'a> Coverage<'a> { fn new(data: &'a[u8]) -> Result<Coverage<'a>, CorruptFont<'a>> { if data.len() < 4 {return Err(CorruptFont(data, TableTooShort))} match read_u16(data).unwrap() { ver @ 1 | ver @ 2 => { let len = read_u16(&data[2..]).unwrap(); match ver { 1 => if data.len() < len as usize*2 { Err(CorruptFont(data, TableTooShort)) } else { Ok(Coverage::Single(&data[4..][..len as usize*2])) }, 2 => if data.len() < len as usize*6 { Err(CorruptFont(data, TableTooShort)) } else { Ok(Coverage::Range(&data[4..][..len as usize*6])) }, _ => unreachable!() } }, _ => Err(CorruptFont(data, ReservedFeature)) } } fn check(&self, GlyphIndex(glyph): GlyphIndex) -> Result<Option<Index<CoveredGlyph>>, CorruptFont<'a>> { let (data, step) = match self { &Coverage::Single(data) => (data, 2), &Coverage::Range(data) => (data, 6) }; match AutoSearch::new(data.len()).search(0..(data.len()/step) as u16, &mut move|i|Ok(read_u16(&data[*i as usize*step..]).unwrap().cmp(&glyph))) { Ok(i) => Ok(Some(Index::new(if step == 6 {read_u16(&data[i as usize*6+4..]).unwrap()} else {i}))), Err(Ok(i)) => { let range = &data[i as usize*6..][..6]; if step == 2 {return Ok(None)} let (first, last, offset) = try!(read_range(range)); Ok(if last >= glyph { Some(Index::new(glyph-first+offset)) } else { None }) }, Err(Err((_, CorruptFont(..)))) => unreachable!() } } } struct Co
impl Indexed for CoveredGlyph {} #[derive(Clone, Copy, PartialEq, Eq)] pub struct GSub<'a> { pub script_list: ScriptList<'a>, pub feature_list: FeatureList<'a>, pub lookup_list: LookupList<'a, GSubLookups> } impl<'a> GSub<'a> { fn new(data: &'a[u8]) -> Result<GSub<'a>, CorruptFont<'a>> { if data.len() < 10 {return Err(CorruptFont(data, TableTooShort))} if read_u32(data)!= Some(0x00010000) {return Err(CorruptFont(data, UnknownTableVersion))} let scr_off = read_u16(&data[4..]).unwrap() as usize; let feat_off = read_u16(&data[6..]).unwrap() as usize; let lut_off = read_u16(&data[8..]).unwrap() as usize; if data.len() < scr_off || data.len() < feat_off || data.len() < lut_off {return Err(CorruptFont(data, OffsetOutOfBounds))}
veredGlyph;
identifier_name
lib.rs
Rot180 {Normal, Rotated} #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ItemTypesetting(pub DirBehavior, pub Rot180); impl ItemTypesetting { fn effective_direction(&self) -> Direction { match self.1 { Rot180::Normal => self.0. 0, Rot180::Rotated => self.0. 0.reverse() } } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MainAxis {Ltr, Rtl, Ttb, Btt} macro_rules! try_opt { ($e:expr) => (match $e {Some(x)=>x, None=>return None}) } /// contains glyphs and typesetting information #[derive(PartialEq, Clone, Copy)] pub struct FontCollection<'a>{ pub tables: TableDirectory<'a>, pub gsub: Option<GSub<'a>> } #[derive(PartialEq, Clone, Copy)] pub struct TableDirectory<'a>{ data: &'a[u8], num_tables: u16 } impl<'a> TableDirectory<'a> { fn new(data: &[u8]) -> Result<TableDirectory, CorruptFont> { if data.len() < 12 {return Err(CorruptFont(data, TableTooShort))} let version = read_u32(data); if version!= Some(0x10000) && version!= Some(0x4f54544f) {return Err(CorruptFont(data, ReservedFeature))} let num_tables = read_u16(&data[4..]).unwrap(); if data.len() < num_tables as usize*16 + 12 { Err(CorruptFont(data, TableTooShort)) } else { Ok(TableDirectory { data: data, num_tables: num_tables }) } } fn find(&self, start: u16, label: u32) -> Option<(u16, &'a[u8])> { for pos_ in start..self.num_tables { let pos = pos_ as usize; let candidate = try_opt!(read_u32(&self.data[12+16*pos..])); if candidate == label { let start = read_u32(&self.data[12+16*pos+8..]).unwrap() as usize; return Some((pos as u16, &self.data[start..read_u32(&self.data[12+16*pos+12..]).unwrap() as usize+start])); } else if candidate > label { return None } } None } } /// contains character mapping #[derive(PartialEq, Clone, Copy)] pub struct Font<'a>{ pub cmap: CMap<'a>, glyph_src: &'a FontCollection<'a> } pub fn read_u32(data: &[u8]) -> Option<u32> { if data.len() > 3 { Some((data[0] as u32) << 24 | (data[1] as u32) << 16 | (data[2] as u32) << 8 | data[3] as u32) } else { None } } pub fn read_u16(data: &[u8]) -> Option<u16> { if data.len() > 1 { Some((data[0] as u16) << 8 | data[1] as u16) } else { None } } pub fn fourcc(tag: u32) -> String { let mut s = String::with_capacity(4); s.push((tag >> 24) as u8 as char); s.push((tag >> 16) as u8 as char); s.push((tag >> 8) as u8 as char); s.push(tag as u8 as char); s } fn find_best_cmap(cmap: &[u8]) -> Option<&[u8]> { let mut bmp = None; for encoding in 0..read_u16(&cmap[2..]).unwrap() as usize { let enc_header = &(&cmap[4+8*encoding..])[..8]; let (plat, enc) = (read_u16(enc_header).unwrap(), read_u16(&enc_header[2..]).unwrap()); match (plat, enc) { (0, 3) | (3, 1) => {bmp=Some(&cmap[try_opt!(read_u32(&enc_header[4..])) as usize..]);}, (0, 4) | (3, 10) => return Some(&cmap[try_opt!(read_u32(&enc_header[4..])) as usize..]), _ => {} // unknown encoding } } bmp } #[derive(PartialEq, Clone, Copy)] pub struct CMap<'otf>(Encoding<'otf>); impl<'otf> CMap<'otf> {pub fn lookup(&self, c: char) -> Option<GlyphIndex> {self.0.lookup(c)}} #[derive(PartialEq, Clone, Copy)] enum Encoding<'a> { Fmt4(CmapFmt4<'a>) } impl<'a> Encoding<'a> { pub fn lookup(&self, c: char) -> Option<GlyphIndex> { match *self { Encoding::Fmt4 (CmapFmt4 {end, start, delta, crazy_indexing_part: range_offset}) => { if c as u32 > 0xffff {return Some(GlyphIndex(0))} let mut range = 0..end.len()/2; while range.start!= range.end { let pivot = ((range.end - range.start) &!1) + range.start*2; let pivot_val = read_u16(&end[pivot..]).unwrap(); range = if pivot_val < c as u16 { pivot/2+1..range.end } else { range.start..pivot/2 }; } let seg_offset = range.start*2; let block_start = read_u16(&start[seg_offset..]).unwrap(); if block_start > c as u16 {return Some(GlyphIndex(0))} return Some(GlyphIndex((read_u16(&delta[seg_offset..]).unwrap()).wrapping_add({ let offset = read_u16(&range_offset[seg_offset..]).unwrap(); if offset == 0 { println!("delta: {} start: {}", read_u16(&delta[seg_offset..]).unwrap(), block_start); c as u16 } else { // this path is untested because the spec is really weird and I've never seen it used let res = read_u16(&range_offset[seg_offset+(offset as usize &!1)+(c as usize - block_start as usize)..]).unwrap(); if res == 0 { return Some(GlyphIndex(0)) } else { res } } }))) } } } } #[derive(PartialEq, Clone, Copy)] struct CmapFmt4<'a> { end: &'a[u8], start: &'a[u8], delta: &'a[u8], crazy_indexing_part: &'a[u8] } fn load_enc_table(mut enc: &[u8]) -> Result<Encoding, CorruptFont> { if enc.len() < 4 {return Err(CorruptFont(enc, TableTooShort))} let format = read_u16(enc).unwrap(); match format { 4 => { let len = read_u16(&enc[2..]).unwrap() as usize; if len > enc.len() && len < 14 {return Err(CorruptFont(enc, TableTooShort))} enc = &enc[..len]; let segsX2 = read_u16(&enc[6..]).unwrap() as usize; if segsX2 % 2!= 0 {return Err(CorruptFont(enc, OddSegsX2))} if segsX2 < 2 || 4*segsX2 + 16 > len {return Err(CorruptFont(enc, CmapInvalidSegmentCount))} let end = &enc[14..14+segsX2]; if read_u16(&end[segsX2-2..]).unwrap()!= 0xffff {return Err(CorruptFont(enc, CmapMissingGuard))} Ok(Encoding::Fmt4(CmapFmt4{ end: end, start: &enc[16+segsX2..16+2*segsX2], delta: &enc[16+2*segsX2..16+3*segsX2], crazy_indexing_part: &enc[16+3*segsX2..] })) }, _ => Err(CorruptFont(enc, Unimplemented)) } } pub fn load_font_collection(data: &[u8]) -> Result<FontCollection, CorruptFont> { let tables = try!(TableDirectory::new(data)); println!("#glyphs: {:?}", tables.find(0, 0x6d617870).and_then(|x|read_u16(&x.1[4..]))); let gsub = if let Some(x) = tables.find(0, GSUB_TAG) { Some(try!(GSub::new(x.1))) } else {None}; Ok(FontCollection { gsub: gsub, tables: tables }) } static CMAP_TAG: u32 = 0x636d6170; static HHEA_TAG: u32 = 0x68686561; static GSUB_TAG: u32 = 0x47535542; pub fn load_font<'a>(collection: &'a FontCollection<'a>, font: &str) -> Result<Font<'a>, CorruptFont<'a>> { let (_pos, cmap) = try!(collection.tables.find(0, CMAP_TAG).ok_or(CorruptFont(collection.tables.data, NoCmap))); let best_enc = try!(find_best_cmap(cmap).ok_or(CorruptFont(cmap, NoCmap))); let enc = try!(load_enc_table(best_enc)); Ok(Font {cmap: CMap(enc), glyph_src: collection}) } #[derive(Debug, Clone, Copy, PartialEq)] pub struct GlyphIndex(u16); #[derive(Debug, Clone, Copy)] pub struct MappedGlyph<'text> { pub range: &'text str, pub glyph: GlyphIndex, pub dir: Direction } pub trait CharMapper { /// given the text of the cluster, the character index relative to cluster start and the position within that character, return the byte offset into the cluster, where the cursor is fn map_cursor(&self, text: &str, character: usize, pos: Fractional) -> usize; fn map_range(&self, range: Range<usize>) -> Vec<Range<usize>>; } pub trait Shaper { type CharMapper: CharMapper; /// segment the string into clusters, shape the clusters and look up the glyphs (with given callback) /// /// first result is the characters, second the pairs of (first character index of cluster, string offset of cluster start) fn shape<T, F: FnMut(char) -> Option<T>>(&self, text: &str, lookup: &mut F) -> Option<(Vec<T>, Self::CharMapper)>; } #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq)] pub struct Fractional(u32); static FRACTIONAL_CENTER: Fractional = Fractional(0x80000000); mod shaping; pub use shaping::*; trait GlyphMapper { fn new() -> Self; fn map_char_to_glyph(&self, char_idx: usize, pos: Fractional) -> Option<(usize, Fractional)>; fn map_glyph_to_char(&self, glyph_idx: usize, pos: Fractional) -> Option<(usize, Fractional)>; } trait MonotonicSubstitution { type GlyphMapper: GlyphMapper; /// performs the substitution. Returns the number of characters affected. fn substitute_mutate(&self, forward: &mut Vec<GlyphIndex>, backward: &mut Vec<GlyphIndex>, map_fwd: &mut Self::GlyphMapper, map_bwd: &mut Self::GlyphMapper) -> Option<usize>; fn substitute(&self, mut glyphs: Vec<GlyphIndex>) -> Option<(Vec<GlyphIndex>, Self::GlyphMapper)> { let (mut m1, mut m2) = (Self::GlyphMapper::new(), Self::GlyphMapper::new()); try_opt!(self.substitute_mutate(&mut glyphs, &mut Vec::new(), &mut m1, &mut m2)); Some((glyphs, m1)) } } #[derive(Clone, Copy, Debug)] enum FontCorruption { Unimplemented, ReservedFeature, TableTooShort, OffsetOutOfBounds, IncorrectDfltScript, CmapInvalidSegmentCount, OddSegsX2, CmapMissingGuard, NoCmap, UnknownTableVersion, InvalidRange, WrappingCoverageIndex } use FontCorruption::*; #[derive(Clone, Copy, Debug)] pub struct CorruptFont<'a>(&'a[u8], FontCorruption); impl<'a> Error for CorruptFont<'a> { fn description(&self) -> &str {match self.1 { Unimplemented => "The font uses a feature that is not implemented", ReservedFeature => "A reserved field differed from the default value", TableTooShort => "Unexpected end of table", OffsetOutOfBounds => "An Offset pointed outside of the respective table", IncorrectDfltScript => "'DFLT' script with missing DefaultLangSys or LangSysCount ≠ 0", CmapInvalidSegmentCount => "The segment count in the character mapping is invalid", OddSegsX2 => "The doubled segment count in the character mapping is not an even number", CmapMissingGuard => "The character mapping is missing a guard value", NoCmap => "No character mapping found", UnknownTableVersion => "The font uses a table version that is not recognised", InvalidRange => "Invalid index range (last < first) found in font", WrappingCoverageIndex => "Index could wrap in Coverage Range" }} } impl<'a> ::std::fmt::Display for CorruptFont<'a> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { write!(f, "{}", self.description()) } } mod search; use search::{AutoSearch, SearchStrategy}; pub trait Indexed:'static {} pub struct Index<T: Indexed>(pub u16, PhantomData<&'static T>); impl<T: Indexed> Index<T> {pub fn new(x: u16) -> Index<T> {Index(x, PhantomData)}} impl<T: Indexed> std::fmt::Debug for Index<T> {fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {self.0.fmt(fmt)}} pub struct LangSysTable<'a>(&'a[u8]); impl<'a> LangSysTable<'a> { pub fn new(data: &'a[u8]) -> Result<LangSysTable<'a>, CorruptFont<'a>> { if data.len() < 6 {return Err(CorruptFont(data, TableTooShort))} if read_u16(data).unwrap()!= 0 {return Err(CorruptFont(data, ReservedFeature))} let num_features = read_u16(&data[4..]).unwrap(); if data.len() - 6 < num_features as usize*2 {return Err(CorruptFont(data, TableTooShort))} Ok(LangSysTable(&data[2..num_features as usize*2 + 6])) } pub fn num_features(&self) -> u16 {(self.0.len() / 2 - 2) as u16} pub fn required_feature(&self) -> Option<Index<Feature>> { let res = read_u16(self.0).unwrap(); if res == 0xffff {None} else {Some(Index::new(res))} } pub fn get_feature(&self, idx: u16) -> Option<Index<Feature>> {read_u16(&self.0[4 + idx as usize*2..]).map(|x| Index::new(x))} pub fn features(&self) -> IndexList<'a, Feature> {IndexList(&self.0[4..], PhantomData)} } static DEFAULT_LANGSYS_TABLE: [u8; 4] = [255, 255, 0, 0]; impl<'a> Default for LangSysTable<'a> { fn default() -> LangSysTable<'a> {LangSysTable(&DEFAULT_LANGSYS_TABLE)} } #[derive(Clone, Copy, PartialEq, Eq)] pub struct LangSys; pub type ScriptTable<'a> = TagOffsetList<'a, LangSys>; impl<'a> TagListTable<'a> for LangSys { type Table = LangSysTable<'a>; fn bias() -> usize {2} fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>> {LangSysTable::new(data)} } impl Tagged for LangSys {} impl Indexed for LangSys {} impl<'a> ScriptTable<'a> { pub fn new(data: &'a[u8]) -> Result<ScriptTable<'a>, CorruptFont<'a>> {ScriptTable::new_list(data)} pub fn default_lang_sys(&self) -> Result<LangSysTable<'a>, CorruptFont<'a>> { let offset = read_u16(self.0).unwrap() as usize; println!("LS offset {:x}", offset); if offset == 0 { Ok(Default::default()) } else { if self.0.len() < offset {return Err(CorruptFont(self.0, OffsetOutOfBounds))} LangSysTable::new(&self.0[offset..]) } } pub fn validate_dflt(&self) -> Result<(), CorruptFont<'a>> { if read_u16(self.0).unwrap()!= 0 && self.num_tables() == 0 { Ok(()) } else { Err(CorruptFont(self.0, IncorrectDfltScript)) } } } use std::marker::PhantomData; pub trait TagListTable<'a>:'static + Indexed + Tagged { type Table; fn bias() -> usize {0} fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>>; } #[derive(Clone, Copy, PartialEq, Eq)] pub struct TagOffsetList<'a, Table: TagListTable<'a>>(&'a[u8], PhantomData<&'static Table>); pub trait Tagged {} pub struct Tag<Table: Tagged>(pub u32, PhantomData<Table>); impl<T: Tagged> Tag<T> {pub fn new(v: u32) -> Tag<T> {Tag(v, PhantomData)}} impl<'a, Table: TagListTable<'a>> TagOffsetList<'a, Table> { fn new_list(data: &'a[u8]) -> Result<TagOffsetList<'a, Table>, CorruptFont<'a>> { if data.len() < 2 + Table::bias() {return Err(CorruptFont(data, TableTooShort))} let res = TagOffsetList(data, PhantomData); if data.len() < res.num_tables() as usize*6 + 2 + Table::bias() {return Err(CorruptFont(data, TableTooShort))} Ok(res) } fn num_tables(&self) -> u16 {read_u16(&self.0[Table::bias()..]).unwrap()} pub fn tag(&self, Index(idx, _): Index<Table>) -> Option<Tag<Table>> {read_u32(&self.0[idx as usize*6+2+Table::bias()..]).map(|x|Tag(x, PhantomData))} pub fn table(&self, Index(index, _): Index<Table>) -> Option<Result<Table::Table, CorruptFont<'a>>> { let offset_pos = &self.0[index as usize*6 + 6 + Table::bias()..]; let offset = read_u16(offset_pos).unwrap() as usize; if self.0.len() < offset {return None} println!("offset {:x}", offset); Some(Table::new(&self.0[offset..])) } } impl<'a, Table: TagListTable<'a>> IntoIterator for TagOffsetList<'a, Table> { type Item = (Tag<Table>, Result<Table::Table, CorruptFont<'a>>); type IntoIter = TagOffsetIterator<'a, Table>; fn into_iter(self) -> TagOffsetIterator<'a, Table> {TagOffsetIterator(self, 0, PhantomData)} } #[derive(Clone, Copy)] pub struct TagOffsetIterator<'a, Table: TagListTable<'a>>(TagOffsetList<'a, Table>, u16, PhantomData<Table>); impl<'a, Table: TagListTable<'a>> Iterator for TagOffsetIterator<'a, Table> { type Item = (Tag<Table>, Result<Table::Table, CorruptFont<'a>>); fn next(&mut self) -> Option<<Self as Iterator>::Item> { if self.1 >= self.0.num_tables() { None } else { self.1 += 1; Some((self.0.tag(Index::new(self.1 - 1)).unwrap(), self.0.table(Index::new(self.1 - 1)).unwrap())) } } fn size_hint(&self) -> (usize, Option<usize>) {let res = self.0.num_tables() as usize; (res, Some(res))} } impl<'a, T: TagListTable<'a> + Tagged> ExactSizeIterator for TagOffsetIterator<'a, T> {} #[derive(Clone, Copy, PartialEq, Eq)] pub struct Script; pub type ScriptList<'a> = TagOffsetList<'a, Script>; impl<'a> TagListTable<'a> for Script {type Table = ScriptTable<'a>; fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>> {ScriptTable::new(data)}} impl Tagged for Script {} impl Indexed for Script {} impl<'a> ScriptList<'a> { pub fn new(data: &'a[u8]) -> Result<ScriptList<'a>, CorruptFont<'a>> {S
pub fn features_for(&self, selector: Option<(Tag<Script>, Option<Tag<LangSys>>)>) -> Result<LangSysTable<'a>, CorruptFont<'a>> { let search = AutoSearch::new(self.num_tables() as usize*6); if let Some((script, lang_sys_opt)) = selector { match search.search(0..self.num_tables(), &mut move|&i| Ok(self.tag(Index::new(i)).unwrap().0.cmp(&script.0))) { Ok(idx) => { let script_table = try!(self.table(Index::new(idx)).unwrap()); if let Some(lang_sys) = lang_sys_opt { unimplemented!() } else { return script_table.default_lang_sys() } }, Err(Ok(_)) => {println!("default");return Ok(Default::default())}, Err(Err((_, e))) => return Err(e) } } match search.search(0..self.num_tables(), &mut move|&i| Ok(self.tag(Index::new(i)).unwrap().0.cmp(&DFLT_TAG.0))) { Ok(i) => { let script_table = try!(self.table(Index::new(i)).unwrap()); try!(script_table.validate_dflt()); script_table.default_lang_sys() }, Err(Ok(_)) => Ok(Default::default()), Err(Err((_, e))) => Err(e) } } } static DFLT_TAG: Tag<Script> = Tag(0x44464c54, PhantomData); #[derive(Clone, Copy, PartialEq, Eq)] pub struct Feature; pub type FeatureList<'a> = TagOffsetList<'a, Feature>; impl<'a> TagListTable<'a> for Feature {type Table = FeatureTable<'a>; fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>> {FeatureTable::new(data)}} impl Tagged for Feature {} impl Indexed for Feature {} impl<'a> FeatureList<'a> { fn new(data: &'a[u8]) -> Result<FeatureList<'a>, CorruptFont<'a>> {FeatureList::new_list(data)} } pub struct FeatureTable<'a>(&'a[u8]); impl<'a> FeatureTable<'a> { fn new(data: &'a[u8]) -> Result<FeatureTable<'a>, CorruptFont<'a>> { if data.len() < 4 {return Err(CorruptFont(data, TableTooShort))} if read_u16(data).unwrap()!= 0 {return Err(CorruptFont(data, ReservedFeature))} let len = read_u16(&data[2..]).unwrap(); if len as usize*2+4 > data.len() {return Err(CorruptFont(data, TableTooShort))} Ok(FeatureTable(&data[4..len as usize*2+4])) } fn lookups(&self) -> IndexList<'a, Lookup> {IndexList(&self.0[4..], PhantomData)} } pub struct IndexList<'a, T: Indexed>(&'a[u8], PhantomData<&'static T>); impl<'a, T: Indexed> IndexList<'a, T> { pub fn len(&self) -> usize {self.0.len()/2} } impl<'a, T: Indexed> ExactSizeIterator for IndexList<'a, T> {} impl<'a, T: Indexed> Iterator for IndexList<'a, T> { type Item = Index<T>; fn next(&mut self) -> Option<Index<T>> { if self.0.len() < 2 { None } else { let res = read_u16(self.0).unwrap(); self.0 = &self.0[2..]; Some(Index::new(res)) } } fn size_hint(&self) -> (usize, Option<usize>) {(self.len(), Some(self.len()))} } pub struct Lookup; impl Indexed for Lookup {} pub trait LookupContainer<'a>:'static + Sized { type Lookup; fn new_lookup(data: &'a[u8], lut: LookupList<'a, Self>) -> Result<Self::Lookup, CorruptFont<'a>>; } #[derive(Clone, Copy, PartialEq, Eq)] pub struct LookupList<'a, T: LookupContainer<'a>>(&'a[u8], PhantomData<&'static T>); impl<'a, T: LookupContainer<'a>> LookupList<'a, T> { fn new(data: &'a[u8]) -> Result<LookupList<'a, T>, CorruptFont<'a>> { if data.len() < 2 {return Err(CorruptFont(data, TableTooShort))} let res = LookupList(data, PhantomData); if data.len() < res.len() as usize*2+2 {return Err(CorruptFont(data, TableTooShort))} Ok(res) } fn len(&self) -> u16 {read_u16(self.0).unwrap()} fn get_lookup(self, Index(idx, _): Index<Lookup>) -> Option<Result<T::Lookup, CorruptFont<'a>>> { if idx >= self.len() {return None} let offset = read_u16(&self.0[2+idx as usize*2..]).unwrap(); Some(if offset as usize > self.0.len() { Err(CorruptFont(self.0, OffsetOutOfBounds)) } else { T::new_lookup(&self.0[offset as usize..], self) }) } } fn read_range(range: &[u8]) -> Result<(u16, u16, u16), CorruptFont> { let last = read_u16(&range[2..]).unwrap(); let first = read_u16(range).unwrap(); if last < first {return Err(CorruptFont(&range[..4], InvalidRange))} let offset = read_u16(&range[4..]).unwrap(); if 0xffff-(last-first) < offset {return Err(CorruptFont(range, WrappingCoverageIndex))} Ok((first, last, offset)) } pub enum Coverage<'a>{ Single(&'a[u8]), Range(&'a[u8]) } impl<'a> Coverage<'a> { fn new(data: &'a[u8]) -> Result<Coverage<'a>, CorruptFont<'a>> { if data.len() < 4 {return Err(CorruptFont(data, TableTooShort))} match read_u16(data).unwrap() { ver @ 1 | ver @ 2 => { let len = read_u16(&data[2..]).unwrap(); match ver { 1 => if data.len() < len as usize*2 { Err(CorruptFont(data, TableTooShort)) } else { Ok(Coverage::Single(&data[4..][..len as usize*2])) }, 2 => if data.len() < len as usize*6 { Err(CorruptFont(data, TableTooShort)) } else { Ok(Coverage::Range(&data[4..][..len as usize*6])) }, _ => unreachable!() } }, _ => Err(CorruptFont(data, ReservedFeature)) } } fn check(&self, GlyphIndex(glyph): GlyphIndex) -> Result<Option<Index<CoveredGlyph>>, CorruptFont<'a>> { let (data, step) = match self { &Coverage::Single(data) => (data, 2), &Coverage::Range(data) => (data, 6) }; match AutoSearch::new(data.len()).search(0..(data.len()/step) as u16, &mut move|i|Ok(read_u16(&data[*i as usize*step..]).unwrap().cmp(&glyph))) { Ok(i) => Ok(Some(Index::new(if step == 6 {read_u16(&data[i as usize*6+4..]).unwrap()} else {i}))), Err(Ok(i)) => { let range = &data[i as usize*6..][..6]; if step == 2 {return Ok(None)} let (first, last, offset) = try!(read_range(range)); Ok(if last >= glyph { Some(Index::new(glyph-first+offset)) } else { None }) }, Err(Err((_, CorruptFont(..)))) => unreachable!() } } } struct CoveredGlyph; impl Indexed for CoveredGlyph {} #[derive(Clone, Copy, PartialEq, Eq)] pub struct GSub<'a> { pub script_list: ScriptList<'a>, pub feature_list: FeatureList<'a>, pub lookup_list: LookupList<'a, GSubLookups> } impl<'a> GSub<'a> { fn new(data: &'a[u8]) -> Result<GSub<'a>, CorruptFont<'a>> { if data.len() < 10 {return Err(CorruptFont(data, TableTooShort))} if read_u32(data)!= Some(0x00010000) {return Err(CorruptFont(data, UnknownTableVersion))} let scr_off = read_u16(&data[4..]).unwrap() as usize; let feat_off = read_u16(&data[6..]).unwrap() as usize; let lut_off = read_u16(&data[8..]).unwrap() as usize; if data.len() < scr_off || data.len() < feat_off || data.len() < lut_off {return Err(CorruptFont(data, OffsetOutOfBounds))}
criptList::new_list(data)}
identifier_body
lib.rs
enum Rot180 {Normal, Rotated} #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ItemTypesetting(pub DirBehavior, pub Rot180); impl ItemTypesetting { fn effective_direction(&self) -> Direction { match self.1 { Rot180::Normal => self.0. 0, Rot180::Rotated => self.0. 0.reverse() } } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MainAxis {Ltr, Rtl, Ttb, Btt} macro_rules! try_opt { ($e:expr) => (match $e {Some(x)=>x, None=>return None}) } /// contains glyphs and typesetting information #[derive(PartialEq, Clone, Copy)] pub struct FontCollection<'a>{ pub tables: TableDirectory<'a>, pub gsub: Option<GSub<'a>> } #[derive(PartialEq, Clone, Copy)] pub struct TableDirectory<'a>{ data: &'a[u8], num_tables: u16 } impl<'a> TableDirectory<'a> { fn new(data: &[u8]) -> Result<TableDirectory, CorruptFont> { if data.len() < 12 {return Err(CorruptFont(data, TableTooShort))} let version = read_u32(data); if version!= Some(0x10000) && version!= Some(0x4f54544f) {return Err(CorruptFont(data, ReservedFeature))} let num_tables = read_u16(&data[4..]).unwrap(); if data.len() < num_tables as usize*16 + 12 { Err(CorruptFont(data, TableTooShort)) } else { Ok(TableDirectory { data: data, num_tables: num_tables }) } } fn find(&self, start: u16, label: u32) -> Option<(u16, &'a[u8])> { for pos_ in start..self.num_tables { let pos = pos_ as usize; let candidate = try_opt!(read_u32(&self.data[12+16*pos..])); if candidate == label { let start = read_u32(&self.data[12+16*pos+8..]).unwrap() as usize; return Some((pos as u16, &self.data[start..read_u32(&self.data[12+16*pos+12..]).unwrap() as usize+start])); } else if candidate > label { return None } } None } } /// contains character mapping #[derive(PartialEq, Clone, Copy)] pub struct Font<'a>{ pub cmap: CMap<'a>, glyph_src: &'a FontCollection<'a> } pub fn read_u32(data: &[u8]) -> Option<u32> { if data.len() > 3 { Some((data[0] as u32) << 24 | (data[1] as u32) << 16 | (data[2] as u32) << 8 | data[3] as u32) } else { None } } pub fn read_u16(data: &[u8]) -> Option<u16> { if data.len() > 1 { Some((data[0] as u16) << 8 | data[1] as u16) } else { None } } pub fn fourcc(tag: u32) -> String { let mut s = String::with_capacity(4); s.push((tag >> 24) as u8 as char); s.push((tag >> 16) as u8 as char); s.push((tag >> 8) as u8 as char); s.push(tag as u8 as char); s } fn find_best_cmap(cmap: &[u8]) -> Option<&[u8]> { let mut bmp = None; for encoding in 0..read_u16(&cmap[2..]).unwrap() as usize { let enc_header = &(&cmap[4+8*encoding..])[..8]; let (plat, enc) = (read_u16(enc_header).unwrap(), read_u16(&enc_header[2..]).unwrap()); match (plat, enc) { (0, 3) | (3, 1) => {bmp=Some(&cmap[try_opt!(read_u32(&enc_header[4..])) as usize..]);}, (0, 4) | (3, 10) => return Some(&cmap[try_opt!(read_u32(&enc_header[4..])) as usize..]), _ => {} // unknown encoding } } bmp } #[derive(PartialEq, Clone, Copy)] pub struct CMap<'otf>(Encoding<'otf>); impl<'otf> CMap<'otf> {pub fn lookup(&self, c: char) -> Option<GlyphIndex> {self.0.lookup(c)}} #[derive(PartialEq, Clone, Copy)] enum Encoding<'a> { Fmt4(CmapFmt4<'a>) } impl<'a> Encoding<'a> { pub fn lookup(&self, c: char) -> Option<GlyphIndex> { match *self { Encoding::Fmt4 (CmapFmt4 {end, start, delta, crazy_indexing_part: range_offset}) => { if c as u32 > 0xffff {return Some(GlyphIndex(0))} let mut range = 0..end.len()/2; while range.start!= range.end { let pivot = ((range.end - range.start) &!1) + range.start*2; let pivot_val = read_u16(&end[pivot..]).unwrap(); range = if pivot_val < c as u16 { pivot/2+1..range.end } else { range.start..pivot/2 }; } let seg_offset = range.start*2; let block_start = read_u16(&start[seg_offset..]).unwrap(); if block_start > c as u16 {return Some(GlyphIndex(0))} return Some(GlyphIndex((read_u16(&delta[seg_offset..]).unwrap()).wrapping_add({ let offset = read_u16(&range_offset[seg_offset..]).unwrap(); if offset == 0 { println!("delta: {} start: {}", read_u16(&delta[seg_offset..]).unwrap(), block_start); c as u16 } else { // this path is untested because the spec is really weird and I've never seen it used let res = read_u16(&range_offset[seg_offset+(offset as usize &!1)+(c as usize - block_start as usize)..]).unwrap(); if res == 0 { return Some(GlyphIndex(0)) } else { res } } }))) } } } } #[derive(PartialEq, Clone, Copy)] struct CmapFmt4<'a> { end: &'a[u8], start: &'a[u8], delta: &'a[u8], crazy_indexing_part: &'a[u8] } fn load_enc_table(mut enc: &[u8]) -> Result<Encoding, CorruptFont> { if enc.len() < 4 {return Err(CorruptFont(enc, TableTooShort))} let format = read_u16(enc).unwrap(); match format { 4 => { let len = read_u16(&enc[2..]).unwrap() as usize; if len > enc.len() && len < 14 {return Err(CorruptFont(enc, TableTooShort))} enc = &enc[..len]; let segsX2 = read_u16(&enc[6..]).unwrap() as usize; if segsX2 % 2!= 0 {return Err(CorruptFont(enc, OddSegsX2))} if segsX2 < 2 || 4*segsX2 + 16 > len {return Err(CorruptFont(enc, CmapInvalidSegmentCount))} let end = &enc[14..14+segsX2]; if read_u16(&end[segsX2-2..]).unwrap()!= 0xffff {return Err(CorruptFont(enc, CmapMissingGuard))} Ok(Encoding::Fmt4(CmapFmt4{ end: end, start: &enc[16+segsX2..16+2*segsX2], delta: &enc[16+2*segsX2..16+3*segsX2], crazy_indexing_part: &enc[16+3*segsX2..] })) }, _ => Err(CorruptFont(enc, Unimplemented)) } } pub fn load_font_collection(data: &[u8]) -> Result<FontCollection, CorruptFont> { let tables = try!(TableDirectory::new(data)); println!("#glyphs: {:?}", tables.find(0, 0x6d617870).and_then(|x|read_u16(&x.1[4..]))); let gsub = if let Some(x) = tables.find(0, GSUB_TAG) { Some(try!(GSub::new(x.1))) } else {None}; Ok(FontCollection { gsub: gsub, tables: tables }) } static CMAP_TAG: u32 = 0x636d6170; static HHEA_TAG: u32 = 0x68686561; static GSUB_TAG: u32 = 0x47535542; pub fn load_font<'a>(collection: &'a FontCollection<'a>, font: &str) -> Result<Font<'a>, CorruptFont<'a>> { let (_pos, cmap) = try!(collection.tables.find(0, CMAP_TAG).ok_or(CorruptFont(collection.tables.data, NoCmap))); let best_enc = try!(find_best_cmap(cmap).ok_or(CorruptFont(cmap, NoCmap))); let enc = try!(load_enc_table(best_enc)); Ok(Font {cmap: CMap(enc), glyph_src: collection}) } #[derive(Debug, Clone, Copy, PartialEq)] pub struct GlyphIndex(u16); #[derive(Debug, Clone, Copy)] pub struct MappedGlyph<'text> { pub range: &'text str, pub glyph: GlyphIndex, pub dir: Direction } pub trait CharMapper { /// given the text of the cluster, the character index relative to cluster start and the position within that character, return the byte offset into the cluster, where the cursor is fn map_cursor(&self, text: &str, character: usize, pos: Fractional) -> usize; fn map_range(&self, range: Range<usize>) -> Vec<Range<usize>>; } pub trait Shaper { type CharMapper: CharMapper; /// segment the string into clusters, shape the clusters and look up the glyphs (with given callback) /// /// first result is the characters, second the pairs of (first character index of cluster, string offset of cluster start) fn shape<T, F: FnMut(char) -> Option<T>>(&self, text: &str, lookup: &mut F) -> Option<(Vec<T>, Self::CharMapper)>; } #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq)] pub struct Fractional(u32); static FRACTIONAL_CENTER: Fractional = Fractional(0x80000000); mod shaping; pub use shaping::*; trait GlyphMapper { fn new() -> Self; fn map_char_to_glyph(&self, char_idx: usize, pos: Fractional) -> Option<(usize, Fractional)>; fn map_glyph_to_char(&self, glyph_idx: usize, pos: Fractional) -> Option<(usize, Fractional)>; } trait MonotonicSubstitution { type GlyphMapper: GlyphMapper; /// performs the substitution. Returns the number of characters affected. fn substitute_mutate(&self, forward: &mut Vec<GlyphIndex>, backward: &mut Vec<GlyphIndex>, map_fwd: &mut Self::GlyphMapper, map_bwd: &mut Self::GlyphMapper) -> Option<usize>; fn substitute(&self, mut glyphs: Vec<GlyphIndex>) -> Option<(Vec<GlyphIndex>, Self::GlyphMapper)> { let (mut m1, mut m2) = (Self::GlyphMapper::new(), Self::GlyphMapper::new()); try_opt!(self.substitute_mutate(&mut glyphs, &mut Vec::new(), &mut m1, &mut m2)); Some((glyphs, m1)) } } #[derive(Clone, Copy, Debug)] enum FontCorruption { Unimplemented, ReservedFeature, TableTooShort, OffsetOutOfBounds, IncorrectDfltScript, CmapInvalidSegmentCount, OddSegsX2, CmapMissingGuard, NoCmap, UnknownTableVersion, InvalidRange, WrappingCoverageIndex } use FontCorruption::*; #[derive(Clone, Copy, Debug)] pub struct CorruptFont<'a>(&'a[u8], FontCorruption); impl<'a> Error for CorruptFont<'a> { fn description(&self) -> &str {match self.1 { Unimplemented => "The font uses a feature that is not implemented", ReservedFeature => "A reserved field differed from the default value", TableTooShort => "Unexpected end of table", OffsetOutOfBounds => "An Offset pointed outside of the respective table", IncorrectDfltScript => "'DFLT' script with missing DefaultLangSys or LangSysCount ≠ 0", CmapInvalidSegmentCount => "The segment count in the character mapping is invalid", OddSegsX2 => "The doubled segment count in the character mapping is not an even number", CmapMissingGuard => "The character mapping is missing a guard value", NoCmap => "No character mapping found", UnknownTableVersion => "The font uses a table version that is not recognised", InvalidRange => "Invalid index range (last < first) found in font", WrappingCoverageIndex => "Index could wrap in Coverage Range" }} } impl<'a> ::std::fmt::Display for CorruptFont<'a> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { write!(f, "{}", self.description()) } } mod search; use search::{AutoSearch, SearchStrategy}; pub trait Indexed:'static {} pub struct Index<T: Indexed>(pub u16, PhantomData<&'static T>); impl<T: Indexed> Index<T> {pub fn new(x: u16) -> Index<T> {Index(x, PhantomData)}} impl<T: Indexed> std::fmt::Debug for Index<T> {fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {self.0.fmt(fmt)}} pub struct LangSysTable<'a>(&'a[u8]); impl<'a> LangSysTable<'a> { pub fn new(data: &'a[u8]) -> Result<LangSysTable<'a>, CorruptFont<'a>> { if data.len() < 6 {return Err(CorruptFont(data, TableTooShort))} if read_u16(data).unwrap()!= 0 {return Err(CorruptFont(data, ReservedFeature))} let num_features = read_u16(&data[4..]).unwrap(); if data.len() - 6 < num_features as usize*2 {return Err(CorruptFont(data, TableTooShort))} Ok(LangSysTable(&data[2..num_features as usize*2 + 6])) } pub fn num_features(&self) -> u16 {(self.0.len() / 2 - 2) as u16} pub fn required_feature(&self) -> Option<Index<Feature>> { let res = read_u16(self.0).unwrap(); if res == 0xffff {None} else {Some(Index::new(res))} } pub fn get_feature(&self, idx: u16) -> Option<Index<Feature>> {read_u16(&self.0[4 + idx as usize*2..]).map(|x| Index::new(x))} pub fn features(&self) -> IndexList<'a, Feature> {IndexList(&self.0[4..], PhantomData)} } static DEFAULT_LANGSYS_TABLE: [u8; 4] = [255, 255, 0, 0]; impl<'a> Default for LangSysTable<'a> { fn default() -> LangSysTable<'a> {LangSysTable(&DEFAULT_LANGSYS_TABLE)} } #[derive(Clone, Copy, PartialEq, Eq)] pub struct LangSys; pub type ScriptTable<'a> = TagOffsetList<'a, LangSys>; impl<'a> TagListTable<'a> for LangSys { type Table = LangSysTable<'a>; fn bias() -> usize {2} fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>> {LangSysTable::new(data)} } impl Tagged for LangSys {} impl Indexed for LangSys {} impl<'a> ScriptTable<'a> { pub fn new(data: &'a[u8]) -> Result<ScriptTable<'a>, CorruptFont<'a>> {ScriptTable::new_list(data)} pub fn default_lang_sys(&self) -> Result<LangSysTable<'a>, CorruptFont<'a>> { let offset = read_u16(self.0).unwrap() as usize; println!("LS offset {:x}", offset); if offset == 0 { Ok(Default::default()) } else { if self.0.len() < offset {return Err(CorruptFont(self.0, OffsetOutOfBounds))} LangSysTable::new(&self.0[offset..]) } } pub fn validate_dflt(&self) -> Result<(), CorruptFont<'a>> { if read_u16(self.0).unwrap()!= 0 && self.num_tables() == 0 { Ok(()) } else { Err(CorruptFont(self.0, IncorrectDfltScript)) } } } use std::marker::PhantomData; pub trait TagListTable<'a>:'static + Indexed + Tagged { type Table; fn bias() -> usize {0} fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>>; } #[derive(Clone, Copy, PartialEq, Eq)] pub struct TagOffsetList<'a, Table: TagListTable<'a>>(&'a[u8], PhantomData<&'static Table>); pub trait Tagged {} pub struct Tag<Table: Tagged>(pub u32, PhantomData<Table>); impl<T: Tagged> Tag<T> {pub fn new(v: u32) -> Tag<T> {Tag(v, PhantomData)}} impl<'a, Table: TagListTable<'a>> TagOffsetList<'a, Table> { fn new_list(data: &'a[u8]) -> Result<TagOffsetList<'a, Table>, CorruptFont<'a>> { if data.len() < 2 + Table::bias() {return Err(CorruptFont(data, TableTooShort))} let res = TagOffsetList(data, PhantomData); if data.len() < res.num_tables() as usize*6 + 2 + Table::bias() {return Err(CorruptFont(data, TableTooShort))} Ok(res) } fn num_tables(&self) -> u16 {read_u16(&self.0[Table::bias()..]).unwrap()} pub fn tag(&self, Index(idx, _): Index<Table>) -> Option<Tag<Table>> {read_u32(&self.0[idx as usize*6+2+Table::bias()..]).map(|x|Tag(x, PhantomData))} pub fn table(&self, Index(index, _): Index<Table>) -> Option<Result<Table::Table, CorruptFont<'a>>> { let offset_pos = &self.0[index as usize*6 + 6 + Table::bias()..]; let offset = read_u16(offset_pos).unwrap() as usize; if self.0.len() < offset {return None} println!("offset {:x}", offset); Some(Table::new(&self.0[offset..])) } } impl<'a, Table: TagListTable<'a>> IntoIterator for TagOffsetList<'a, Table> { type Item = (Tag<Table>, Result<Table::Table, CorruptFont<'a>>); type IntoIter = TagOffsetIterator<'a, Table>; fn into_iter(self) -> TagOffsetIterator<'a, Table> {TagOffsetIterator(self, 0, PhantomData)} } #[derive(Clone, Copy)] pub struct TagOffsetIterator<'a, Table: TagListTable<'a>>(TagOffsetList<'a, Table>, u16, PhantomData<Table>); impl<'a, Table: TagListTable<'a>> Iterator for TagOffsetIterator<'a, Table> { type Item = (Tag<Table>, Result<Table::Table, CorruptFont<'a>>); fn next(&mut self) -> Option<<Self as Iterator>::Item> { if self.1 >= self.0.num_tables() { None } else { self.1 += 1; Some((self.0.tag(Index::new(self.1 - 1)).unwrap(), self.0.table(Index::new(self.1 - 1)).unwrap())) } } fn size_hint(&self) -> (usize, Option<usize>) {let res = self.0.num_tables() as usize; (res, Some(res))} } impl<'a, T: TagListTable<'a> + Tagged> ExactSizeIterator for TagOffsetIterator<'a, T> {} #[derive(Clone, Copy, PartialEq, Eq)] pub struct Script; pub type ScriptList<'a> = TagOffsetList<'a, Script>; impl<'a> TagListTable<'a> for Script {type Table = ScriptTable<'a>; fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>> {ScriptTable::new(data)}} impl Tagged for Script {} impl Indexed for Script {} impl<'a> ScriptList<'a> { pub fn new(data: &'a[u8]) -> Result<ScriptList<'a>, CorruptFont<'a>> {ScriptList::new_list(data)} pub fn features_for(&self, selector: Option<(Tag<Script>, Option<Tag<LangSys>>)>) -> Result<LangSysTable<'a>, CorruptFont<'a>> { let search = AutoSearch::new(self.num_tables() as usize*6); if let Some((script, lang_sys_opt)) = selector { match search.search(0..self.num_tables(), &mut move|&i| Ok(self.tag(Index::new(i)).unwrap().0.cmp(&script.0))) { Ok(idx) => { let script_table = try!(self.table(Index::new(idx)).unwrap()); if let Some(lang_sys) = lang_sys_opt { unimplemented!() } else { return script_table.default_lang_sys() } }, Err(Ok(_)) => {println!("default");return Ok(Default::default())}, Err(Err((_, e))) => return Err(e) } } match search.search(0..self.num_tables(), &mut move|&i| Ok(self.tag(Index::new(i)).unwrap().0.cmp(&DFLT_TAG.0))) { Ok(i) => { let script_table = try!(self.table(Index::new(i)).unwrap()); try!(script_table.validate_dflt()); script_table.default_lang_sys() }, Err(Ok(_)) => Ok(Default::default()), Err(Err((_, e))) => Err(e) } } } static DFLT_TAG: Tag<Script> = Tag(0x44464c54, PhantomData); #[derive(Clone, Copy, PartialEq, Eq)] pub struct Feature; pub type FeatureList<'a> = TagOffsetList<'a, Feature>; impl<'a> TagListTable<'a> for Feature {type Table = FeatureTable<'a>; fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>> {FeatureTable::new(data)}} impl Tagged for Feature {} impl Indexed for Feature {} impl<'a> FeatureList<'a> { fn new(data: &'a[u8]) -> Result<FeatureList<'a>, CorruptFont<'a>> {FeatureList::new_list(data)} } pub struct FeatureTable<'a>(&'a[u8]); impl<'a> FeatureTable<'a> { fn new(data: &'a[u8]) -> Result<FeatureTable<'a>, CorruptFont<'a>> { if data.len() < 4 {return Err(CorruptFont(data, TableTooShort))} if read_u16(data).unwrap()!= 0 {return Err(CorruptFont(data, ReservedFeature))} let len = read_u16(&data[2..]).unwrap(); if len as usize*2+4 > data.len() {return Err(CorruptFont(data, TableTooShort))} Ok(FeatureTable(&data[4..len as usize*2+4])) } fn lookups(&self) -> IndexList<'a, Lookup> {IndexList(&self.0[4..], PhantomData)} } pub struct IndexList<'a, T: Indexed>(&'a[u8], PhantomData<&'static T>); impl<'a, T: Indexed> IndexList<'a, T> { pub fn len(&self) -> usize {self.0.len()/2} } impl<'a, T: Indexed> ExactSizeIterator for IndexList<'a, T> {} impl<'a, T: Indexed> Iterator for IndexList<'a, T> { type Item = Index<T>; fn next(&mut self) -> Option<Index<T>> { if self.0.len() < 2 { None } else { let res = read_u16(self.0).unwrap(); self.0 = &self.0[2..]; Some(Index::new(res)) } } fn size_hint(&self) -> (usize, Option<usize>) {(self.len(), Some(self.len()))} } pub struct Lookup; impl Indexed for Lookup {} pub trait LookupContainer<'a>:'static + Sized { type Lookup; fn new_lookup(data: &'a[u8], lut: LookupList<'a, Self>) -> Result<Self::Lookup, CorruptFont<'a>>;
fn new(data: &'a[u8]) -> Result<LookupList<'a, T>, CorruptFont<'a>> { if data.len() < 2 {return Err(CorruptFont(data, TableTooShort))} let res = LookupList(data, PhantomData); if data.len() < res.len() as usize*2+2 {return Err(CorruptFont(data, TableTooShort))} Ok(res) } fn len(&self) -> u16 {read_u16(self.0).unwrap()} fn get_lookup(self, Index(idx, _): Index<Lookup>) -> Option<Result<T::Lookup, CorruptFont<'a>>> { if idx >= self.len() {return None} let offset = read_u16(&self.0[2+idx as usize*2..]).unwrap(); Some(if offset as usize > self.0.len() { Err(CorruptFont(self.0, OffsetOutOfBounds)) } else { T::new_lookup(&self.0[offset as usize..], self) }) } } fn read_range(range: &[u8]) -> Result<(u16, u16, u16), CorruptFont> { let last = read_u16(&range[2..]).unwrap(); let first = read_u16(range).unwrap(); if last < first {return Err(CorruptFont(&range[..4], InvalidRange))} let offset = read_u16(&range[4..]).unwrap(); if 0xffff-(last-first) < offset {return Err(CorruptFont(range, WrappingCoverageIndex))} Ok((first, last, offset)) } pub enum Coverage<'a>{ Single(&'a[u8]), Range(&'a[u8]) } impl<'a> Coverage<'a> { fn new(data: &'a[u8]) -> Result<Coverage<'a>, CorruptFont<'a>> { if data.len() < 4 {return Err(CorruptFont(data, TableTooShort))} match read_u16(data).unwrap() { ver @ 1 | ver @ 2 => { let len = read_u16(&data[2..]).unwrap(); match ver { 1 => if data.len() < len as usize*2 { Err(CorruptFont(data, TableTooShort)) } else { Ok(Coverage::Single(&data[4..][..len as usize*2])) }, 2 => if data.len() < len as usize*6 { Err(CorruptFont(data, TableTooShort)) } else { Ok(Coverage::Range(&data[4..][..len as usize*6])) }, _ => unreachable!() } }, _ => Err(CorruptFont(data, ReservedFeature)) } } fn check(&self, GlyphIndex(glyph): GlyphIndex) -> Result<Option<Index<CoveredGlyph>>, CorruptFont<'a>> { let (data, step) = match self { &Coverage::Single(data) => (data, 2), &Coverage::Range(data) => (data, 6) }; match AutoSearch::new(data.len()).search(0..(data.len()/step) as u16, &mut move|i|Ok(read_u16(&data[*i as usize*step..]).unwrap().cmp(&glyph))) { Ok(i) => Ok(Some(Index::new(if step == 6 {read_u16(&data[i as usize*6+4..]).unwrap()} else {i}))), Err(Ok(i)) => { let range = &data[i as usize*6..][..6]; if step == 2 {return Ok(None)} let (first, last, offset) = try!(read_range(range)); Ok(if last >= glyph { Some(Index::new(glyph-first+offset)) } else { None }) }, Err(Err((_, CorruptFont(..)))) => unreachable!() } } } struct CoveredGlyph; impl Indexed for CoveredGlyph {} #[derive(Clone, Copy, PartialEq, Eq)] pub struct GSub<'a> { pub script_list: ScriptList<'a>, pub feature_list: FeatureList<'a>, pub lookup_list: LookupList<'a, GSubLookups> } impl<'a> GSub<'a> { fn new(data: &'a[u8]) -> Result<GSub<'a>, CorruptFont<'a>> { if data.len() < 10 {return Err(CorruptFont(data, TableTooShort))} if read_u32(data)!= Some(0x00010000) {return Err(CorruptFont(data, UnknownTableVersion))} let scr_off = read_u16(&data[4..]).unwrap() as usize; let feat_off = read_u16(&data[6..]).unwrap() as usize; let lut_off = read_u16(&data[8..]).unwrap() as usize; if data.len() < scr_off || data.len() < feat_off || data.len() < lut_off {return Err(CorruptFont(data, OffsetOutOfBounds))} Ok(
} #[derive(Clone, Copy, PartialEq, Eq)] pub struct LookupList<'a, T: LookupContainer<'a>>(&'a[u8], PhantomData<&'static T>); impl<'a, T: LookupContainer<'a>> LookupList<'a, T> {
random_line_split
lib.rs
Rot180 {Normal, Rotated} #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ItemTypesetting(pub DirBehavior, pub Rot180); impl ItemTypesetting { fn effective_direction(&self) -> Direction { match self.1 { Rot180::Normal => self.0. 0, Rot180::Rotated => self.0. 0.reverse() } } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MainAxis {Ltr, Rtl, Ttb, Btt} macro_rules! try_opt { ($e:expr) => (match $e {Some(x)=>x, None=>return None}) } /// contains glyphs and typesetting information #[derive(PartialEq, Clone, Copy)] pub struct FontCollection<'a>{ pub tables: TableDirectory<'a>, pub gsub: Option<GSub<'a>> } #[derive(PartialEq, Clone, Copy)] pub struct TableDirectory<'a>{ data: &'a[u8], num_tables: u16 } impl<'a> TableDirectory<'a> { fn new(data: &[u8]) -> Result<TableDirectory, CorruptFont> { if data.len() < 12 {return Err(CorruptFont(data, TableTooShort))} let version = read_u32(data); if version!= Some(0x10000) && version!= Some(0x4f54544f) {return Err(CorruptFont(data, ReservedFeature))} let num_tables = read_u16(&data[4..]).unwrap(); if data.len() < num_tables as usize*16 + 12 { Err(CorruptFont(data, TableTooShort)) } else { Ok(TableDirectory { data: data, num_tables: num_tables }) } } fn find(&self, start: u16, label: u32) -> Option<(u16, &'a[u8])> { for pos_ in start..self.num_tables { let pos = pos_ as usize; let candidate = try_opt!(read_u32(&self.data[12+16*pos..])); if candidate == label { let start = read_u32(&self.data[12+16*pos+8..]).unwrap() as usize; return Some((pos as u16, &self.data[start..read_u32(&self.data[12+16*pos+12..]).unwrap() as usize+start])); } else if candidate > label { return None } } None } } /// contains character mapping #[derive(PartialEq, Clone, Copy)] pub struct Font<'a>{ pub cmap: CMap<'a>, glyph_src: &'a FontCollection<'a> } pub fn read_u32(data: &[u8]) -> Option<u32> { if data.len() > 3 { Some((data[0] as u32) << 24 | (data[1] as u32) << 16 | (data[2] as u32) << 8 | data[3] as u32) } else { None } } pub fn read_u16(data: &[u8]) -> Option<u16> { if data.len() > 1 { Some((data[0] as u16) << 8 | data[1] as u16) } else { None } } pub fn fourcc(tag: u32) -> String { let mut s = String::with_capacity(4); s.push((tag >> 24) as u8 as char); s.push((tag >> 16) as u8 as char); s.push((tag >> 8) as u8 as char); s.push(tag as u8 as char); s } fn find_best_cmap(cmap: &[u8]) -> Option<&[u8]> { let mut bmp = None; for encoding in 0..read_u16(&cmap[2..]).unwrap() as usize { let enc_header = &(&cmap[4+8*encoding..])[..8]; let (plat, enc) = (read_u16(enc_header).unwrap(), read_u16(&enc_header[2..]).unwrap()); match (plat, enc) { (0, 3) | (3, 1) => {bmp=Some(&cmap[try_opt!(read_u32(&enc_header[4..])) as usize..]);}, (0, 4) | (3, 10) => return Some(&cmap[try_opt!(read_u32(&enc_header[4..])) as usize..]), _ => {} // unknown encoding } } bmp } #[derive(PartialEq, Clone, Copy)] pub struct CMap<'otf>(Encoding<'otf>); impl<'otf> CMap<'otf> {pub fn lookup(&self, c: char) -> Option<GlyphIndex> {self.0.lookup(c)}} #[derive(PartialEq, Clone, Copy)] enum Encoding<'a> { Fmt4(CmapFmt4<'a>) } impl<'a> Encoding<'a> { pub fn lookup(&self, c: char) -> Option<GlyphIndex> { match *self { Encoding::Fmt4 (CmapFmt4 {end, start, delta, crazy_indexing_part: range_offset}) => { if c as u32 > 0xffff {return Some(GlyphIndex(0))} let mut range = 0..end.len()/2; while range.start!= range.end { let pivot = ((range.end - range.start) &!1) + range.start*2; let pivot_val = read_u16(&end[pivot..]).unwrap(); range = if pivot_val < c as u16 { pivot/2+1..range.end } else { range.start..pivot/2 }; } let seg_offset = range.start*2; let block_start = read_u16(&start[seg_offset..]).unwrap(); if block_start > c as u16 {return Some(GlyphIndex(0))} return Some(GlyphIndex((read_u16(&delta[seg_offset..]).unwrap()).wrapping_add({ let offset = read_u16(&range_offset[seg_offset..]).unwrap(); if offset == 0 { println!("delta: {} start: {}", read_u16(&delta[seg_offset..]).unwrap(), block_start); c as u16 } else { // this path is untested because the spec is really weird and I've never seen it used let res = read_u16(&range_offset[seg_offset+(offset as usize &!1)+(c as usize - block_start as usize)..]).unwrap(); if res == 0 { return Some(GlyphIndex(0)) } else { res } } }))) } } } } #[derive(PartialEq, Clone, Copy)] struct CmapFmt4<'a> { end: &'a[u8], start: &'a[u8], delta: &'a[u8], crazy_indexing_part: &'a[u8] } fn load_enc_table(mut enc: &[u8]) -> Result<Encoding, CorruptFont> { if enc.len() < 4 {return Err(CorruptFont(enc, TableTooShort))} let format = read_u16(enc).unwrap(); match format { 4 => { let len = read_u16(&enc[2..]).unwrap() as usize; if len > enc.len() && len < 14 {return Err(CorruptFont(enc, TableTooShort))} enc = &enc[..len]; let segsX2 = read_u16(&enc[6..]).unwrap() as usize; if segsX2 % 2!= 0 {return Err(CorruptFont(enc, OddSegsX2))} if segsX2 < 2 || 4*segsX2 + 16 > len {return Err(CorruptFont(enc, CmapInvalidSegmentCount))} let end = &enc[14..14+segsX2]; if read_u16(&end[segsX2-2..]).unwrap()!= 0xffff {return Err(CorruptFont(enc, CmapMissingGuard))} Ok(Encoding::Fmt4(CmapFmt4{ end: end, start: &enc[16+segsX2..16+2*segsX2], delta: &enc[16+2*segsX2..16+3*segsX2], crazy_indexing_part: &enc[16+3*segsX2..] })) }, _ => Err(CorruptFont(enc, Unimplemented)) } } pub fn load_font_collection(data: &[u8]) -> Result<FontCollection, CorruptFont> { let tables = try!(TableDirectory::new(data)); println!("#glyphs: {:?}", tables.find(0, 0x6d617870).and_then(|x|read_u16(&x.1[4..]))); let gsub = if let Some(x) = tables.find(0, GSUB_TAG) { Some(try!(GSub::new(x.1))) } else {None}; Ok(FontCollection { gsub: gsub, tables: tables }) } static CMAP_TAG: u32 = 0x636d6170; static HHEA_TAG: u32 = 0x68686561; static GSUB_TAG: u32 = 0x47535542; pub fn load_font<'a>(collection: &'a FontCollection<'a>, font: &str) -> Result<Font<'a>, CorruptFont<'a>> { let (_pos, cmap) = try!(collection.tables.find(0, CMAP_TAG).ok_or(CorruptFont(collection.tables.data, NoCmap))); let best_enc = try!(find_best_cmap(cmap).ok_or(CorruptFont(cmap, NoCmap))); let enc = try!(load_enc_table(best_enc)); Ok(Font {cmap: CMap(enc), glyph_src: collection}) } #[derive(Debug, Clone, Copy, PartialEq)] pub struct GlyphIndex(u16); #[derive(Debug, Clone, Copy)] pub struct MappedGlyph<'text> { pub range: &'text str, pub glyph: GlyphIndex, pub dir: Direction } pub trait CharMapper { /// given the text of the cluster, the character index relative to cluster start and the position within that character, return the byte offset into the cluster, where the cursor is fn map_cursor(&self, text: &str, character: usize, pos: Fractional) -> usize; fn map_range(&self, range: Range<usize>) -> Vec<Range<usize>>; } pub trait Shaper { type CharMapper: CharMapper; /// segment the string into clusters, shape the clusters and look up the glyphs (with given callback) /// /// first result is the characters, second the pairs of (first character index of cluster, string offset of cluster start) fn shape<T, F: FnMut(char) -> Option<T>>(&self, text: &str, lookup: &mut F) -> Option<(Vec<T>, Self::CharMapper)>; } #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq)] pub struct Fractional(u32); static FRACTIONAL_CENTER: Fractional = Fractional(0x80000000); mod shaping; pub use shaping::*; trait GlyphMapper { fn new() -> Self; fn map_char_to_glyph(&self, char_idx: usize, pos: Fractional) -> Option<(usize, Fractional)>; fn map_glyph_to_char(&self, glyph_idx: usize, pos: Fractional) -> Option<(usize, Fractional)>; } trait MonotonicSubstitution { type GlyphMapper: GlyphMapper; /// performs the substitution. Returns the number of characters affected. fn substitute_mutate(&self, forward: &mut Vec<GlyphIndex>, backward: &mut Vec<GlyphIndex>, map_fwd: &mut Self::GlyphMapper, map_bwd: &mut Self::GlyphMapper) -> Option<usize>; fn substitute(&self, mut glyphs: Vec<GlyphIndex>) -> Option<(Vec<GlyphIndex>, Self::GlyphMapper)> { let (mut m1, mut m2) = (Self::GlyphMapper::new(), Self::GlyphMapper::new()); try_opt!(self.substitute_mutate(&mut glyphs, &mut Vec::new(), &mut m1, &mut m2)); Some((glyphs, m1)) } } #[derive(Clone, Copy, Debug)] enum FontCorruption { Unimplemented, ReservedFeature, TableTooShort, OffsetOutOfBounds, IncorrectDfltScript, CmapInvalidSegmentCount, OddSegsX2, CmapMissingGuard, NoCmap, UnknownTableVersion, InvalidRange, WrappingCoverageIndex } use FontCorruption::*; #[derive(Clone, Copy, Debug)] pub struct CorruptFont<'a>(&'a[u8], FontCorruption); impl<'a> Error for CorruptFont<'a> { fn description(&self) -> &str {match self.1 { Unimplemented => "The font uses a feature that is not implemented", ReservedFeature => "A reserved field differed from the default value", TableTooShort => "Unexpected end of table", OffsetOutOfBounds => "An Offset pointed outside of the respective table", IncorrectDfltScript => "'DFLT' script with missing DefaultLangSys or LangSysCount ≠ 0", CmapInvalidSegmentCount => "The segment count in the character mapping is invalid", OddSegsX2 => "The doubled segment count in the character mapping is not an even number", CmapMissingGuard => "The character mapping is missing a guard value", NoCmap => "No character mapping found", UnknownTableVersion => "The font uses a table version that is not recognised", InvalidRange => "Invalid index range (last < first) found in font", WrappingCoverageIndex => "Index could wrap in Coverage Range" }} } impl<'a> ::std::fmt::Display for CorruptFont<'a> { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { write!(f, "{}", self.description()) } } mod search; use search::{AutoSearch, SearchStrategy}; pub trait Indexed:'static {} pub struct Index<T: Indexed>(pub u16, PhantomData<&'static T>); impl<T: Indexed> Index<T> {pub fn new(x: u16) -> Index<T> {Index(x, PhantomData)}} impl<T: Indexed> std::fmt::Debug for Index<T> {fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {self.0.fmt(fmt)}} pub struct LangSysTable<'a>(&'a[u8]); impl<'a> LangSysTable<'a> { pub fn new(data: &'a[u8]) -> Result<LangSysTable<'a>, CorruptFont<'a>> { if data.len() < 6 {return Err(CorruptFont(data, TableTooShort))} if read_u16(data).unwrap()!= 0 {return Err(CorruptFont(data, ReservedFeature))} let num_features = read_u16(&data[4..]).unwrap(); if data.len() - 6 < num_features as usize*2 {return Err(CorruptFont(data, TableTooShort))} Ok(LangSysTable(&data[2..num_features as usize*2 + 6])) } pub fn num_features(&self) -> u16 {(self.0.len() / 2 - 2) as u16} pub fn required_feature(&self) -> Option<Index<Feature>> { let res = read_u16(self.0).unwrap(); if res == 0xffff {None} else {Some(Index::new(res))} } pub fn get_feature(&self, idx: u16) -> Option<Index<Feature>> {read_u16(&self.0[4 + idx as usize*2..]).map(|x| Index::new(x))} pub fn features(&self) -> IndexList<'a, Feature> {IndexList(&self.0[4..], PhantomData)} } static DEFAULT_LANGSYS_TABLE: [u8; 4] = [255, 255, 0, 0]; impl<'a> Default for LangSysTable<'a> { fn default() -> LangSysTable<'a> {LangSysTable(&DEFAULT_LANGSYS_TABLE)} } #[derive(Clone, Copy, PartialEq, Eq)] pub struct LangSys; pub type ScriptTable<'a> = TagOffsetList<'a, LangSys>; impl<'a> TagListTable<'a> for LangSys { type Table = LangSysTable<'a>; fn bias() -> usize {2} fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>> {LangSysTable::new(data)} } impl Tagged for LangSys {} impl Indexed for LangSys {} impl<'a> ScriptTable<'a> { pub fn new(data: &'a[u8]) -> Result<ScriptTable<'a>, CorruptFont<'a>> {ScriptTable::new_list(data)} pub fn default_lang_sys(&self) -> Result<LangSysTable<'a>, CorruptFont<'a>> { let offset = read_u16(self.0).unwrap() as usize; println!("LS offset {:x}", offset); if offset == 0 { Ok(Default::default()) } else { if self.0.len() < offset {return Err(CorruptFont(self.0, OffsetOutOfBounds))} LangSysTable::new(&self.0[offset..]) } } pub fn validate_dflt(&self) -> Result<(), CorruptFont<'a>> { if read_u16(self.0).unwrap()!= 0 && self.num_tables() == 0 { Ok(()) } else { Err(CorruptFont(self.0, IncorrectDfltScript)) } } } use std::marker::PhantomData; pub trait TagListTable<'a>:'static + Indexed + Tagged { type Table; fn bias() -> usize {0} fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>>; } #[derive(Clone, Copy, PartialEq, Eq)] pub struct TagOffsetList<'a, Table: TagListTable<'a>>(&'a[u8], PhantomData<&'static Table>); pub trait Tagged {} pub struct Tag<Table: Tagged>(pub u32, PhantomData<Table>); impl<T: Tagged> Tag<T> {pub fn new(v: u32) -> Tag<T> {Tag(v, PhantomData)}} impl<'a, Table: TagListTable<'a>> TagOffsetList<'a, Table> { fn new_list(data: &'a[u8]) -> Result<TagOffsetList<'a, Table>, CorruptFont<'a>> { if data.len() < 2 + Table::bias() {return Err(CorruptFont(data, TableTooShort))} let res = TagOffsetList(data, PhantomData); if data.len() < res.num_tables() as usize*6 + 2 + Table::bias() {return Err(CorruptFont(data, TableTooShort))} Ok(res) } fn num_tables(&self) -> u16 {read_u16(&self.0[Table::bias()..]).unwrap()} pub fn tag(&self, Index(idx, _): Index<Table>) -> Option<Tag<Table>> {read_u32(&self.0[idx as usize*6+2+Table::bias()..]).map(|x|Tag(x, PhantomData))} pub fn table(&self, Index(index, _): Index<Table>) -> Option<Result<Table::Table, CorruptFont<'a>>> { let offset_pos = &self.0[index as usize*6 + 6 + Table::bias()..]; let offset = read_u16(offset_pos).unwrap() as usize; if self.0.len() < offset {return None} println!("offset {:x}", offset); Some(Table::new(&self.0[offset..])) } } impl<'a, Table: TagListTable<'a>> IntoIterator for TagOffsetList<'a, Table> { type Item = (Tag<Table>, Result<Table::Table, CorruptFont<'a>>); type IntoIter = TagOffsetIterator<'a, Table>; fn into_iter(self) -> TagOffsetIterator<'a, Table> {TagOffsetIterator(self, 0, PhantomData)} } #[derive(Clone, Copy)] pub struct TagOffsetIterator<'a, Table: TagListTable<'a>>(TagOffsetList<'a, Table>, u16, PhantomData<Table>); impl<'a, Table: TagListTable<'a>> Iterator for TagOffsetIterator<'a, Table> { type Item = (Tag<Table>, Result<Table::Table, CorruptFont<'a>>); fn next(&mut self) -> Option<<Self as Iterator>::Item> { if self.1 >= self.0.num_tables() { None } else { self.1 += 1; Some((self.0.tag(Index::new(self.1 - 1)).unwrap(), self.0.table(Index::new(self.1 - 1)).unwrap())) } } fn size_hint(&self) -> (usize, Option<usize>) {let res = self.0.num_tables() as usize; (res, Some(res))} } impl<'a, T: TagListTable<'a> + Tagged> ExactSizeIterator for TagOffsetIterator<'a, T> {} #[derive(Clone, Copy, PartialEq, Eq)] pub struct Script; pub type ScriptList<'a> = TagOffsetList<'a, Script>; impl<'a> TagListTable<'a> for Script {type Table = ScriptTable<'a>; fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>> {ScriptTable::new(data)}} impl Tagged for Script {} impl Indexed for Script {} impl<'a> ScriptList<'a> { pub fn new(data: &'a[u8]) -> Result<ScriptList<'a>, CorruptFont<'a>> {ScriptList::new_list(data)} pub fn features_for(&self, selector: Option<(Tag<Script>, Option<Tag<LangSys>>)>) -> Result<LangSysTable<'a>, CorruptFont<'a>> { let search = AutoSearch::new(self.num_tables() as usize*6); if let Some((script, lang_sys_opt)) = selector { match search.search(0..self.num_tables(), &mut move|&i| Ok(self.tag(Index::new(i)).unwrap().0.cmp(&script.0))) { Ok(idx) => { let script_table = try!(self.table(Index::new(idx)).unwrap()); if let Some(lang_sys) = lang_sys_opt { unimplemented!() } else { return script_table.default_lang_sys() } }, Err(Ok(_)) => {println!("default");return Ok(Default::default())}, Err(Err((_, e))) => return Err(e) } } match search.search(0..self.num_tables(), &mut move|&i| Ok(self.tag(Index::new(i)).unwrap().0.cmp(&DFLT_TAG.0))) { Ok(i) => { let script_table = try!(self.table(Index::new(i)).unwrap()); try!(script_table.validate_dflt()); script_table.default_lang_sys() }, Err(Ok(_)) => Ok(Default::default()), Err(Err((_, e))) => Err(e) } } } static DFLT_TAG: Tag<Script> = Tag(0x44464c54, PhantomData); #[derive(Clone, Copy, PartialEq, Eq)] pub struct Feature; pub type FeatureList<'a> = TagOffsetList<'a, Feature>; impl<'a> TagListTable<'a> for Feature {type Table = FeatureTable<'a>; fn new(data: &'a[u8]) -> Result<Self::Table, CorruptFont<'a>> {FeatureTable::new(data)}} impl Tagged for Feature {} impl Indexed for Feature {} impl<'a> FeatureList<'a> { fn new(data: &'a[u8]) -> Result<FeatureList<'a>, CorruptFont<'a>> {FeatureList::new_list(data)} } pub struct FeatureTable<'a>(&'a[u8]); impl<'a> FeatureTable<'a> { fn new(data: &'a[u8]) -> Result<FeatureTable<'a>, CorruptFont<'a>> { if data.len() < 4 {return Err(CorruptFont(data, TableTooShort))} if read_u16(data).unwrap()!= 0 {return Err(CorruptFont(data, ReservedFeature))} let len = read_u16(&data[2..]).unwrap(); if len as usize*2+4 > data.len() {return Err(CorruptFont(data, TableTooShort))} Ok(FeatureTable(&data[4..len as usize*2+4])) } fn lookups(&self) -> IndexList<'a, Lookup> {IndexList(&self.0[4..], PhantomData)} } pub struct IndexList<'a, T: Indexed>(&'a[u8], PhantomData<&'static T>); impl<'a, T: Indexed> IndexList<'a, T> { pub fn len(&self) -> usize {self.0.len()/2} } impl<'a, T: Indexed> ExactSizeIterator for IndexList<'a, T> {} impl<'a, T: Indexed> Iterator for IndexList<'a, T> { type Item = Index<T>; fn next(&mut self) -> Option<Index<T>> { if self.0.len() < 2 { None } else { let res = read_u16(self.0).unwrap(); self.0 = &self.0[2..]; Some(Index::new(res)) } } fn size_hint(&self) -> (usize, Option<usize>) {(self.len(), Some(self.len()))} } pub struct Lookup; impl Indexed for Lookup {} pub trait LookupContainer<'a>:'static + Sized { type Lookup; fn new_lookup(data: &'a[u8], lut: LookupList<'a, Self>) -> Result<Self::Lookup, CorruptFont<'a>>; } #[derive(Clone, Copy, PartialEq, Eq)] pub struct LookupList<'a, T: LookupContainer<'a>>(&'a[u8], PhantomData<&'static T>); impl<'a, T: LookupContainer<'a>> LookupList<'a, T> { fn new(data: &'a[u8]) -> Result<LookupList<'a, T>, CorruptFont<'a>> { if data.len() < 2 {return Err(CorruptFont(data, TableTooShort))} let res = LookupList(data, PhantomData); if data.len() < res.len() as usize*2+2 {return Err(CorruptFont(data, TableTooShort))} Ok(res) } fn len(&self) -> u16 {read_u16(self.0).unwrap()} fn get_lookup(self, Index(idx, _): Index<Lookup>) -> Option<Result<T::Lookup, CorruptFont<'a>>> { if idx >= self.len() {return None} let offset = read_u16(&self.0[2+idx as usize*2..]).unwrap(); Some(if offset as usize > self.0.len() { Err(CorruptFont(self.0, OffsetOutOfBounds)) } else { T::new_lookup(&self.0[offset as usize..], self) }) } } fn read_range(range: &[u8]) -> Result<(u16, u16, u16), CorruptFont> { let last = read_u16(&range[2..]).unwrap(); let first = read_u16(range).unwrap(); if last < first {return Err(CorruptFont(&range[..4], InvalidRange))} let offset = read_u16(&range[4..]).unwrap(); if 0xffff-(last-first) < offset {return Err(CorruptFont(range, WrappingCoverageIndex))} Ok((first, last, offset)) } pub enum Coverage<'a>{ Single(&'a[u8]), Range(&'a[u8]) } impl<'a> Coverage<'a> { fn new(data: &'a[u8]) -> Result<Coverage<'a>, CorruptFont<'a>> { if data.len() < 4 {return Err(CorruptFont(data, TableTooShort))} match read_u16(data).unwrap() { ver @ 1 | ver @ 2 => { let len = read_u16(&data[2..]).unwrap(); match ver { 1 => if data.len() < len as usize*2 { Err(CorruptFont(data, TableTooShort)) } else { Ok(Coverage::Single(&data[4..][..len as usize*2])) }, 2 => if data.len() < len as usize*6 { Err(CorruptFont(data, TableTooShort)) } else { Ok(Coverage::Range(&data[4..][..len as usize*6])) }, _ => unreachable!() } }, _ => Err(CorruptFont(data, ReservedFeature)) } } fn check(&self, GlyphIndex(glyph): GlyphIndex) -> Result<Option<Index<CoveredGlyph>>, CorruptFont<'a>> { let (data, step) = match self { &Coverage::Single(data) => (data, 2), &Coverage::Range(data) => (data, 6) }; match AutoSearch::new(data.len()).search(0..(data.len()/step) as u16, &mut move|i|Ok(read_u16(&data[*i as usize*step..]).unwrap().cmp(&glyph))) { Ok(i) => Ok(Some(Index::new(if step == 6 {read_u16(&data[i as usize*6+4..]).unwrap()} else {i
), Err(Ok(i)) => { let range = &data[i as usize*6..][..6]; if step == 2 {return Ok(None)} let (first, last, offset) = try!(read_range(range)); Ok(if last >= glyph { Some(Index::new(glyph-first+offset)) } else { None }) }, Err(Err((_, CorruptFont(..)))) => unreachable!() } } } struct CoveredGlyph; impl Indexed for CoveredGlyph {} #[derive(Clone, Copy, PartialEq, Eq)] pub struct GSub<'a> { pub script_list: ScriptList<'a>, pub feature_list: FeatureList<'a>, pub lookup_list: LookupList<'a, GSubLookups> } impl<'a> GSub<'a> { fn new(data: &'a[u8]) -> Result<GSub<'a>, CorruptFont<'a>> { if data.len() < 10 {return Err(CorruptFont(data, TableTooShort))} if read_u32(data)!= Some(0x00010000) {return Err(CorruptFont(data, UnknownTableVersion))} let scr_off = read_u16(&data[4..]).unwrap() as usize; let feat_off = read_u16(&data[6..]).unwrap() as usize; let lut_off = read_u16(&data[8..]).unwrap() as usize; if data.len() < scr_off || data.len() < feat_off || data.len() < lut_off {return Err(CorruptFont(data, OffsetOutOfBounds))} Ok
}))
conditional_block
fmt.rs
#[macro_use] extern crate custom_derive; #[macro_use] extern crate newtype_derive; use std::fmt::{self, Binary, Debug, Display, LowerExp, LowerHex, Octal, Pointer, UpperExp, UpperHex}; macro_rules! impl_fmt { (impl $tr:ident for $name:ident: $msg:expr) => { impl $tr for $name { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, $msg) } } }; } struct Dummy; impl_fmt!(impl Binary for Dummy: "binary"); impl_fmt!(impl Debug for Dummy: "debug"); impl_fmt!(impl Display for Dummy: "display"); impl_fmt!(impl LowerExp for Dummy: "lowerexp"); impl_fmt!(impl LowerHex for Dummy: "lowerhex"); impl_fmt!(impl Octal for Dummy: "octal"); impl_fmt!(impl Pointer for Dummy: "pointer"); impl_fmt!(impl UpperExp for Dummy: "upperexp"); impl_fmt!(impl UpperHex for Dummy: "upperhex"); custom_derive! { #[derive( NewtypeBinary, NewtypeDebug, NewtypeDisplay, NewtypeLowerExp, NewtypeLowerHex, NewtypeOctal,
NewtypePointer, NewtypeUpperExp, NewtypeUpperHex )] struct Wrapper(Dummy); } #[test] fn test_fmt() { let a = Wrapper(Dummy); assert_eq!(&*format!("{:b}", a), "binary"); assert_eq!(&*format!("{:?}", a), "debug"); assert_eq!(&*format!("{}", a), "display"); assert_eq!(&*format!("{:e}", a), "lowerexp"); assert_eq!(&*format!("{:x}", a), "lowerhex"); assert_eq!(&*format!("{:o}", a), "octal"); assert_eq!(&*format!("{:p}", a), "pointer"); assert_eq!(&*format!("{:E}", a), "upperexp"); assert_eq!(&*format!("{:X}", a), "upperhex"); }
random_line_split
fmt.rs
#[macro_use] extern crate custom_derive; #[macro_use] extern crate newtype_derive; use std::fmt::{self, Binary, Debug, Display, LowerExp, LowerHex, Octal, Pointer, UpperExp, UpperHex}; macro_rules! impl_fmt { (impl $tr:ident for $name:ident: $msg:expr) => { impl $tr for $name { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, $msg) } } }; } struct
; impl_fmt!(impl Binary for Dummy: "binary"); impl_fmt!(impl Debug for Dummy: "debug"); impl_fmt!(impl Display for Dummy: "display"); impl_fmt!(impl LowerExp for Dummy: "lowerexp"); impl_fmt!(impl LowerHex for Dummy: "lowerhex"); impl_fmt!(impl Octal for Dummy: "octal"); impl_fmt!(impl Pointer for Dummy: "pointer"); impl_fmt!(impl UpperExp for Dummy: "upperexp"); impl_fmt!(impl UpperHex for Dummy: "upperhex"); custom_derive! { #[derive( NewtypeBinary, NewtypeDebug, NewtypeDisplay, NewtypeLowerExp, NewtypeLowerHex, NewtypeOctal, NewtypePointer, NewtypeUpperExp, NewtypeUpperHex )] struct Wrapper(Dummy); } #[test] fn test_fmt() { let a = Wrapper(Dummy); assert_eq!(&*format!("{:b}", a), "binary"); assert_eq!(&*format!("{:?}", a), "debug"); assert_eq!(&*format!("{}", a), "display"); assert_eq!(&*format!("{:e}", a), "lowerexp"); assert_eq!(&*format!("{:x}", a), "lowerhex"); assert_eq!(&*format!("{:o}", a), "octal"); assert_eq!(&*format!("{:p}", a), "pointer"); assert_eq!(&*format!("{:E}", a), "upperexp"); assert_eq!(&*format!("{:X}", a), "upperhex"); }
Dummy
identifier_name
sjisprober.rs
use std::ops::Deref; use std::ops::DerefMut; use super::enums::MachineState; use super::mbcharsetprober::MultiByteCharsetProber; use super::charsetprober::CharsetProber; use super::enums::ProbingState; use super::codingstatemachine::CodingStateMachine; use super::mbcssm::SJIS_SM_MODEL; use super::chardistribution::SJISDistributionAnalysis; use super::jpcntx::{JapaneseContextAnalysis, SJISContextAnalysis}; pub struct SJISProber<'a> { base: MultiByteCharsetProber<'a>, m_context_analyzer: SJISContextAnalysis, } impl<'x> Deref for SJISProber<'x> { type Target = MultiByteCharsetProber<'x>; fn deref<'a>(&'a self) -> &'a MultiByteCharsetProber<'x> { &self.base } } impl<'x> DerefMut for SJISProber<'x> { fn deref_mut<'a>(&'a mut self) -> &'a mut MultiByteCharsetProber<'x> { &mut self.base } } impl<'a> CharsetProber for SJISProber<'a> { fn reset(&mut self) { self.base.reset(); self.m_context_analyzer.reset(); } fn feed(&mut self, byte_str: &[u8]) -> &ProbingState { { let sm = self.base.m_coding_sm.as_mut().unwrap(); let da = self.base.m_distribution_analyzer.as_mut().unwrap(); for i in 0..byte_str.len() { match sm.next_state(byte_str[i]) { MachineState::START =>
MachineState::ERROR => { self.base.m_state = ProbingState::NotMe; break; } MachineState::ITS_ME => { self.base.m_state = ProbingState::FoundIt; break; } _ => {} } } } self.base.m_last_char[0] = byte_str[byte_str.len() - 1]; if self.base.m_state == ProbingState::Detecting { if (self.m_context_analyzer.got_enough_data()) && (self.get_confidence() > 0.95) { self.base.m_state = ProbingState::FoundIt; } } &self.base.m_state } fn get_charset(&self) -> String { self.m_context_analyzer.get_charset() } fn get_confidence(&self) -> f32 { let a = self.base.get_confidence(); let b = self.m_context_analyzer.get_confidence(); if a>b { a } else { b } } fn get_language(&self) -> String { "Japanese".to_string() } fn get_state(&self) -> &ProbingState { self.base.get_state() } } impl<'a> SJISProber<'a> { pub fn new() -> SJISProber<'a> { let mut x = SJISProber { base: MultiByteCharsetProber::new(), m_context_analyzer: SJISContextAnalysis::new(), }; x.base.m_coding_sm = Some(CodingStateMachine::new(&SJIS_SM_MODEL)); x.base.m_distribution_analyzer = Some(Box::new(SJISDistributionAnalysis::new())); x } }
{ let char_len = sm.get_current_charlen(); if i == 0 { self.base.m_last_char[1] = byte_str[0]; self.m_context_analyzer.feed( &self.base.m_last_char[(2 - char_len) as usize..], char_len as usize, ); da.feed(&self.base.m_last_char[..], char_len); } else { self.m_context_analyzer.feed( &byte_str[i + 1 - char_len as usize..], char_len as usize, ); da.feed(&byte_str[i - 1..i + 1], char_len); } }
conditional_block
sjisprober.rs
use std::ops::Deref; use std::ops::DerefMut; use super::enums::MachineState; use super::mbcharsetprober::MultiByteCharsetProber; use super::charsetprober::CharsetProber; use super::enums::ProbingState; use super::codingstatemachine::CodingStateMachine; use super::mbcssm::SJIS_SM_MODEL; use super::chardistribution::SJISDistributionAnalysis; use super::jpcntx::{JapaneseContextAnalysis, SJISContextAnalysis}; pub struct SJISProber<'a> { base: MultiByteCharsetProber<'a>, m_context_analyzer: SJISContextAnalysis, } impl<'x> Deref for SJISProber<'x> { type Target = MultiByteCharsetProber<'x>; fn deref<'a>(&'a self) -> &'a MultiByteCharsetProber<'x> { &self.base } } impl<'x> DerefMut for SJISProber<'x> { fn deref_mut<'a>(&'a mut self) -> &'a mut MultiByteCharsetProber<'x> { &mut self.base } } impl<'a> CharsetProber for SJISProber<'a> { fn reset(&mut self) { self.base.reset(); self.m_context_analyzer.reset(); } fn feed(&mut self, byte_str: &[u8]) -> &ProbingState { { let sm = self.base.m_coding_sm.as_mut().unwrap(); let da = self.base.m_distribution_analyzer.as_mut().unwrap(); for i in 0..byte_str.len() { match sm.next_state(byte_str[i]) { MachineState::START => { let char_len = sm.get_current_charlen(); if i == 0 { self.base.m_last_char[1] = byte_str[0]; self.m_context_analyzer.feed( &self.base.m_last_char[(2 - char_len) as usize..], char_len as usize, ); da.feed(&self.base.m_last_char[..], char_len); } else { self.m_context_analyzer.feed( &byte_str[i + 1 - char_len as usize..], char_len as usize, ); da.feed(&byte_str[i - 1..i + 1], char_len); } } MachineState::ERROR => { self.base.m_state = ProbingState::NotMe; break; } MachineState::ITS_ME => { self.base.m_state = ProbingState::FoundIt; break; } _ => {} } } } self.base.m_last_char[0] = byte_str[byte_str.len() - 1]; if self.base.m_state == ProbingState::Detecting { if (self.m_context_analyzer.got_enough_data()) && (self.get_confidence() > 0.95) { self.base.m_state = ProbingState::FoundIt; } } &self.base.m_state } fn get_charset(&self) -> String { self.m_context_analyzer.get_charset() } fn get_confidence(&self) -> f32 { let a = self.base.get_confidence(); let b = self.m_context_analyzer.get_confidence(); if a>b { a } else { b } } fn get_language(&self) -> String {
} } impl<'a> SJISProber<'a> { pub fn new() -> SJISProber<'a> { let mut x = SJISProber { base: MultiByteCharsetProber::new(), m_context_analyzer: SJISContextAnalysis::new(), }; x.base.m_coding_sm = Some(CodingStateMachine::new(&SJIS_SM_MODEL)); x.base.m_distribution_analyzer = Some(Box::new(SJISDistributionAnalysis::new())); x } }
"Japanese".to_string() } fn get_state(&self) -> &ProbingState { self.base.get_state()
random_line_split
sjisprober.rs
use std::ops::Deref; use std::ops::DerefMut; use super::enums::MachineState; use super::mbcharsetprober::MultiByteCharsetProber; use super::charsetprober::CharsetProber; use super::enums::ProbingState; use super::codingstatemachine::CodingStateMachine; use super::mbcssm::SJIS_SM_MODEL; use super::chardistribution::SJISDistributionAnalysis; use super::jpcntx::{JapaneseContextAnalysis, SJISContextAnalysis}; pub struct SJISProber<'a> { base: MultiByteCharsetProber<'a>, m_context_analyzer: SJISContextAnalysis, } impl<'x> Deref for SJISProber<'x> { type Target = MultiByteCharsetProber<'x>; fn deref<'a>(&'a self) -> &'a MultiByteCharsetProber<'x> { &self.base } } impl<'x> DerefMut for SJISProber<'x> { fn deref_mut<'a>(&'a mut self) -> &'a mut MultiByteCharsetProber<'x> { &mut self.base } } impl<'a> CharsetProber for SJISProber<'a> { fn reset(&mut self) { self.base.reset(); self.m_context_analyzer.reset(); } fn feed(&mut self, byte_str: &[u8]) -> &ProbingState { { let sm = self.base.m_coding_sm.as_mut().unwrap(); let da = self.base.m_distribution_analyzer.as_mut().unwrap(); for i in 0..byte_str.len() { match sm.next_state(byte_str[i]) { MachineState::START => { let char_len = sm.get_current_charlen(); if i == 0 { self.base.m_last_char[1] = byte_str[0]; self.m_context_analyzer.feed( &self.base.m_last_char[(2 - char_len) as usize..], char_len as usize, ); da.feed(&self.base.m_last_char[..], char_len); } else { self.m_context_analyzer.feed( &byte_str[i + 1 - char_len as usize..], char_len as usize, ); da.feed(&byte_str[i - 1..i + 1], char_len); } } MachineState::ERROR => { self.base.m_state = ProbingState::NotMe; break; } MachineState::ITS_ME => { self.base.m_state = ProbingState::FoundIt; break; } _ => {} } } } self.base.m_last_char[0] = byte_str[byte_str.len() - 1]; if self.base.m_state == ProbingState::Detecting { if (self.m_context_analyzer.got_enough_data()) && (self.get_confidence() > 0.95) { self.base.m_state = ProbingState::FoundIt; } } &self.base.m_state } fn get_charset(&self) -> String { self.m_context_analyzer.get_charset() } fn get_confidence(&self) -> f32 { let a = self.base.get_confidence(); let b = self.m_context_analyzer.get_confidence(); if a>b { a } else { b } } fn get_language(&self) -> String { "Japanese".to_string() } fn get_state(&self) -> &ProbingState
} impl<'a> SJISProber<'a> { pub fn new() -> SJISProber<'a> { let mut x = SJISProber { base: MultiByteCharsetProber::new(), m_context_analyzer: SJISContextAnalysis::new(), }; x.base.m_coding_sm = Some(CodingStateMachine::new(&SJIS_SM_MODEL)); x.base.m_distribution_analyzer = Some(Box::new(SJISDistributionAnalysis::new())); x } }
{ self.base.get_state() }
identifier_body
sjisprober.rs
use std::ops::Deref; use std::ops::DerefMut; use super::enums::MachineState; use super::mbcharsetprober::MultiByteCharsetProber; use super::charsetprober::CharsetProber; use super::enums::ProbingState; use super::codingstatemachine::CodingStateMachine; use super::mbcssm::SJIS_SM_MODEL; use super::chardistribution::SJISDistributionAnalysis; use super::jpcntx::{JapaneseContextAnalysis, SJISContextAnalysis}; pub struct SJISProber<'a> { base: MultiByteCharsetProber<'a>, m_context_analyzer: SJISContextAnalysis, } impl<'x> Deref for SJISProber<'x> { type Target = MultiByteCharsetProber<'x>; fn deref<'a>(&'a self) -> &'a MultiByteCharsetProber<'x> { &self.base } } impl<'x> DerefMut for SJISProber<'x> { fn
<'a>(&'a mut self) -> &'a mut MultiByteCharsetProber<'x> { &mut self.base } } impl<'a> CharsetProber for SJISProber<'a> { fn reset(&mut self) { self.base.reset(); self.m_context_analyzer.reset(); } fn feed(&mut self, byte_str: &[u8]) -> &ProbingState { { let sm = self.base.m_coding_sm.as_mut().unwrap(); let da = self.base.m_distribution_analyzer.as_mut().unwrap(); for i in 0..byte_str.len() { match sm.next_state(byte_str[i]) { MachineState::START => { let char_len = sm.get_current_charlen(); if i == 0 { self.base.m_last_char[1] = byte_str[0]; self.m_context_analyzer.feed( &self.base.m_last_char[(2 - char_len) as usize..], char_len as usize, ); da.feed(&self.base.m_last_char[..], char_len); } else { self.m_context_analyzer.feed( &byte_str[i + 1 - char_len as usize..], char_len as usize, ); da.feed(&byte_str[i - 1..i + 1], char_len); } } MachineState::ERROR => { self.base.m_state = ProbingState::NotMe; break; } MachineState::ITS_ME => { self.base.m_state = ProbingState::FoundIt; break; } _ => {} } } } self.base.m_last_char[0] = byte_str[byte_str.len() - 1]; if self.base.m_state == ProbingState::Detecting { if (self.m_context_analyzer.got_enough_data()) && (self.get_confidence() > 0.95) { self.base.m_state = ProbingState::FoundIt; } } &self.base.m_state } fn get_charset(&self) -> String { self.m_context_analyzer.get_charset() } fn get_confidence(&self) -> f32 { let a = self.base.get_confidence(); let b = self.m_context_analyzer.get_confidence(); if a>b { a } else { b } } fn get_language(&self) -> String { "Japanese".to_string() } fn get_state(&self) -> &ProbingState { self.base.get_state() } } impl<'a> SJISProber<'a> { pub fn new() -> SJISProber<'a> { let mut x = SJISProber { base: MultiByteCharsetProber::new(), m_context_analyzer: SJISContextAnalysis::new(), }; x.base.m_coding_sm = Some(CodingStateMachine::new(&SJIS_SM_MODEL)); x.base.m_distribution_analyzer = Some(Box::new(SJISDistributionAnalysis::new())); x } }
deref_mut
identifier_name
lib.rs
//! natural_constants: a collection of constants and helper functions //! //! Written by Willi Kappler, Version 0.1 (2017.02.20) //! //! Repository: https://github.com/willi-kappler/natural_constants //! //! License: MIT //! //! //! # Example: //! //! ``` //! extern crate natural_constants;
//! //! fn main() { //! let c = speed_of_light_vac; //! let m0 = 100.0; //! //! // Use c in your code: //! let E = m0 * c * c; //! } //! ``` // For clippy // #![feature(plugin)] // // #![plugin(clippy)] #![allow(non_upper_case_globals)] #![allow(dead_code)] pub mod math; pub mod physics; pub mod chemistry; pub mod biology; pub mod engineering; pub mod conversion; pub mod misc; pub mod geosciences;
//! use natural_constants::physics::*; //!
random_line_split