text
stringlengths
8
4.13M
//! Reading `.hltas` files. use std::{ fmt::{self, Display, Formatter}, num::NonZeroU32, str::FromStr, }; use nom::{ self, bytes::complete::tag, character::complete::{digit0, line_ending, multispace0, one_of, space1}, combinator::{all_consuming, map_res, opt, recognize, verify}, error::{FromExternalError, ParseError}, multi::{many1, separated_list0}, sequence::{delimited, pair, preceded}, Offset, }; use crate::types::{Line, HLTAS}; mod line; pub use line::{frame_bulk, line}; pub(crate) mod properties; use properties::properties; #[derive(Debug, Clone, Copy, Eq, PartialEq)] enum ErrorKind { ExpectedChar(char), Other(nom::error::ErrorKind), } /// Enumeration of possible semantic errors. #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum Context { /// Failed to read the version. ErrorReadingVersion, /// The version is too high. VersionTooHigh, /// Both autojump and ducktap are enabled at once. BothAutoJumpAndDuckTap, /// LGAGST is enabled without autojump or ducktap. NoLeaveGroundAction, /// Times is specified on the LGAGST action. TimesOnLeaveGroundAction, /// Save name is not specified. NoSaveName, /// Seed is not specified. NoSeed, /// Yaw is required but not specified. NoYaw, /// Buttons are not specified. NoButtons, /// The LGAGST min speed valueis not specified. NoLGAGSTMinSpeed, /// The reset seed is not specified. NoResetSeed, /// Failed to parse a frames entry. ErrorParsingLine, /// Invalid strafing algorithm. InvalidStrafingAlgorithm, /// Vectorial strafing constraints are not specified. NoConstraints, /// The +- in the vectorial strafing constraints is missing. NoPlusMinusBeforeTolerance, /// The parameters in the yaw range vectorial strafing constraints are not specified. NoFromToParameters, /// The yaw range vectorial strafing constraint is missing the "to" word. NoTo, /// Yawspeed is required for constant yawspeed but not specified. NoYawspeed, /// Only side strafe works with constant yawspeed now. UnsupportedConstantYawspeedDir, /// Negative yawspeed value. NegativeYawspeed, } /// `.hltas` parsing error. #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub struct Error<'a> { /// Remaining input at the point of failure. pub input: &'a str, pub(crate) whole_input: &'a str, kind: ErrorKind, /// Semantic meaning of the parsing error. pub context: Option<Context>, } type IResult<'a, T> = Result<(&'a str, T), nom::Err<Error<'a>>>; impl Error<'_> { fn add_context(&mut self, context: Context) { if self.context.is_some() { return; } self.context = Some(context); } } impl Display for Context { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { use Context::*; match self { ErrorReadingVersion => write!(f, "failed to read version"), VersionTooHigh => write!(f, "this version is not supported"), BothAutoJumpAndDuckTap => write!( f, "both autojump and ducktap are specified at the same time" ), NoLeaveGroundAction => write!( f, "no LGAGST action specified (either autojump or ducktap is required)" ), TimesOnLeaveGroundAction => write!( f, "times on autojump or ducktap with LGAGST enabled (put times on LGAGST instead)" ), NoSaveName => write!(f, "missing save name"), NoSeed => write!(f, "missing seed value"), NoButtons => write!(f, "missing button values"), NoLGAGSTMinSpeed => write!(f, "missing lgagstminspeed value"), NoResetSeed => write!(f, "missing reset seed"), NoYaw => write!(f, "missing yaw value"), ErrorParsingLine => write!(f, "failed to parse the line"), InvalidStrafingAlgorithm => write!( f, "invalid strafing algorithm (only \"yaw\" and \"vectorial\" allowed)" ), NoConstraints => write!(f, "missing constraints"), NoPlusMinusBeforeTolerance => write!(f, "missing +- before tolerance"), NoFromToParameters => write!(f, "missing from/to parameters"), NoTo => write!(f, "missing \"to\" in the from/to constraint"), NoYawspeed => write!(f, "missing yawspeed value"), UnsupportedConstantYawspeedDir => { write!(f, "cannot pair constant yawspeed with current strafe dir") } NegativeYawspeed => { write!(f, "yawspeed value is negative") } } } } impl Display for Error<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let mut line = 0; let mut column = 0; let mut offset = self.whole_input.offset(self.input); let mut just_error_line = None; for (j, l) in self.whole_input.lines().enumerate() { if offset <= l.len() { line = j; column = offset; just_error_line = Some(l); break; } else { offset = offset - l.len() - 1; } } if let Some(context) = self.context { context.fmt(f)?; } else { match self.kind { ErrorKind::ExpectedChar(c) => { if let Some(next_char) = self.input.chars().next() { write!(f, "expected '{}', got '{}'", c, next_char)?; } else { write!(f, "expected '{}', got EOF", c)?; } } ErrorKind::Other(nom_kind) => { write!(f, "error applying {}", nom_kind.description())? } } } // Can happen if whole_input is some unrelated &str. if just_error_line.is_none() { return Ok(()); } let just_error_line = just_error_line.unwrap(); let line_number = format!("{} | ", line); write!(f, "\n{}{}\n", line_number, just_error_line)?; write!(f, "{:1$}^", ' ', line_number.len() + column)?; if let ErrorKind::ExpectedChar(c) = self.kind { write!(f, " expected '{}'", c)?; } Ok(()) } } impl std::error::Error for Error<'_> {} impl<'a> ParseError<&'a str> for Error<'a> { fn from_error_kind(input: &'a str, kind: nom::error::ErrorKind) -> Self { Self { input, whole_input: input, kind: ErrorKind::Other(kind), context: None, } } fn append(_input: &'a str, _kind: nom::error::ErrorKind, other: Self) -> Self { other } fn from_char(input: &'a str, c: char) -> Self { Self { input, whole_input: input, kind: ErrorKind::ExpectedChar(c), context: None, } } } impl<'a, E> FromExternalError<&'a str, E> for Error<'a> { fn from_external_error(input: &'a str, kind: nom::error::ErrorKind, _e: E) -> Self { Self::from_error_kind(input, kind) } } impl Error<'_> { /// Returns the line number on which the error has occurred. pub fn line(&self) -> usize { let mut line = 0; let mut offset = self.whole_input.offset(self.input); for (j, l) in self.whole_input.lines().enumerate() { if offset <= l.len() { line = j; break; } else { offset = offset - l.len() - 1; } } line } } /// Adds context to the potential parser error. /// /// If the error already has context stored, does nothing. fn context<'a, T>( context: Context, mut f: impl FnMut(&'a str) -> IResult<'a, T>, ) -> impl FnMut(&'a str) -> IResult<T> { move |i: &str| { f(i).map_err(move |error| match error { nom::Err::Incomplete(needed) => nom::Err::Incomplete(needed), nom::Err::Error(mut e) => { e.add_context(context); nom::Err::Error(e) } nom::Err::Failure(mut e) => { e.add_context(context); nom::Err::Failure(e) } }) } } fn non_zero_u32(i: &str) -> IResult<NonZeroU32> { map_res( recognize(pair(one_of("123456789"), digit0)), NonZeroU32::from_str, )(i) } fn version(i: &str) -> IResult<()> { // This is a little involved to report the correct HLTAS error. // When we can't parse the version as a number at all, we should report ErrorReadingVersion. // When we can parse it as a number and it's above 1, we should report VersionTooHigh. let version_number = context( Context::VersionTooHigh, verify( context(Context::ErrorReadingVersion, one_of("123456789")), |&c| c == '1', ), ); let (i, _) = preceded(tag("version"), preceded(space1, version_number))(i)?; Ok((i, ())) } /// Parses a line ending character, followed by any additional whitespace. fn whitespace(i: &str) -> IResult<()> { let (i, _) = preceded(line_ending, multispace0)(i)?; Ok((i, ())) } /// Parses [`Line`]s, ensuring nother is left in the input. /// /// # Examples /// /// ``` /// # extern crate hltas; /// /// let lines = "\ /// ------b---|------|------|0.001|-|-|5 /// ------b---|------|------|0.001|-|-|10 /// "; /// /// assert!(hltas::read::all_consuming_lines(lines).is_ok()); /// /// let lines = "\ /// ------b---|------|------|0.001|-|-|5 /// ------b---|------|------|0.001|-|-|10 /// something extra in the end"; /// /// assert!(hltas::read::all_consuming_lines(lines).is_err()); /// ``` pub fn all_consuming_lines(i: &str) -> IResult<Vec<Line>> { let many_lines = separated_list0(whitespace, line); all_consuming(delimited(opt(multispace0), many_lines, opt(multispace0)))(i) } /// Parses an entire HLTAS script, ensuring nothing is left in the input. /// /// This is a lower-level function. You might be looking for [`HLTAS::from_str`] instead. /// /// # Examples /// /// ``` /// # extern crate hltas; /// /// let contents = "\ /// version 1 /// demo test /// frames /// ------b---|------|------|0.001|-|-|5"; /// /// assert!(hltas::read::hltas(contents).is_ok()); /// /// let contents = "\ /// version 1 /// demo test /// frames /// ------b---|------|------|0.001|-|-|5 /// something extra in the end"; /// /// assert!(hltas::read::hltas(contents).is_err()); /// ``` pub fn hltas(i: &str) -> IResult<HLTAS> { let (i, _) = context(Context::ErrorReadingVersion, version)(i)?; let (i, properties) = properties(i)?; let (i, _) = preceded(many1(line_ending), tag("frames"))(i)?; let (i, lines) = context( Context::ErrorParsingLine, preceded(whitespace, all_consuming_lines), )(i)?; Ok((i, HLTAS { properties, lines })) } #[cfg(test)] mod tests { use super::*; #[test] fn version_0() { let input = "version 0"; let err = version(input).unwrap_err(); if let nom::Err::Error(err) = err { assert_eq!(err.context, Some(Context::ErrorReadingVersion)); } else { unreachable!() } } #[test] fn version_too_high() { let input = "version 9"; let err = version(input).unwrap_err(); if let nom::Err::Error(err) = err { assert_eq!(err.context, Some(Context::VersionTooHigh)); } else { unreachable!() } } #[test] fn no_newline_after_frames() { let input = "version 1\nframesbuttons"; assert!(hltas(input).is_err()); } #[test] fn no_newline_after_frames_only_space() { let input = "version 1\nframes buttons"; assert!(hltas(input).is_err()); } }
mod item; mod repository; pub use item::*; pub use repository::*; use common::error::Error; use common::model::{AggregateRoot, StringId}; use common::result::Result; use shared::event::CollectionEvent; use crate::domain::author::AuthorId; use crate::domain::publication::{Header, Publication, PublicationId}; pub type CollectionId = StringId; #[derive(Debug, Clone)] pub struct Collection { base: AggregateRoot<CollectionId, CollectionEvent>, author_id: AuthorId, header: Header, items: Vec<Item>, } impl Collection { pub fn new(id: CollectionId, author_id: AuthorId, header: Header) -> Result<Self> { let mut collection = Collection { base: AggregateRoot::new(id), author_id, header, items: Vec::new(), }; collection.base.record_event(CollectionEvent::Created { id: collection.base().id().to_string(), author_id: collection.author_id().to_string(), name: collection.header().name().to_string(), synopsis: collection.header().synopsis().to_string(), category_id: collection.header().category_id().to_string(), tags: collection .header() .tags() .iter() .map(|t| t.name().to_string()) .collect(), cover: collection.header().cover().url().to_string(), }); Ok(collection) } pub fn base(&self) -> &AggregateRoot<CollectionId, CollectionEvent> { &self.base } pub fn author_id(&self) -> &AuthorId { &self.author_id } pub fn header(&self) -> &Header { &self.header } pub fn items(&self) -> &[Item] { &self.items } pub fn set_header(&mut self, header: Header) -> Result<()> { self.header = header; self.base.record_event(CollectionEvent::HeaderUpdated { id: self.base().id().to_string(), name: self.header().name().to_string(), synopsis: self.header().synopsis().to_string(), category_id: self.header().category_id().to_string(), tags: self .header() .tags() .iter() .map(|t| t.name().to_string()) .collect(), cover: self.header().cover().url().to_string(), }); Ok(()) } pub fn add_item(&mut self, publication: &Publication) -> Result<()> { if !publication.is_published() { return Err(Error::new("collection", "publication_is_not_published")); } let item = Item::new(publication.base().id().clone())?; self.items.push(item); self.base.record_event(CollectionEvent::PublicationAdded { id: self.base().id().to_string(), publication_id: publication.base().id().to_string(), }); Ok(()) } pub fn remove_item(&mut self, publication_id: &PublicationId) -> Result<()> { self.items .retain(|item| item.publication_id() != publication_id); self.base.record_event(CollectionEvent::PublicationRemoved { id: self.base().id().to_string(), publication_id: publication_id.to_string(), }); Ok(()) } pub fn delete(&mut self) -> Result<()> { self.base.delete(); self.base.record_event(CollectionEvent::Deleted { id: self.base().id().to_string(), }); Ok(()) } }
pub(crate) mod network_manager;
extern crate oxygengine_core as core; pub mod device; pub mod resource; pub mod system; pub mod prelude { pub use crate::{device::*, resource::*, system::*}; } use crate::{ resource::InputController, system::{input_system, InputSystemResources}, }; use core::{ app::AppBuilder, ecs::pipeline::{PipelineBuilder, PipelineBuilderError}, }; pub fn bundle_installer<PB, ICS>( builder: &mut AppBuilder<PB>, mut input_controller_setup: ICS, ) -> Result<(), PipelineBuilderError> where PB: PipelineBuilder, ICS: FnMut(&mut InputController), { let mut input = InputController::default(); input_controller_setup(&mut input); builder.install_resource(input); builder.install_system::<InputSystemResources>("input", input_system, &[])?; Ok(()) }
use hacspec_dev::prelude::*; use hacspec_lib::prelude::*; use unsafe_hacspec_examples::aes_gcm::*; struct AeadTestVector<'a> { key: &'a str, nonce: &'a str, msg: &'a str, aad: &'a str, exp_cipher: &'a str, exp_mac: &'a str, } const KAT: [AeadTestVector; 4] = [ AeadTestVector { key: "00000000000000000000000000000000", nonce: "000000000000000000000000", msg: "", aad: "", exp_cipher: "", exp_mac: "58e2fccefa7e3061367f1d57a4e7455a" }, AeadTestVector { key : "00000000000000000000000000000000", nonce : "000000000000000000000000", aad : "", msg : "00000000000000000000000000000000", exp_cipher : "0388dace60b6a392f328c2b971b2fe78", exp_mac : "ab6e47d42cec13bdf53a67b21257bddf", }, AeadTestVector { key : "feffe9928665731c6d6a8f9467308308", nonce : "cafebabefacedbaddecaf888", msg : "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255", aad : "", exp_cipher : "42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f5985", exp_mac : "4d5c2af327cd64a62cf35abd2ba6fab4", }, AeadTestVector { key : "feffe9928665731c6d6a8f9467308308", nonce : "cafebabefacedbaddecaf888", msg : "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39", aad : "feedfacedeadbeeffeedfacedeadbeefabaddad2", exp_cipher: "42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091", exp_mac : "5bc94fbc3221a5db94fae95ae7121a47", } ]; const KAT_256: [AeadTestVector; 2] = [ AeadTestVector { key: "E3C08A8F06C6E3AD95A70557B23F75483CE33021A9C72B7025666204C69C0B72", nonce: "12153524C0895E81B2C28465", msg: "", aad: "D609B1F056637A0D46DF998D88E5222AB2C2846512153524C0895E8108000F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F30313233340001", exp_cipher: "", exp_mac: "2F0BC5AF409E06D609EA8B7D0FA5EA50" }, AeadTestVector { key: "E3C08A8F06C6E3AD95A70557B23F75483CE33021A9C72B7025666204C69C0B72", nonce: "12153524C0895E81B2C28465", msg: "08000F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A0002", aad: "D609B1F056637A0D46DF998D88E52E00B2C2846512153524C0895E81", exp_cipher: "E2006EB42F5277022D9B19925BC419D7A592666C925FE2EF718EB4E308EFEAA7C5273B394118860A5BE2A97F56AB7836", exp_mac: "5CA597CDBB3EDB8D1A1151EA0AF7B436" } ]; macro_rules! to_public_vec { ($x:expr) => { $x.iter().map(|x| U8::declassify(*x)).collect::<Vec<_>>() }; } #[test] fn kat_test() { for kat in KAT.iter() { let k = aes::Key128::from_hex(kat.key); let nonce = aes::Nonce::from_hex(kat.nonce); let exp_mac = gf128::Tag::from_hex(kat.exp_mac); let msg = ByteSeq::from_hex(kat.msg); let aad = ByteSeq::from_hex(kat.aad); let exp_cipher = ByteSeq::from_hex(kat.exp_cipher); let (cipher, mac) = encrypt_aes128(k, nonce, &aad, &msg); assert_eq!( exp_cipher .iter() .map(|x| U8::declassify(*x)) .collect::<Vec<_>>(), cipher .iter() .map(|x| U8::declassify(*x)) .collect::<Vec<_>>() ); assert_eq!( exp_mac .iter() .map(|x| U8::declassify(*x)) .collect::<Vec<_>>(), mac.iter().map(|x| U8::declassify(*x)).collect::<Vec<_>>() ); let decrypted_msg = decrypt_aes128(k, nonce, &aad, &cipher, mac).unwrap(); assert_eq!( msg.iter().map(|x| U8::declassify(*x)).collect::<Vec<_>>(), decrypted_msg .iter() .map(|x| U8::declassify(*x)) .collect::<Vec<_>>() ); } } #[test] fn kat_test_256() { for kat in KAT_256.iter() { let k = aes::Key256::from_hex(kat.key); let nonce = aes::Nonce::from_hex(kat.nonce); let exp_mac = gf128::Tag::from_hex(kat.exp_mac); let msg = ByteSeq::from_hex(kat.msg); let aad = ByteSeq::from_hex(kat.aad); let exp_cipher = ByteSeq::from_hex(kat.exp_cipher); let (cipher, mac) = encrypt_aes256(k, nonce, &aad, &msg); assert_eq!( exp_cipher .iter() .map(|x| U8::declassify(*x)) .collect::<Vec<_>>(), cipher .iter() .map(|x| U8::declassify(*x)) .collect::<Vec<_>>() ); assert_eq!( exp_mac .iter() .map(|x| U8::declassify(*x)) .collect::<Vec<_>>(), mac.iter().map(|x| U8::declassify(*x)).collect::<Vec<_>>() ); let decrypted_msg = decrypt_aes256(k, nonce, &aad, &cipher, mac).unwrap(); assert_eq!( msg.iter().map(|x| U8::declassify(*x)).collect::<Vec<_>>(), decrypted_msg .iter() .map(|x| U8::declassify(*x)) .collect::<Vec<_>>() ); } } create_test_vectors!( AesGcmTestVector, algorithm: String, generatorVersion: String, numberOfTests: usize, notes: Option<Value>, // text notes (might not be present), keys correspond to flags header: Vec<Value>, // not used testGroups: Vec<TestGroup> ); create_test_vectors!( TestGroup, ivSize: usize, keySize: usize, tagSize: usize, r#type: String, tests: Vec<Test> ); create_test_vectors!( Test, tcId: usize, comment: String, key: String, iv: String, aad: String, msg: String, ct: String, tag: String, result: String, flags: Vec<String> ); #[allow(non_snake_case)] #[test] fn test_wycheproof() { let tests: AesGcmTestVector = AesGcmTestVector::from_file("tests/aes_gcm_test_wycheproof.json"); let num_tests = tests.numberOfTests; let mut skipped_tests = 0; let mut tests_run = 0; match tests.algorithm.as_ref() { "AES-GCM" => (), _ => panic!("This is not an AES-GCM test vector."), }; for testGroup in tests.testGroups.iter() { assert_eq!(testGroup.r#type, "AeadTest"); let algorithm = match testGroup.keySize { 128 => aes::AesVariant::Aes128, 256 => aes::AesVariant::Aes256, _ => { // not implemented println!("Only AES 128 and 256 are implemented."); skipped_tests += testGroup.tests.len(); continue; } }; if testGroup.ivSize != 96 { // not implemented println!("Nonce sizes != 96 are not supported for AES GCM."); skipped_tests += testGroup.tests.len(); continue; } for test in testGroup.tests.iter() { let valid = test.result.eq("valid"); if test.comment == "invalid nonce size" { // not implemented println!("Invalid nonce sizes are not supported."); skipped_tests += 1; break; } println!("Test {:?}: {:?}", test.tcId, test.comment); let nonce = aes::Nonce::from_hex(&test.iv); let msg = ByteSeq::from_hex(&test.msg); let aad = ByteSeq::from_hex(&test.aad); let exp_cipher = ByteSeq::from_hex(&test.ct); let exp_tag = gf128::Tag::from_hex(&test.tag); let (cipher, tag) = match algorithm { aes::AesVariant::Aes128 => { // let r = test_ring_aead(&key, &iv, &aad, &m, algorithm); let k = aes::Key128::from_hex(&test.key); encrypt_aes128(k, nonce, &aad, &msg) } aes::AesVariant::Aes256 => { let k = aes::Key256::from_hex(&test.key); encrypt_aes256(k, nonce, &aad, &msg) } }; if valid { assert_eq!(to_public_vec!(tag), to_public_vec!(exp_tag)); } else { assert_ne!(to_public_vec!(tag), to_public_vec!(exp_tag)); } assert_eq!(to_public_vec!(cipher), to_public_vec!(exp_cipher)); tests_run += 1; } } // Check that we ran all tests. println!( "Ran {} out of {} tests and skipped {}.", tests_run, num_tests, skipped_tests ); assert_eq!(num_tests - skipped_tests, tests_run); } #[allow(non_snake_case)] #[test] fn generate_test_vectors() { const NUM_TESTS_EACH: usize = 100; let mut tests_128 = Vec::new(); let mut tests_256 = Vec::new(); for i in 0..NUM_TESTS_EACH { let msg_l = 123 + i; let aad_l = 13 + i; // Generate random key, nonce, message, and aad for AES 256. let k = aes::Key256::from_public_slice(&random_byte_vec(aes::Key256::length())); let nonce = aes::Nonce::from_public_slice(&random_byte_vec(aes::Nonce::length())); let msg = ByteSeq::from_public_slice(&random_byte_vec(msg_l)); let aad = ByteSeq::from_public_slice(&random_byte_vec(aad_l)); // Generate random key, nonce, message, and aad for AES 128. let k128 = aes::Key128::from_public_slice(&random_byte_vec(aes::Key128::length())); let nonce128 = aes::Nonce::from_public_slice(&random_byte_vec(aes::Nonce::length())); let msg128 = ByteSeq::from_public_slice(&random_byte_vec(msg_l)); let aad128 = ByteSeq::from_public_slice(&random_byte_vec(aad_l)); // Generate ciphertext and mac let (cipher, mac) = encrypt_aes256(k, nonce, &aad, &msg); let (cipher128, mac128) = encrypt_aes128(k128, nonce128, &aad128, &msg128); // self-test let decrypted_msg = decrypt_aes256(k, nonce, &aad, &cipher, mac).unwrap(); assert_eq!( msg.iter().map(|x| U8::declassify(*x)).collect::<Vec<_>>(), decrypted_msg .iter() .map(|x| U8::declassify(*x)) .collect::<Vec<_>>() ); let decrypted_msg128 = decrypt_aes128(k128, nonce128, &aad128, &cipher128, mac128).unwrap(); assert_eq!( msg128 .iter() .map(|x| U8::declassify(*x)) .collect::<Vec<_>>(), decrypted_msg128 .iter() .map(|x| U8::declassify(*x)) .collect::<Vec<_>>() ); // Store result. tests_256.push(Test { tcId: i, comment: String::default(), key: k.to_hex(), iv: nonce.to_hex(), aad: aad.to_hex(), msg: msg.to_hex(), ct: cipher.to_hex(), tag: mac.to_hex(), result: "valid".to_string(), flags: vec![], }); tests_128.push(Test { tcId: i + NUM_TESTS_EACH, comment: String::default(), key: k128.to_hex(), iv: nonce128.to_hex(), aad: aad128.to_hex(), msg: msg128.to_hex(), ct: cipher128.to_hex(), tag: mac128.to_hex(), result: "valid".to_string(), flags: vec![], }); } let test_group_256 = TestGroup { ivSize: aes::Nonce::length(), keySize: aes::Key256::length(), tagSize: gf128::Tag::length(), r#type: "AeadTest".to_string(), tests: tests_256, }; let test_group_128 = TestGroup { ivSize: aes::Nonce::length(), keySize: aes::Key128::length(), tagSize: gf128::Tag::length(), r#type: "AeadTest".to_string(), tests: tests_128, }; let test_vector = AesGcmTestVector { algorithm: "AES-GCM".to_string(), generatorVersion: "0.0.1".to_string(), numberOfTests: 1, notes: None, header: vec![], testGroups: vec![test_group_128, test_group_256], }; // Write out test vectors. test_vector.write_file("tests/aes_gcm_test_vector_out.json"); }
mod header; mod packet; mod parser; mod reader; mod writer; pub use header::*; pub use packet::*; pub use parser::*; pub use reader::*; pub use writer::*;
use std::collections::HashMap; fn get_new_freq(freq: i32, line: &str) -> i32 { let mut chars = line.chars(); let operation = chars.next(); let delta_str: String = chars.collect(); let delta: i32 = delta_str.parse().unwrap(); if operation == Some('+') { freq + delta } else { freq - delta } } fn part1(lines: &Vec<&str>) -> i32 { let mut freq: i32 = 0; for line in lines { freq = get_new_freq(freq, line); } freq } fn part2(lines: &Vec<&str>) -> i32 { let mut freq: i32 = 0; let mut freqs = HashMap::new(); let mut i = 0; loop { let count = freqs.entry(freq).or_insert(0); *count += 1; if *count >= 2 { return freq; } i %= lines.len(); freq = get_new_freq(freq, &lines[i]); i += 1; } } pub fn main() { let filename = "src/day1/input"; let contents = std::fs::read_to_string(filename).expect("Something went wrong reading the file"); let lines: Vec<&str> = contents.lines().collect(); print!("part1: {}\n", part1(&lines)); print!("part2: {}", part2(&lines)); }
// Copyright 2020 lencx // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. use std::{thread::sleep, time::Duration}; enum UpdateResult { None, QuitApplication, } struct App { client: Box<dyn Client>, state: AppState, } struct AppState { title: String, } trait Client { // returns false if the app should exit fn update(&mut self) -> UpdateResult; fn render(&self); } struct MyClient { ticks_left: usize, } impl Client for MyClient { fn update(&mut self) -> UpdateResult { self.ticks_left -= 1; if self.ticks_left > 0 { UpdateResult::None } else { UpdateResult::QuitApplication } } fn render(&self) { if self.ticks_left > 0 { println!("You turn the crank..."); } else { println!("Jack POPS OUT OF THE BOX"); } } } impl App { fn run(&mut self) { println!("=== Your are now playing {} === ", self.state.title); loop { let result = self.client.update(); self.client.render(); match result { UpdateResult::None => {}, UpdateResult::QuitApplication => break, } sleep(Duration::from_secs(1)) } } } fn main() { let client = MyClient { ticks_left: 4 }; let mut app = App { state: AppState { title: String::from("Jack in the box"), }, client: Box::new(client), }; app.run(); }
use crate::{ gui::{BuildContext, Ui, UiMessage, UiNode}, scene::commands::{ particle_system::{ EmitterNumericParameter, SetEmitterNumericParameterCommand, SetEmitterPositionCommand, SetEmitterResurrectParticlesCommand, }, SceneCommand, }, send_sync_message, sidebar::{ make_bool_input_field, make_f32_input_field, make_section, make_text_mark, make_vec3_input_field, particle::{cuboid::BoxSection, cylinder::CylinderSection, sphere::SphereSection}, COLUMN_WIDTH, ROW_HEIGHT, }, Message, }; use rg3d::{ core::pool::Handle, gui::{ grid::{Column, GridBuilder, Row}, message::{ CheckBoxMessage, MessageDirection, NumericUpDownMessage, UiMessageData, Vec3EditorMessage, WidgetMessage, }, numeric::NumericUpDownBuilder, stack_panel::StackPanelBuilder, widget::WidgetBuilder, Thickness, }, scene::{ node::Node, particle_system::{emitter::Emitter, ParticleLimit}, }, }; use std::sync::mpsc::Sender; pub struct EmitterSection { pub section: Handle<UiNode>, position: Handle<UiNode>, spawn_rate: Handle<UiNode>, max_particles: Handle<UiNode>, min_lifetime: Handle<UiNode>, max_lifetime: Handle<UiNode>, min_size_modifier: Handle<UiNode>, max_size_modifier: Handle<UiNode>, min_x_velocity: Handle<UiNode>, max_x_velocity: Handle<UiNode>, min_y_velocity: Handle<UiNode>, max_y_velocity: Handle<UiNode>, min_z_velocity: Handle<UiNode>, max_z_velocity: Handle<UiNode>, min_rotation_speed: Handle<UiNode>, max_rotation_speed: Handle<UiNode>, min_rotation: Handle<UiNode>, max_rotation: Handle<UiNode>, resurrect_particles: Handle<UiNode>, sender: Sender<Message>, sphere_section: SphereSection, cylinder_section: CylinderSection, box_section: BoxSection, } fn make_range_field(ctx: &mut BuildContext, column: usize) -> Handle<UiNode> { NumericUpDownBuilder::new( WidgetBuilder::new() .on_column(column) .with_margin(Thickness::uniform(1.0)), ) .build(ctx) } fn make_range( ctx: &mut BuildContext, row: usize, ) -> (Handle<UiNode>, Handle<UiNode>, Handle<UiNode>) { let min; let max; let grid = GridBuilder::new( WidgetBuilder::new() .on_row(row) .on_column(1) .with_child({ min = make_range_field(ctx, 0); min }) .with_child({ max = make_range_field(ctx, 1); max }), ) .add_column(Column::stretch()) .add_column(Column::stretch()) .add_row(Row::stretch()) .build(ctx); (grid, min, max) } impl EmitterSection { pub fn new(ctx: &mut BuildContext, sender: Sender<Message>) -> Self { let sphere_section = SphereSection::new(ctx, sender.clone()); let cylinder_section = CylinderSection::new(ctx, sender.clone()); let box_section = BoxSection::new(ctx, sender.clone()); let position; let spawn_rate; let max_particles; let min_lifetime; let max_lifetime; let min_size_modifier; let max_size_modifier; let min_x_velocity; let max_x_velocity; let min_y_velocity; let max_y_velocity; let min_z_velocity; let max_z_velocity; let min_rotation_speed; let max_rotation_speed; let min_rotation; let max_rotation; let resurrect_particles; let common_properties = GridBuilder::new( WidgetBuilder::new() .with_child(make_text_mark(ctx, "Position", 0)) .with_child({ position = make_vec3_input_field(ctx, 0); position }) .with_child(make_text_mark(ctx, "Spawn Rate", 1)) .with_child({ spawn_rate = make_f32_input_field(ctx, 1, 0.0, std::f32::MAX, 1.0); spawn_rate }) .with_child(make_text_mark(ctx, "Max Particles", 2)) .with_child({ max_particles = make_f32_input_field(ctx, 2, 0.0, std::f32::MAX, 1.0); max_particles }) .with_child(make_text_mark(ctx, "Lifetime Range", 3)) .with_child({ let (grid, min, max) = make_range(ctx, 3); min_lifetime = min; max_lifetime = max; grid }) .with_child(make_text_mark(ctx, "Size Modifier Range", 4)) .with_child({ let (grid, min, max) = make_range(ctx, 4); min_size_modifier = min; max_size_modifier = max; grid }) .with_child(make_text_mark(ctx, "X Velocity Range", 5)) .with_child({ let (grid, min, max) = make_range(ctx, 5); min_x_velocity = min; max_x_velocity = max; grid }) .with_child(make_text_mark(ctx, "Y Velocity Range", 6)) .with_child({ let (grid, min, max) = make_range(ctx, 6); min_y_velocity = min; max_y_velocity = max; grid }) .with_child(make_text_mark(ctx, "Z Velocity Range", 7)) .with_child({ let (grid, min, max) = make_range(ctx, 7); min_z_velocity = min; max_z_velocity = max; grid }) .with_child(make_text_mark(ctx, "Rotation Speed Range", 8)) .with_child({ let (grid, min, max) = make_range(ctx, 8); min_rotation_speed = min; max_rotation_speed = max; grid }) .with_child(make_text_mark(ctx, "Rotation Range", 9)) .with_child({ let (grid, min, max) = make_range(ctx, 9); min_rotation = min; max_rotation = max; grid }) .with_child(make_text_mark(ctx, "Resurrect Particles", 10)) .with_child({ resurrect_particles = make_bool_input_field(ctx, 10); resurrect_particles }), ) .add_row(Row::strict(ROW_HEIGHT)) .add_row(Row::strict(ROW_HEIGHT)) .add_row(Row::strict(ROW_HEIGHT)) .add_row(Row::strict(ROW_HEIGHT)) .add_row(Row::strict(ROW_HEIGHT)) .add_row(Row::strict(ROW_HEIGHT)) .add_row(Row::strict(ROW_HEIGHT)) .add_row(Row::strict(ROW_HEIGHT)) .add_row(Row::strict(ROW_HEIGHT)) .add_row(Row::strict(ROW_HEIGHT)) .add_row(Row::strict(ROW_HEIGHT)) .add_column(Column::strict(COLUMN_WIDTH)) .add_column(Column::stretch()) .build(ctx); let section = make_section( "Emitter Properties", StackPanelBuilder::new( WidgetBuilder::new() .with_child(common_properties) .with_child(sphere_section.section) .with_child(cylinder_section.section) .with_child(box_section.section), ) .build(ctx), ctx, ); Self { section, sender, position, spawn_rate, max_particles, min_lifetime, max_lifetime, min_size_modifier, max_size_modifier, min_x_velocity, max_x_velocity, min_y_velocity, max_y_velocity, min_z_velocity, max_z_velocity, min_rotation_speed, max_rotation_speed, min_rotation, max_rotation, resurrect_particles, sphere_section, cylinder_section, box_section, } } pub fn sync_to_model(&mut self, emitter: &Emitter, ui: &mut Ui) { send_sync_message( ui, Vec3EditorMessage::value( self.position, MessageDirection::ToWidget, emitter.position(), ), ); let sync_f32 = |destination: Handle<UiNode>, value: f32| { send_sync_message( ui, NumericUpDownMessage::value(destination, MessageDirection::ToWidget, value), ); }; sync_f32( self.max_particles, match emitter.max_particles() { ParticleLimit::Unlimited => -1.0, ParticleLimit::Strict(value) => value as f32, }, ); sync_f32(self.spawn_rate, emitter.spawn_rate() as f32); sync_f32(self.min_lifetime, emitter.life_time_range().bounds[0]); sync_f32(self.max_lifetime, emitter.life_time_range().bounds[1]); sync_f32( self.min_size_modifier, emitter.size_modifier_range().bounds[0], ); sync_f32( self.max_size_modifier, emitter.size_modifier_range().bounds[1], ); sync_f32(self.min_x_velocity, emitter.x_velocity_range().bounds[0]); sync_f32(self.max_x_velocity, emitter.x_velocity_range().bounds[1]); sync_f32(self.min_y_velocity, emitter.y_velocity_range().bounds[0]); sync_f32(self.max_y_velocity, emitter.y_velocity_range().bounds[1]); sync_f32(self.min_z_velocity, emitter.z_velocity_range().bounds[0]); sync_f32(self.max_z_velocity, emitter.z_velocity_range().bounds[1]); sync_f32( self.min_rotation_speed, emitter.rotation_speed_range().bounds[0], ); sync_f32( self.max_rotation_speed, emitter.rotation_speed_range().bounds[1], ); sync_f32(self.min_rotation, emitter.rotation_range().bounds[0]); sync_f32(self.max_rotation, emitter.rotation_range().bounds[1]); send_sync_message( ui, CheckBoxMessage::checked( self.resurrect_particles, MessageDirection::ToWidget, Some(emitter.is_particles_resurrects()), ), ); fn toggle_visibility(ui: &mut Ui, destination: Handle<UiNode>, value: bool) { send_sync_message( ui, WidgetMessage::visibility(destination, MessageDirection::ToWidget, value), ); } toggle_visibility(ui, self.sphere_section.section, false); toggle_visibility(ui, self.cylinder_section.section, false); toggle_visibility(ui, self.box_section.section, false); match emitter { Emitter::Unknown => unreachable!(), Emitter::Cuboid(box_emitter) => { toggle_visibility(ui, self.box_section.section, true); self.box_section.sync_to_model(box_emitter, ui); } Emitter::Sphere(sphere) => { toggle_visibility(ui, self.sphere_section.section, true); self.sphere_section.sync_to_model(sphere, ui); } Emitter::Cylinder(cylinder) => { toggle_visibility(ui, self.cylinder_section.section, true); self.cylinder_section.sync_to_model(cylinder, ui); } } } pub fn handle_message( &mut self, message: &UiMessage, emitter: &Emitter, emitter_index: usize, handle: Handle<Node>, ) { match emitter { Emitter::Unknown => unreachable!(), Emitter::Cuboid(box_emitter) => { self.box_section .handle_message(message, box_emitter, handle, emitter_index); } Emitter::Sphere(sphere) => { self.sphere_section .handle_message(message, sphere, handle, emitter_index); } Emitter::Cylinder(cylinder) => { self.cylinder_section .handle_message(message, cylinder, handle, emitter_index); } } match message.data() { &UiMessageData::NumericUpDown(NumericUpDownMessage::Value(value)) => { let mut parameter = None; let mut final_value = value; if message.destination() == self.max_particles { let max_particles = match emitter.max_particles() { ParticleLimit::Unlimited => -1.0, ParticleLimit::Strict(value) => value as f32, }; if max_particles.ne(&value) { parameter = Some(EmitterNumericParameter::MaxParticles); } } else if message.destination() == self.spawn_rate && (emitter.spawn_rate() as f32).ne(&value) { parameter = Some(EmitterNumericParameter::SpawnRate); } else if message.destination() == self.min_lifetime && emitter.life_time_range().bounds[0].ne(&value) { parameter = Some(EmitterNumericParameter::MinLifetime); emitter.life_time_range().clamp_value(&mut final_value); } else if message.destination() == self.max_lifetime && emitter.life_time_range().bounds[1].ne(&value) { parameter = Some(EmitterNumericParameter::MaxLifetime); emitter.life_time_range().clamp_value(&mut final_value); } else if message.destination() == self.min_size_modifier && emitter.size_modifier_range().bounds[0].ne(&value) { parameter = Some(EmitterNumericParameter::MinSizeModifier); emitter.size_modifier_range().clamp_value(&mut final_value); } else if message.destination() == self.max_size_modifier && emitter.size_modifier_range().bounds[1].ne(&value) { parameter = Some(EmitterNumericParameter::MaxSizeModifier); emitter.size_modifier_range().clamp_value(&mut final_value); } else if message.destination() == self.min_x_velocity && emitter.x_velocity_range().bounds[0].ne(&value) { parameter = Some(EmitterNumericParameter::MinXVelocity); emitter.x_velocity_range().clamp_value(&mut final_value); } else if message.destination() == self.max_x_velocity && emitter.x_velocity_range().bounds[1].ne(&value) { parameter = Some(EmitterNumericParameter::MaxXVelocity); emitter.x_velocity_range().clamp_value(&mut final_value); } else if message.destination() == self.min_y_velocity && emitter.y_velocity_range().bounds[0].ne(&value) { parameter = Some(EmitterNumericParameter::MinYVelocity); emitter.y_velocity_range().clamp_value(&mut final_value); } else if message.destination() == self.max_y_velocity && emitter.y_velocity_range().bounds[1].ne(&value) { parameter = Some(EmitterNumericParameter::MaxYVelocity); emitter.y_velocity_range().clamp_value(&mut final_value); } else if message.destination() == self.min_z_velocity && emitter.z_velocity_range().bounds[0].ne(&value) { emitter.z_velocity_range().clamp_value(&mut final_value); parameter = Some(EmitterNumericParameter::MinZVelocity); } else if message.destination() == self.max_z_velocity && emitter.z_velocity_range().bounds[1].ne(&value) { parameter = Some(EmitterNumericParameter::MaxZVelocity); emitter.z_velocity_range().clamp_value(&mut final_value); } else if message.destination() == self.min_rotation_speed && emitter.rotation_speed_range().bounds[0].ne(&value) { parameter = Some(EmitterNumericParameter::MinRotationSpeed); emitter.rotation_speed_range().clamp_value(&mut final_value); } else if message.destination() == self.max_rotation_speed && emitter.rotation_speed_range().bounds[1].ne(&value) { parameter = Some(EmitterNumericParameter::MaxRotationSpeed); emitter.rotation_speed_range().clamp_value(&mut final_value); } else if message.destination() == self.min_rotation && emitter.rotation_range().bounds[0].ne(&value) { parameter = Some(EmitterNumericParameter::MinRotation); emitter.rotation_range().clamp_value(&mut final_value); } else if message.destination() == self.max_rotation && emitter.rotation_range().bounds[1].ne(&value) { parameter = Some(EmitterNumericParameter::MaxRotation); emitter.rotation_range().clamp_value(&mut final_value); } if let Some(parameter) = parameter { self.sender .send(Message::DoSceneCommand( SceneCommand::SetEmitterNumericParameter( SetEmitterNumericParameterCommand::new( handle, emitter_index, parameter, final_value, ), ), )) .unwrap(); } } UiMessageData::CheckBox(CheckBoxMessage::Check(Some(value))) if message.destination() == self.resurrect_particles => { if emitter.is_particles_resurrects() != *value { self.sender .send(Message::DoSceneCommand( SceneCommand::SetEmitterResurrectParticles( SetEmitterResurrectParticlesCommand::new( handle, emitter_index, *value, ), ), )) .unwrap(); } } UiMessageData::Vec3Editor(Vec3EditorMessage::Value(value)) => { if message.destination() == self.position && emitter.position().ne(value) { self.sender .send(Message::DoSceneCommand(SceneCommand::SetEmitterPosition( SetEmitterPositionCommand::new(handle, emitter_index, *value), ))) .unwrap(); } } _ => {} } } }
// since our policy is tabs, we want to stop clippy from warning about that #![allow(clippy::tabs_in_doc_comments)] extern crate graphite_proc_macros; mod communication; #[macro_use] pub mod misc; mod document; mod frontend; mod global; pub mod input; pub mod tool; pub mod consts; #[doc(inline)] pub use misc::EditorError; #[doc(inline)] pub use graphene::color::Color; #[doc(inline)] pub use graphene::LayerId; #[doc(inline)] pub use graphene::document::Document as SvgDocument; #[doc(inline)] pub use frontend::Callback; use communication::dispatcher::Dispatcher; // TODO: serialize with serde to save the current editor state pub struct Editor { dispatcher: Dispatcher, } use message_prelude::*; impl Editor { pub fn new(callback: Callback) -> Self { Self { dispatcher: Dispatcher::new(callback), } } pub fn handle_message<T: Into<Message>>(&mut self, message: T) -> Result<(), EditorError> { self.dispatcher.handle_message(message) } } pub mod message_prelude { pub use crate::communication::generate_uuid; pub use crate::communication::message::{AsMessage, Message, MessageDiscriminant}; pub use crate::communication::{ActionList, MessageHandler}; pub use crate::document::{DocumentMessage, DocumentMessageDiscriminant}; pub use crate::document::{DocumentsMessage, DocumentsMessageDiscriminant}; pub use crate::document::{MovementMessage, MovementMessageDiscriminant}; pub use crate::frontend::{FrontendMessage, FrontendMessageDiscriminant}; pub use crate::global::{GlobalMessage, GlobalMessageDiscriminant}; pub use crate::input::{InputMapperMessage, InputMapperMessageDiscriminant, InputPreprocessorMessage, InputPreprocessorMessageDiscriminant}; pub use crate::misc::derivable_custom_traits::{ToDiscriminant, TransitiveChild}; pub use crate::tool::tool_messages::*; pub use crate::tool::tools::crop::{CropMessage, CropMessageDiscriminant}; pub use crate::tool::tools::eyedropper::{EyedropperMessage, EyedropperMessageDiscriminant}; pub use crate::tool::tools::fill::{FillMessage, FillMessageDiscriminant}; pub use crate::tool::tools::line::{LineMessage, LineMessageDiscriminant}; pub use crate::tool::tools::navigate::{NavigateMessage, NavigateMessageDiscriminant}; pub use crate::tool::tools::path::{PathMessage, PathMessageDiscriminant}; pub use crate::tool::tools::pen::{PenMessage, PenMessageDiscriminant}; pub use crate::tool::tools::rectangle::{RectangleMessage, RectangleMessageDiscriminant}; pub use crate::tool::tools::select::{SelectMessage, SelectMessageDiscriminant}; pub use crate::tool::tools::shape::{ShapeMessage, ShapeMessageDiscriminant}; pub use crate::LayerId; pub use graphite_proc_macros::*; pub use std::collections::VecDeque; }
use std::ops::{Deref, Range}; use std::marker::PhantomData; use errors::*; pub trait BlockDevice { fn block_size(&self) -> usize; fn num_blocks(&self) -> usize; fn get_block(&mut self, num: usize) -> Result<Block>; fn push(&mut self, block: &[u8]) -> Result<()>; fn pop(&mut self) -> Result<()>; fn replace(&mut self, num: usize, block: &[u8]) -> Result<()>; } pub struct Block<'a> { data: &'a [u8], phantom_mut: PhantomData<&'a mut ()>, } impl<'a> Deref for Block<'a> { type Target = [u8]; fn deref(&self) -> &[u8] { &self.data } } pub struct MemBlockDevice { block_size: usize, buf: Vec<u8>, } impl MemBlockDevice { pub fn new(block_size: usize) -> MemBlockDevice { assert!(block_size != 0); assert!(block_size.is_power_of_two()); MemBlockDevice { block_size: block_size, buf: Vec::new(), } } } impl BlockDevice for MemBlockDevice { fn block_size(&self) -> usize { self.block_size } fn num_blocks(&self) -> usize { assert!(self.buf.len() % self.block_size == 0); self.buf.len() / self.block_size } fn get_block(&mut self, num: usize) -> Result<Block> { let offset = num * self.block_size; assert!(offset + self.block_size <= self.buf.len()); Ok(Block { data: &self.buf[offset .. offset + self.block_size], phantom_mut: PhantomData, }) } fn push(&mut self, block: &[u8]) -> Result<()> { assert!(block.len() == self.block_size); self.buf.extend(block); Ok(()) } fn pop(&mut self) -> Result<()> { assert!(self.buf.len() % self.block_size == 0); if self.buf.is_empty() { panic!("popping empty block device"); } else { let newlen = self.buf.len() - self.block_size; self.buf.truncate(newlen); Ok(()) } } fn replace(&mut self, num: usize, block: &[u8]) -> Result<()> { assert!(block.len() == self.block_size); let offset = num * self.block_size; assert!(offset + self.block_size <= self.buf.len()); let buf = &mut self.buf[offset .. offset + self.block_size]; buf.copy_from_slice(block); Ok(()) } }
//! Tests auto-converted from "sass-spec/spec/libsass-closed-issues" #[allow(unused)] use super::rsass; mod t47_str_slice; // From "sass-spec/spec/libsass-closed-issues/issue-2640.hrx" #[test] fn issue_2640() { assert_eq!( rsass( ".theme1, .theme2 {\ \n .something {\ \n /* nothing */\ \n }\ \n}\ \n\ \n$sel: selector-nest(\'.theme1, .theme2\', \'.something\');\ \n \ \n#{$sel} {\ \n /* nothing */\ \n}\ \n" ) .unwrap(), ".theme1 .something, .theme2 .something {\ \n /* nothing */\ \n}\ \n.theme1 .something, .theme2 .something {\ \n /* nothing */\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue-2681.hrx" #[test] #[ignore] // wrong result fn issue_2681() { assert_eq!( rsass( "%button-styles {\ \n color: red;\ \n\ \n &:focus {\ \n color: blue;\ \n }\ \n}\ \n\ \n[type=\"button\"] {\ \n @extend %button-styles;\ \n}\ \n\ \n" ) .unwrap(), "[type=button] {\ \n color: red;\ \n}\ \n[type=button]:focus {\ \n color: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_100.hrx" #[test] fn issue_100() { assert_eq!( rsass( "$endColor: red;\r\ \ntest {\r\ \n background-color: darken($endColor, 10%) \\9;\r\ \n}" ) .unwrap(), "test {\ \n background-color: #cc0000 \\9 ;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1007.hrx" #[test] fn issue_1007() { assert_eq!( rsass( "/* start */ foo /* foo */ baz /* bar */ {\ \n /* before */ margin /* X */: /* Y */ 0 /* */; /* after */\ \n} /* end */" ) .unwrap(), "/* start */\ \nfoo baz {\ \n /* before */\ \n margin: 0;\ \n /* after */\ \n}\ \n/* end */\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1016.hrx" #[test] fn issue_1016() { assert_eq!( rsass( ".foo {\ \n [baz=\"#{&}\"] {\ \n foo: bar;\ \n }\ \n}\ \n" ) .unwrap(), ".foo [baz=\".foo\"] {\ \n foo: bar;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1021.hrx" #[test] fn issue_1021() { assert_eq!( rsass( "div {\r\ \n top: 10px - 2 * 5px /* arrow size */;\r\ \n}" ) .unwrap(), "div {\ \n top: 0px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1025.hrx" #[test] fn issue_1025() { assert_eq!( rsass( "@mixin m() {\ \n .a & {\ \n @content;\ \n }\ \n}\ \n\ \n:not(:last-of-type) {\ \n top: 10px;\ \n @include m {\ \n top: 10px;\ \n }\ \n}\ \n" ) .unwrap(), ":not(:last-of-type) {\ \n top: 10px;\ \n}\ \n.a :not(:last-of-type) {\ \n top: 10px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1030.hrx" #[test] fn issue_1030() { assert_eq!( rsass( "@mixin will-change() {\ \n @supports (will-change: transform) {\ \n will-change: transform;\ \n }\ \n}\ \ndiv {\ \n a {\ \n top: 10px;\ \n @include will-change();\ \n }\ \n}\ \n" ) .unwrap(), "div a {\ \n top: 10px;\ \n}\ \n@supports (will-change: transform) {\ \n div a {\ \n will-change: transform;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1036.hrx" #[test] fn issue_1036() { assert_eq!( rsass( "@mixin all-vip() {\ \n test: vip;\ \n}\ \n@mixin gold() {\ \n test: gold;\ \n}\ \n@mixin platinum() {\ \n test: platinum;\ \n}\ \n\ \n@mixin icons-sprite($icon-name){\ \n @if $icon-name == \'all-vip\' {\ \n @include all-vip();\ \n }\ \n @else if $icon-name == \'gold\' {\ \n @include gold();\ \n }\ \n @else if $icon-name == \'platinum\' {\ \n @include platinum();\ \n }\ \n}\ \n\ \ndiv {\ \n @include icons-sprite(\"platinum\");\ \n @include icons-sprite(\"all-vip\");\ \n @include icons-sprite(\"gold\");\ \n}\ \ndiv {\ \n @include icons-sprite(platinum);\ \n @include icons-sprite(all-vip);\ \n @include icons-sprite(gold);\ \n}" ) .unwrap(), "div {\ \n test: platinum;\ \n test: vip;\ \n test: gold;\ \n}\ \ndiv {\ \n test: platinum;\ \n test: vip;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1043.hrx" #[test] #[ignore] // wrong result fn issue_1043() { assert_eq!( rsass( ".component{\ \n color: red;\ \n @at-root{\ \n #{&}--foo#{&}--bar {\ \n color: blue;\ \n }\ \n }\ \n}\ \n\ \n.test{\ \n .selector#{&} {\ \n color: blue;\ \n }\ \n}" ) .unwrap(), ".component {\ \n color: red;\ \n}\ \n.component--foo.component--bar {\ \n color: blue;\ \n}\ \n.test .selector.test {\ \n color: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1060.hrx" #[test] fn issue_1060() { assert_eq!( rsass( "foo {\ \n @if true {\ \n foo: true;\ \n } @elseif true {\ \n foo: false;\ \n } @else {\ \n foo: false;\ \n }\ \n\ \n @if true {\ \n bar: true;\ \n } @else if true {\ \n bar: false;\ \n } @else {\ \n bar: false;\ \n }\ \n}\ \n" ) .unwrap(), "foo {\ \n foo: true;\ \n bar: true;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1061.hrx" #[test] fn issue_1061() { assert_eq!( rsass( "a {\ \n &.div,\ \n &.span {\ \n display: block;\ \n }\ \n}\ \n" ) .unwrap(), "a.div, a.span {\ \n display: block;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1063.hrx" #[test] #[ignore] // wrong result fn issue_1063() { assert_eq!( rsass( "%foo {\ \n & > x { display: block; }\ \n}\ \n\ \na {\ \n > b { @extend %foo; }\ \n > b > c { @extend %foo; }\ \n}\ \n" ) .unwrap(), "a > b > c > x, a > b > x {\ \n display: block;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1074.hrx" #[test] fn issue_1074() { assert_eq!( rsass( "$i: 1;\ \n.foo#{-$i} { a:b }\ \n.foo-#{$i} { a:b }\ \n.foo#{-1} { a:b }\ \n.foo-#{1} { a:b }\ \n" ) .unwrap(), ".foo-1 {\ \n a: b;\ \n}\ \n.foo-1 {\ \n a: b;\ \n}\ \n.foo-1 {\ \n a: b;\ \n}\ \n.foo-1 {\ \n a: b;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1075.hrx" #[test] fn issue_1075() { assert_eq!( rsass( "$name: \"lighten\";\ \n$args: (\"color\": #ff0000, \"amount\": 10%);\ \nfoo {\ \n bar: call($name, $args...);\ \n}\ \n" ) .unwrap(), "foo {\ \n bar: #ff3333;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1079.hrx" // Ignoring "issue_1079", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_108.hrx" #[test] fn issue_108() { assert_eq!( rsass( "$a: red;\r\ \n\r\ \n@mixin f($a: $a) {\r\ \n color: $a;\r\ \n}\r\ \n\r\ \nh1 {\r\ \n @include f;\r\ \n}\r\ \n\r\ \nh2 {\r\ \n @include f(blue);\r\ \n}" ) .unwrap(), "h1 {\ \n color: red;\ \n}\ \nh2 {\ \n color: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1080.hrx" #[test] #[ignore] // wrong result fn issue_1080() { assert_eq!( rsass( "/** comment 1 */\ \n@import url(\"import-1\");\ \n/** comment 2 */\ \n@import url(\"import-2\");\ \n/** comment 3 */\ \nfoo { bar: baz; }\ \n" ) .unwrap(), "/** comment 1 */\ \n@import url(\"import-1\");\ \n/** comment 2 */\ \n@import url(\"import-2\");\ \n/** comment 3 */\ \nfoo {\ \n bar: baz;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1081.hrx" #[test] #[ignore] // wrong result fn issue_1081() { assert_eq!( rsass( "$foo: foo !global !default;\ \n\ \ndefault {\ \n foo: $foo;\ \n}\ \n\ \n$foo: bar;\ \n\ \nafter {\ \n @import \"import\";\ \n foo: $foo;\ \n}\ \n" ) .unwrap(), "default {\ \n foo: foo;\ \n}\ \nafter {\ \n foo: bar;\ \n}\ \nafter import-before {\ \n foo: bar;\ \n}\ \nafter import-after {\ \n foo: bar;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1082.hrx" #[test] fn issue_1082() { assert_eq!( rsass( "@font-face {\ \n font-family: \'My Font\';\ \n font-style: normal;\ \n font-weight: 300;\ \n src: local(\'My Font\'), local(\'My-Font\'),\ \n /* from http://.... original source of .eot */\ \n url(\'my-font.eot?#iefix\') format(\'embedded-opentype\'),\ \n /* from http://.... original source of .woff */\ \n url(\'my-font.woff\') format(\'woff\'),\ \n /* from http://.... original source of .ttf */\ \n url(\'my-font.ttf\') format(\'truetype\'),\ \n /* from http://.... original source of .svg */\ \n url(\'my-font.svg#MyFont\') format(\'svg\');\ \n}\ \n" ) .unwrap(), "@font-face {\ \n font-family: \"My Font\";\ \n font-style: normal;\ \n font-weight: 300;\ \n src: local(\"My Font\"), local(\"My-Font\"), url(\"my-font.eot?#iefix\") format(\"embedded-opentype\"), url(\"my-font.woff\") format(\"woff\"), url(\"my-font.ttf\") format(\"truetype\"), url(\"my-font.svg#MyFont\") format(\"svg\");\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1086.hrx" #[test] fn issue_1086() { assert_eq!(rsass("$map: (-1px: 12);").unwrap(), ""); } // From "sass-spec/spec/libsass-closed-issues/issue_1087.hrx" #[test] fn issue_1087() { assert_eq!( rsass( "$foo: bar;\ \na {\ \n foo: url($foo);\ \n foo: url(#{$foo});\ \n}\ \n" ) .unwrap(), "a {\ \n foo: url(bar);\ \n foo: url(bar);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1091.hrx" #[test] #[ignore] // wrong result fn issue_1091() { assert_eq!( rsass( ".a {\ \n top: 0;\ \n}\ \n\ \n.b .c {\ \n @extend .a;\ \n}\ \n\ \n.d > .e {\ \n @extend .a;\ \n @extend .c;\ \n}\ \n" ) .unwrap(), ".a, .d > .e, .b .c, .b .d > .e {\ \n top: 0;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1092.hrx" #[test] fn issue_1092() { assert_eq!( rsass( "$bar: \"\";\ \n$baz: \" \";\ \na { a: foo #{\"\"}; }\ \nb { b: foo #{\" \"}; }\ \nc { c: foo #{$bar}; }\ \nd { d: foo #{$baz}; }\ \n" ) .unwrap(), "a {\ \n a: foo;\ \n}\ \nb {\ \n b: foo ;\ \n}\ \nc {\ \n c: foo;\ \n}\ \nd {\ \n d: foo ;\ \n}\ \n" ); } mod issue_1093; // From "sass-spec/spec/libsass-closed-issues/issue_1098.hrx" #[test] #[ignore] // wrong result fn issue_1098() { assert_eq!( rsass( "div {\ \n opacity: 1\\9;\ \n width: 500px\\9;\ \n color: #f00000\\9\\0;\ \n color: #f00000\\9\\0\\;\ \n}\ \n" ) .unwrap(), "div {\ \n opacity: 1\\9 ;\ \n width: 500px\\9 ;\ \n color: #f00000\\9 \\0 ;\ \n color: #f00000\\9 \\0 \\;;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1101.hrx" #[test] fn issue_1101() { assert_eq!( rsass( "$foo: white;\r\ \nfoo {\r\ \n bar: adjust-color($foo, $hue: -6deg, $lightness: -16, $saturation: -7);\r\ \n}" ) .unwrap(), "foo {\ \n bar: #d6d6d6;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1102.hrx" #[test] fn issue_1102() { assert_eq!( rsass( "foo {\ \n display:expression(\"inline\",\ \n (this.innerHTML += (this.innerHTML.indexOf(\",\") == -1 ? \", \" : \"\")),\ \n this.runtimeStyle.display = \"inline\");\ \n}\ \n" ) .unwrap(), "foo {\ \n display: expression(\"inline\", (this.innerHTML += (this.innerHTML.indexOf(\",\") == -1 ? \", \" : \"\")), this.runtimeStyle.display = \"inline\");\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1103.hrx" #[test] #[ignore] // wrong result fn issue_1103() { assert_eq!( rsass( "@import \"import\";\ \n\ \n@media screen and (min-width: 1) {\ \n foo { bar: baz }\ \n baz { bar: foo }\ \n}\ \n\ \n@media screen and (min-width: 1) {\ \n @import \"import\";\ \n}\ \n" ) .unwrap(), "foo {\ \n bar: baz;\ \n}\ \nbaz {\ \n bar: foo;\ \n}\ \n@media screen and (max-width: 2) {\ \n foo {\ \n bar: baz;\ \n }\ \n baz {\ \n bar: foo;\ \n }\ \n}\ \n@media screen and (min-width: 1) {\ \n foo {\ \n bar: baz;\ \n }\ \n baz {\ \n bar: foo;\ \n }\ \n}\ \n@media screen and (min-width: 1) {\ \n foo {\ \n bar: baz;\ \n }\ \n baz {\ \n bar: foo;\ \n }\ \n}\ \n@media screen and (min-width: 1) and (max-width: 2) {\ \n foo {\ \n bar: baz;\ \n }\ \n baz {\ \n bar: foo;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1106.hrx" #[test] fn issue_1106() { assert_eq!( rsass( "@function foo() { @return null; }\ \n$foo: null;\ \na {\ \n foo: bar;\ \n variable: $foo;\ \n function: foo();\ \n unquote: unquote($foo);\ \n}\ \n\ \nb {\ \n variable: $foo;\ \n function: foo();\ \n unquote: unquote($foo);\ \n}\ \n" ) .unwrap(), "a {\ \n foo: bar;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1107.hrx" #[test] #[ignore] // wrong result fn issue_1107() { assert_eq!( rsass( ".foo {\ \n filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(\ \n src=\"#{foo}\",\ \n sizingMethod=\'scale\');\ \n}\ \n" ) .unwrap(), ".foo {\ \n filter: progid:DXImageTransform.Microsoft.AlphaImageLoader( src=\"foo\", sizingMethod=\"scale\");\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1115.hrx" #[test] fn issue_1115() { assert_eq!( rsass( "foo {\ \n bar: \"x\\79\";\ \n baz: \"#{x}\\79\";\ \n bar: \"x\\a\";\ \n baz: \"#{x}\\a\";\ \n}\ \n" ) .unwrap(), "foo {\ \n bar: \"xy\";\ \n baz: \"xy\";\ \n bar: \"x\\a\";\ \n baz: \"x\\a\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_112.hrx" #[test] fn issue_112() { assert_eq!( rsass( "@mixin media($var1, $var2) {\r\ \n @media screen and ($var1: $var2) {\r\ \n @content;\r\ \n }\r\ \n}\r\ \n\r\ \n@include media(max-device-width, 500px) {\r\ \n foo {\r\ \n bar: \"works\";\r\ \n }\r\ \n}" ) .unwrap(), "@media screen and (max-device-width: 500px) {\ \n foo {\ \n bar: \"works\";\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1121.hrx" #[test] fn issue_1121() { assert_eq!( rsass( "$foo: \"foo\";\ \n$bar: \"bar\";\ \n$baz: \"baz\";\ \n/*\ \n * <div class=\"foo #{$foo}\" bar=\"#{$bar}\" baz=\"#{$baz}\">\ \n */\ \n" ) .unwrap(), "/*\ \n * <div class=\"foo foo\" bar=\"bar\" baz=\"baz\">\ \n */\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1127.hrx" #[test] fn issue_1127() { assert_eq!( rsass( "$a: to-upper-case(\'abcd\');\ \n$b: to-upper-case(\"abcd\");\ \n$c: to-upper-case(abcd);\ \n\ \nfoo {\ \n content: #{$a};\ \n content: #{$b};\ \n content: #{$c};\ \n content: \'#{$a}\';\ \n content: \'#{$b}\';\ \n content: \'#{$c}\';\ \n content: \"#{$a}\";\ \n content: \"#{$b}\";\ \n content: \"#{$c}\";\ \n\ \n content: #{unquote($a)};\ \n content: #{unquote($b)};\ \n content: #{unquote($c)};\ \n content: \'#{unquote($a)}\';\ \n content: \'#{unquote($b)}\';\ \n content: \'#{unquote($c)}\';\ \n content: \"#{unquote($a)}\";\ \n content: \"#{unquote($b)}\";\ \n content: \"#{unquote($c)}\";\ \n\ \n content: #{$a + unquote(\"efg\")};\ \n content: #{$b + unquote(\"efg\")};\ \n content: #{$c + unquote(\"efg\")};\ \n content: \'#{$a + unquote(\"efg\")}\';\ \n content: \'#{$b + unquote(\"efg\")}\';\ \n content: \'#{$c + unquote(\"efg\")}\';\ \n content: \"#{$a + unquote(\"efg\")}\";\ \n content: \"#{$b + unquote(\"efg\")}\";\ \n content: \"#{$c + unquote(\"efg\")}\";\ \n\ \n content: #{$a + unquote(\"\")};\ \n content: #{$b + unquote(\"\")};\ \n content: #{$c + unquote(\"\")};\ \n content: \'#{$a + unquote(\"\")}\';\ \n content: \'#{$b + unquote(\"\")}\';\ \n content: \'#{$c + unquote(\"\")}\';\ \n content: \"#{$a + unquote(\"\")}\";\ \n content: \"#{$b + unquote(\"\")}\";\ \n content: \"#{$c + unquote(\"\")}\";\ \n}\ \n" ) .unwrap(), "foo {\ \n content: ABCD;\ \n content: ABCD;\ \n content: ABCD;\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n content: ABCD;\ \n content: ABCD;\ \n content: ABCD;\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n content: ABCDefg;\ \n content: ABCDefg;\ \n content: ABCDefg;\ \n content: \"ABCDefg\";\ \n content: \"ABCDefg\";\ \n content: \"ABCDefg\";\ \n content: \"ABCDefg\";\ \n content: \"ABCDefg\";\ \n content: \"ABCDefg\";\ \n content: ABCD;\ \n content: ABCD;\ \n content: ABCD;\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n content: \"ABCD\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_113.hrx" #[test] fn issue_113() { assert_eq!( rsass( "// Input\ \nsection {\ \n $w: null, 10px;\ \n width: $w;\ \n}" ) .unwrap(), "section {\ \n width: 10px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1130.hrx" #[test] fn issue_1130() { assert_eq!( rsass( "@function foo($args...) {\ \n @return bar($args...);\ \n}\ \n\ \n@function bar() {\ \n @return \"hi\";\ \n}\ \n\ \n.foo {\ \n result: foo();\ \n}\ \n" ) .unwrap(), ".foo {\ \n result: \"hi\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1132.hrx" #[test] fn issue_1132() { assert_eq!( rsass( "foo {\ \n @for $i from 0 through 360 {\ \n i#{$i}: hue(hsl($i, 10%, 20%));\ \n }\ \n}\ \n" ) .unwrap(), "foo {\ \n i0: 0deg;\ \n i1: 1deg;\ \n i2: 2deg;\ \n i3: 3deg;\ \n i4: 4deg;\ \n i5: 5deg;\ \n i6: 6deg;\ \n i7: 7deg;\ \n i8: 8deg;\ \n i9: 9deg;\ \n i10: 10deg;\ \n i11: 11deg;\ \n i12: 12deg;\ \n i13: 13deg;\ \n i14: 14deg;\ \n i15: 15deg;\ \n i16: 16deg;\ \n i17: 17deg;\ \n i18: 18deg;\ \n i19: 19deg;\ \n i20: 20deg;\ \n i21: 21deg;\ \n i22: 22deg;\ \n i23: 23deg;\ \n i24: 24deg;\ \n i25: 25deg;\ \n i26: 26deg;\ \n i27: 27deg;\ \n i28: 28deg;\ \n i29: 29deg;\ \n i30: 30deg;\ \n i31: 31deg;\ \n i32: 32deg;\ \n i33: 33deg;\ \n i34: 34deg;\ \n i35: 35deg;\ \n i36: 36deg;\ \n i37: 37deg;\ \n i38: 38deg;\ \n i39: 39deg;\ \n i40: 40deg;\ \n i41: 41deg;\ \n i42: 42deg;\ \n i43: 43deg;\ \n i44: 44deg;\ \n i45: 45deg;\ \n i46: 46deg;\ \n i47: 47deg;\ \n i48: 48deg;\ \n i49: 49deg;\ \n i50: 50deg;\ \n i51: 51deg;\ \n i52: 52deg;\ \n i53: 53deg;\ \n i54: 54deg;\ \n i55: 55deg;\ \n i56: 56deg;\ \n i57: 57deg;\ \n i58: 58deg;\ \n i59: 59deg;\ \n i60: 60deg;\ \n i61: 61deg;\ \n i62: 62deg;\ \n i63: 63deg;\ \n i64: 64deg;\ \n i65: 65deg;\ \n i66: 66deg;\ \n i67: 67deg;\ \n i68: 68deg;\ \n i69: 69deg;\ \n i70: 70deg;\ \n i71: 71deg;\ \n i72: 72deg;\ \n i73: 73deg;\ \n i74: 74deg;\ \n i75: 75deg;\ \n i76: 76deg;\ \n i77: 77deg;\ \n i78: 78deg;\ \n i79: 79deg;\ \n i80: 80deg;\ \n i81: 81deg;\ \n i82: 82deg;\ \n i83: 83deg;\ \n i84: 84deg;\ \n i85: 85deg;\ \n i86: 86deg;\ \n i87: 87deg;\ \n i88: 88deg;\ \n i89: 89deg;\ \n i90: 90deg;\ \n i91: 91deg;\ \n i92: 92deg;\ \n i93: 93deg;\ \n i94: 94deg;\ \n i95: 95deg;\ \n i96: 96deg;\ \n i97: 97deg;\ \n i98: 98deg;\ \n i99: 99deg;\ \n i100: 100deg;\ \n i101: 101deg;\ \n i102: 102deg;\ \n i103: 103deg;\ \n i104: 104deg;\ \n i105: 105deg;\ \n i106: 106deg;\ \n i107: 107deg;\ \n i108: 108deg;\ \n i109: 109deg;\ \n i110: 110deg;\ \n i111: 111deg;\ \n i112: 112deg;\ \n i113: 113deg;\ \n i114: 114deg;\ \n i115: 115deg;\ \n i116: 116deg;\ \n i117: 117deg;\ \n i118: 118deg;\ \n i119: 119deg;\ \n i120: 120deg;\ \n i121: 121deg;\ \n i122: 122deg;\ \n i123: 123deg;\ \n i124: 124deg;\ \n i125: 125deg;\ \n i126: 126deg;\ \n i127: 127deg;\ \n i128: 128deg;\ \n i129: 129deg;\ \n i130: 130deg;\ \n i131: 131deg;\ \n i132: 132deg;\ \n i133: 133deg;\ \n i134: 134deg;\ \n i135: 135deg;\ \n i136: 136deg;\ \n i137: 137deg;\ \n i138: 138deg;\ \n i139: 139deg;\ \n i140: 140deg;\ \n i141: 141deg;\ \n i142: 142deg;\ \n i143: 143deg;\ \n i144: 144deg;\ \n i145: 145deg;\ \n i146: 146deg;\ \n i147: 147deg;\ \n i148: 148deg;\ \n i149: 149deg;\ \n i150: 150deg;\ \n i151: 151deg;\ \n i152: 152deg;\ \n i153: 153deg;\ \n i154: 154deg;\ \n i155: 155deg;\ \n i156: 156deg;\ \n i157: 157deg;\ \n i158: 158deg;\ \n i159: 159deg;\ \n i160: 160deg;\ \n i161: 161deg;\ \n i162: 162deg;\ \n i163: 163deg;\ \n i164: 164deg;\ \n i165: 165deg;\ \n i166: 166deg;\ \n i167: 167deg;\ \n i168: 168deg;\ \n i169: 169deg;\ \n i170: 170deg;\ \n i171: 171deg;\ \n i172: 172deg;\ \n i173: 173deg;\ \n i174: 174deg;\ \n i175: 175deg;\ \n i176: 176deg;\ \n i177: 177deg;\ \n i178: 178deg;\ \n i179: 179deg;\ \n i180: 180deg;\ \n i181: 181deg;\ \n i182: 182deg;\ \n i183: 183deg;\ \n i184: 184deg;\ \n i185: 185deg;\ \n i186: 186deg;\ \n i187: 187deg;\ \n i188: 188deg;\ \n i189: 189deg;\ \n i190: 190deg;\ \n i191: 191deg;\ \n i192: 192deg;\ \n i193: 193deg;\ \n i194: 194deg;\ \n i195: 195deg;\ \n i196: 196deg;\ \n i197: 197deg;\ \n i198: 198deg;\ \n i199: 199deg;\ \n i200: 200deg;\ \n i201: 201deg;\ \n i202: 202deg;\ \n i203: 203deg;\ \n i204: 204deg;\ \n i205: 205deg;\ \n i206: 206deg;\ \n i207: 207deg;\ \n i208: 208deg;\ \n i209: 209deg;\ \n i210: 210deg;\ \n i211: 211deg;\ \n i212: 212deg;\ \n i213: 213deg;\ \n i214: 214deg;\ \n i215: 215deg;\ \n i216: 216deg;\ \n i217: 217deg;\ \n i218: 218deg;\ \n i219: 219deg;\ \n i220: 220deg;\ \n i221: 221deg;\ \n i222: 222deg;\ \n i223: 223deg;\ \n i224: 224deg;\ \n i225: 225deg;\ \n i226: 226deg;\ \n i227: 227deg;\ \n i228: 228deg;\ \n i229: 229deg;\ \n i230: 230deg;\ \n i231: 231deg;\ \n i232: 232deg;\ \n i233: 233deg;\ \n i234: 234deg;\ \n i235: 235deg;\ \n i236: 236deg;\ \n i237: 237deg;\ \n i238: 238deg;\ \n i239: 239deg;\ \n i240: 240deg;\ \n i241: 241deg;\ \n i242: 242deg;\ \n i243: 243deg;\ \n i244: 244deg;\ \n i245: 245deg;\ \n i246: 246deg;\ \n i247: 247deg;\ \n i248: 248deg;\ \n i249: 249deg;\ \n i250: 250deg;\ \n i251: 251deg;\ \n i252: 252deg;\ \n i253: 253deg;\ \n i254: 254deg;\ \n i255: 255deg;\ \n i256: 256deg;\ \n i257: 257deg;\ \n i258: 258deg;\ \n i259: 259deg;\ \n i260: 260deg;\ \n i261: 261deg;\ \n i262: 262deg;\ \n i263: 263deg;\ \n i264: 264deg;\ \n i265: 265deg;\ \n i266: 266deg;\ \n i267: 267deg;\ \n i268: 268deg;\ \n i269: 269deg;\ \n i270: 270deg;\ \n i271: 271deg;\ \n i272: 272deg;\ \n i273: 273deg;\ \n i274: 274deg;\ \n i275: 275deg;\ \n i276: 276deg;\ \n i277: 277deg;\ \n i278: 278deg;\ \n i279: 279deg;\ \n i280: 280deg;\ \n i281: 281deg;\ \n i282: 282deg;\ \n i283: 283deg;\ \n i284: 284deg;\ \n i285: 285deg;\ \n i286: 286deg;\ \n i287: 287deg;\ \n i288: 288deg;\ \n i289: 289deg;\ \n i290: 290deg;\ \n i291: 291deg;\ \n i292: 292deg;\ \n i293: 293deg;\ \n i294: 294deg;\ \n i295: 295deg;\ \n i296: 296deg;\ \n i297: 297deg;\ \n i298: 298deg;\ \n i299: 299deg;\ \n i300: 300deg;\ \n i301: 301deg;\ \n i302: 302deg;\ \n i303: 303deg;\ \n i304: 304deg;\ \n i305: 305deg;\ \n i306: 306deg;\ \n i307: 307deg;\ \n i308: 308deg;\ \n i309: 309deg;\ \n i310: 310deg;\ \n i311: 311deg;\ \n i312: 312deg;\ \n i313: 313deg;\ \n i314: 314deg;\ \n i315: 315deg;\ \n i316: 316deg;\ \n i317: 317deg;\ \n i318: 318deg;\ \n i319: 319deg;\ \n i320: 320deg;\ \n i321: 321deg;\ \n i322: 322deg;\ \n i323: 323deg;\ \n i324: 324deg;\ \n i325: 325deg;\ \n i326: 326deg;\ \n i327: 327deg;\ \n i328: 328deg;\ \n i329: 329deg;\ \n i330: 330deg;\ \n i331: 331deg;\ \n i332: 332deg;\ \n i333: 333deg;\ \n i334: 334deg;\ \n i335: 335deg;\ \n i336: 336deg;\ \n i337: 337deg;\ \n i338: 338deg;\ \n i339: 339deg;\ \n i340: 340deg;\ \n i341: 341deg;\ \n i342: 342deg;\ \n i343: 343deg;\ \n i344: 344deg;\ \n i345: 345deg;\ \n i346: 346deg;\ \n i347: 347deg;\ \n i348: 348deg;\ \n i349: 349deg;\ \n i350: 350deg;\ \n i351: 351deg;\ \n i352: 352deg;\ \n i353: 353deg;\ \n i354: 354deg;\ \n i355: 355deg;\ \n i356: 356deg;\ \n i357: 357deg;\ \n i358: 358deg;\ \n i359: 359deg;\ \n i360: 0deg;\ \n}\ \n" ); } mod issue_1133; // From "sass-spec/spec/libsass-closed-issues/issue_1153.hrx" #[test] fn issue_1153() { assert_eq!( rsass( "/* precision: 0 */\ \n$foo: 123px;\ \nfoo {\ \n bar: $foo;\ \n}" ) .unwrap(), "/* precision: 0 */\ \nfoo {\ \n bar: 123px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1162.hrx" #[test] fn issue_1162() { assert_eq!( rsass( "div {\ \n content: #{0/0} a;\ \n}" ) .unwrap(), "div {\ \n content: 0/0 a;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1163.hrx" #[test] fn issue_1163() { assert_eq!( rsass( "div {\ \n content: (((92px * 12) / 13px) * 1em) + 22em;\ \n}" ) .unwrap(), "div {\ \n content: 106.9230769231em;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1167.hrx" #[test] fn issue_1167() { assert_eq!( rsass( "a {\ \n b: 3s + 101ms;\ \n}" ) .unwrap(), "a {\ \n b: 3.101s;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1168.hrx" #[test] fn issue_1168() { assert_eq!( rsass( "$namespace: \'test-\';\ \n$column: 1;\ \n\ \n.#{$namespace}#{$column}\\/#{$column} {\ \n width: 100% !important;\ \n}" ) .unwrap(), ".test-1\\/1 {\ \n width: 100% !important;\ \n}\ \n" ); } mod issue_1169; mod issue_1170; // From "sass-spec/spec/libsass-closed-issues/issue_1171.hrx" #[test] #[ignore] // wrong result fn issue_1171() { assert_eq!( rsass( "@function foo($initial, $args...) {\ \n $args: append($args, 3);\ \n\ \n @return bar($initial, $args...);\ \n}\ \n\ \n@function bar($args...) {\ \n @return length($args);\ \n}\ \n\ \n@function baz($initial, $args...) {\ \n $args: append($args, 3);\ \n\ \n @return nth($args, 1);\ \n}\ \n\ \n.test {\ \n foo: foo(1, 2);\ \n baz: baz(1, 2);\ \n}" ) .unwrap(), ".test {\ \n foo: 3;\ \n baz: 2;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1178.hrx" #[test] fn issue_1178() { assert_eq!( rsass( "$foo: ((4, 5), 6, (7 8) 9);\ \n\ \nbar {\ \n a: $foo;\ \n f: 1 2 3 + $foo;\ \n b: 1, 2, 3 + (2 ($foo));\ \n x: inspect($foo);\ \n}\ \n" ) .unwrap(), "bar {\ \n a: 4, 5, 6, 7 8 9;\ \n f: 1 2 34, 5, 6, 7 8 9;\ \n b: 1, 2, 32 4, 5, 6, 7 8 9;\ \n x: (4, 5), 6, (7 8) 9;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1187.hrx" // Ignoring "issue_1187", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1188.hrx" #[test] #[ignore] // unexepected error fn issue_1188() { assert_eq!( rsass( "$columns: 4;\ \n$context: 120px;\ \n$name-multiplicator: 2;\ \nfoo {\ \n *width: expression((this.parentNode.clientWidth/#{$context}*#{($columns / $name-multiplicator)} - parseInt(this.currentStyle[\'paddingLeft\']) - parseInt(this.currentStyle[\'paddingRight\'])) + \'px\');\ \n}" ) .unwrap(), "foo {\ \n *width: expression((this.parentNode.clientWidth/120px*2 - parseInt(this.currentStyle[\"paddingLeft\"]) - parseInt(this.currentStyle[\"paddingRight\"])) + \"px\");\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1192" #[test] #[ignore] // wrong result fn issue_1192() { assert_eq!( rsass( "$keyword: foobar;\ \n\ \n@mixin test($arglist...){\ \n $map: keywords($arglist);\ \n /*#{inspect($map)}*/\ \n /*#{inspect($arglist)}*/\ \n}\ \n\ \n// Works\ \n@include test(foo, bar, baz);\ \n// Ruby Sass: /*foo, bar, baz*/\ \n// LibSass : /*foo, bar, baz*/\ \n\ \n// LibSass does not inspect as ()\ \n@include test;\ \n// Ruby Sass: /*()*/\ \n// LibSass : /**/\ \n\ \n// Ruby Sass throws error – LibSass shows keywords in arglist\ \n// (keywords should not show in arglist – see below)\ \n@include test(foo, bar, baz, $keyword: keyword);\ \n// Ruby Sass: \"Mixin test1 doesn\'t have an argument named $keyword.\"\ \n// LibSass : /*foo, bar, baz, $keyword: keyword*/" ) .unwrap(), "/*()*/\ \n/*foo, bar, baz*/\ \n/*()*/\ \n/*()*/\ \n/*(keyword: keyword)*/\ \n/*foo, bar, baz*/\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1206.hrx" #[test] fn issue_1206() { assert_eq!( rsass( "foo {\ \n bar: #{0/0};\ \n bar: #{0/1};\ \n bar: #{1/2};\ \n}\ \n" ) .unwrap(), "foo {\ \n bar: 0/0;\ \n bar: 0/1;\ \n bar: 1/2;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1207.hrx" #[test] fn issue_1207() { assert_eq!( rsass( "@function test($pos) {\ \n @return test-#{$pos};\ \n}\ \n\ \n.foo {\ \n content: test(str-slice(\'scale-0\', 7)); // Nope\ \n content: test-#{str-slice(\'scale-0\', 7)}; // Yep\ \n}" ) .unwrap(), ".foo {\ \n content: test-0;\ \n content: test-0;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1208.hrx" #[test] fn issue_1208() { assert_eq!( rsass( "foo {\ \n &.bar, /* */\ \n &.baz {\ \n color: red;\ \n }\ \n}\ \n" ) .unwrap(), "foo.bar, foo.baz {\ \n color: red;\ \n}\ \n" ); } mod issue_1210; // From "sass-spec/spec/libsass-closed-issues/issue_1214.hrx" #[test] fn issue_1214() { assert_eq!( rsass( "@mixin keyframes($animation-name) {\ \n @keyframes $animation-name {\ \n @content;\ \n }\ \n}\ \n\ \n@include keyframes(bounce) {\ \n 0%, 20%, 50%, 80%, 100% {transform: translateY(0);}\ \n 40% {transform: translateY(-30px);}\ \n 60% {transform: translateY(-15px);}\ \n}" ) .unwrap(), "@keyframes $animation-name {\ \n 0%, 20%, 50%, 80%, 100% {\ \n transform: translateY(0);\ \n }\ \n 40% {\ \n transform: translateY(-30px);\ \n }\ \n 60% {\ \n transform: translateY(-15px);\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1215.hrx" #[test] fn issue_1215() { assert_eq!( rsass( "foo {\ \n -quotes: \'this-string\' == \'this-string\';\ \n -quotes: this-string == \'this-string\';\ \n -quotes: \'this-string\' == \"this-string\";\ \n -quotes: \'this-string\' == \'\"this-string\"\';\ \n -quotes: \'\"this-string\"\' == \"\'this-string\'\";\ \n foo: this-string;\ \n foo: \'this-string\';\ \n foo: \"this-string\";\ \n foo: \'\"this-string\"\';\ \n foo: \"\'this-string\'\";\ \n}\ \n" ) .unwrap(), "foo {\ \n -quotes: true;\ \n -quotes: true;\ \n -quotes: true;\ \n -quotes: false;\ \n -quotes: false;\ \n foo: this-string;\ \n foo: \"this-string\";\ \n foo: \"this-string\";\ \n foo: \'\"this-string\"\';\ \n foo: \"\'this-string\'\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1216.hrx" #[test] fn issue_1216() { assert_eq!( rsass( "a {\ \n width: 4.0px;\ \n height: 3.00px;\ \n opacity: 1.0;\ \n}\ \n" ) .unwrap(), "a {\ \n width: 4px;\ \n height: 3px;\ \n opacity: 1;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1218.hrx" #[test] #[ignore] // wrong result fn issue_1218() { assert_eq!( rsass( "$foo: 20px;\ \n@media screen and (\"min-width:#{$foo}\") {\ \n .bar {\ \n width: 12px;\ \n }\ \n}\ \n@media screen and (\"min-width:0\") {\ \n .bar {\ \n width: 12px;\ \n }\ \n}\ \n" ) .unwrap(), "@media screen and (min-width:20px) {\ \n .bar {\ \n width: 12px;\ \n }\ \n}\ \n@media screen and (min-width:0) {\ \n .bar {\ \n width: 12px;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1224.hrx" #[test] #[ignore] // wrong result fn issue_1224() { assert_eq!( rsass( "@media all and (max-width: 768px) {\ \n @media only screen {\ \n a { b: c; }\ \n }\ \n}\ \n" ) .unwrap(), "@media only screen and (max-width: 768px) {\ \n a {\ \n b: c;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1230.hrx" #[test] fn issue_1230() { assert_eq!( rsass( "div {\ \n transition-property:\ \n border-color,\ \n box-shadow,\ \n color;\ \n}" ) .unwrap(), "div {\ \n transition-property: border-color, box-shadow, color;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1231" #[test] fn issue_1231() { assert_eq!( rsass( "div::before {\ \n content: #{\"\\\"\"+\\e600+\"\\\"\"};\ \n}" ) .unwrap(), "@charset \"UTF-8\";\ \ndiv::before {\ \n content: \"\u{e600}\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1233.hrx" #[test] fn issue_1233() { assert_eq!( rsass( "@-moz-keyframes animatetoptop /* Firefox */ line 429\ \n{\ \nfrom {width:0%}\ \nto {width:100%}\ \n}" ) .unwrap(), "@-moz-keyframes animatetoptop /* Firefox */ line 429 {\ \n from {\ \n width: 0%;\ \n }\ \n to {\ \n width: 100%;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1240.hrx" #[test] fn issue_1240() { assert_eq!( rsass( "$var: 1;\ \n$list: 2, 3;\ \n$new-list: append($var, $list);\ \n$nested-list: $var $list;\ \n@debug($var);\ \n@debug($list);\ \n@debug($new-list);\ \n@debug($nested-list);\ \ndiv {\ \n a: $var;\ \n a: $list;\ \n a: $new-list;\ \n a: $nested-list;\ \n}" ) .unwrap(), "div {\ \n a: 1;\ \n a: 2, 3;\ \n a: 1 2, 3;\ \n a: 1 2, 3;\ \n}\ \n" ); } mod issue_1243; // From "sass-spec/spec/libsass-closed-issues/issue_1248.hrx" #[test] #[ignore] // wrong result fn issue_1248() { assert_eq!( rsass( ".a.b .c {\ \n top: 0;\ \n}\ \n.a {\ \n @extend .b;\ \n}\ \n.a .d {\ \n @extend .c;\ \n}\ \n" ) .unwrap(), ".a.b .c, .a .c, .a .d {\ \n top: 0;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1251.hrx" #[test] fn issue_1251() { assert_eq!( rsass( ".foo {\ \n yellow: yellow;\ \n red: red;\ \n blue: blue;\ \n white: white;\ \n black: black;\ \n eval: if(red, yellow, null);\ \n}\ \n" ) .unwrap(), ".foo {\ \n yellow: yellow;\ \n red: red;\ \n blue: blue;\ \n white: white;\ \n black: black;\ \n eval: yellow;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1253.hrx" #[test] fn issue_1253() { assert_eq!( rsass( "$foo: bar;\ \n@keyframes $foo {\ \n from { a: b }\ \n to { a: c }\ \n}" ) .unwrap(), "@keyframes $foo {\ \n from {\ \n a: b;\ \n }\ \n to {\ \n a: c;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1255.hrx" #[test] #[ignore] // wrong result fn issue_1255() { assert_eq!( rsass( "@function double($value) {\ \n @return $value * 2;\ \n}\ \n\ \n@mixin dummy-bug($args...) {\ \n @for $i from 1 through length($args) {\ \n $args: set-nth($args, $i, double(nth($args, $i)));\ \n }\ \n\ \n content: $args;\ \n}\ \n\ \n.foo {\ \n @include dummy-bug(1, 2, 3, 4);\ \n}" ) .unwrap(), ".foo {\ \n content: 2, 4, 6, 8;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1257.hrx" #[test] #[ignore] // wrong result fn issue_1257() { assert_eq!( rsass( ".foo {\ \n color: invert(red...);\ \n}" ) .unwrap(), ".foo {\ \n color: aqua;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1258.hrx" #[test] fn issue_1258() { assert_eq!( rsass( "$list: \'(-webkit-min-device-pixel-ratio: 2)\', \'(min-resolution: 192dpi)\';\ \n$string: \'(-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi)\';\ \n\ \n.foo {\ \n // I should not unquote a list, I know. But still.\ \n content: unquote($list);\ \n content: unquote($string);\ \n}" ) .unwrap(), ".foo {\ \n content: \"(-webkit-min-device-pixel-ratio: 2)\", \"(min-resolution: 192dpi)\";\ \n content: (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1259.hrx" #[test] #[ignore] // wrong result fn issue_1259() { assert_eq!( rsass( "@mixin dummy($a, $b, $c, $d, $e: true) {\ \n content: $a $b $c $d $e;\ \n}\ \n\ \n.foo {\ \n @include dummy( (\'a\', \'b\', \'c\', \'e\')..., $e: false );\ \n}" ) .unwrap(), ".foo {\ \n content: \"a\" \"b\" \"c\" \"e\" false;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1260.hrx" #[test] fn issue_1260() { assert_eq!( rsass( "$EQ-Selectors: ();\ \n\ \n.el {\ \n $EQ-Selectors: append($EQ-Selectors, &, \'comma\') !global;\ \n}\ \n\ \nhtml:before {\ \n content: \"#{$EQ-Selectors}\";\ \n}" ) .unwrap(), "html:before {\ \n content: \".el\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1263.hrx" #[test] #[ignore] // unexepected error fn issue_1263() { assert_eq!( rsass( "foo {\ \n @ap#{pl}y;\ \n @apply(--bar);\ \n @apply ( --bar );\ \n @ap#{pl}y ( --bar , --foo ) ;\ \n}" ) .unwrap(), "foo {\ \n @apply;\ \n @apply (--bar);\ \n @apply ( --bar );\ \n @apply ( --bar , --foo );\ \n}\ \n" ); } mod issue_1266; // From "sass-spec/spec/libsass-closed-issues/issue_1269.hrx" #[test] fn issue_1269() { assert_eq!( rsass( "@function push($list, $items...) {\ \n @return join($list, $items, $separator: auto);\ \n}\ \n\ \n.test {\ \n $list: push(1 2 3, 4, 5);\ \n list: inspect($list);\ \n value: nth($list, 4);\ \n}" ) .unwrap(), ".test {\ \n list: 1 2 3 4 5;\ \n value: 4;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1271.hrx" #[test] fn issue_1271() { assert_eq!( rsass( "$character-code: f102;\ \n\ \ntest {\ \n\ \n /* Expected: \"\\f102\" */\ \n\ \n /* Sass 3.4 */\ \n content: unquote(\"\\\"\\\\#{$character-code}\\\"\");\ \n\ \n /* Sass 3.3 */\ \n content: str-slice(\"\\x\", 1, 1) + $character-code;\ \n\ \n}" ) .unwrap(), "test {\ \n /* Expected: \"\\f102\" */\ \n /* Sass 3.4 */\ \n content: \"\\f102\";\ \n /* Sass 3.3 */\ \n content: \"xf102\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1273.hrx" #[test] fn issue_1273() { assert_eq!( rsass( "test {\ \n src: url(test.eot#{if(true, \'?#{42}\', \'\')});\ \n}" ) .unwrap(), "test {\ \n src: url(test.eot?42);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1277.hrx" #[test] fn issue_1277() { assert_eq!( rsass( "$foo: foo;\ \n$bar: bar;\ \n\ \n.foo {\ \n foo: foo #{$foo}, bar #{$bar};\ \n}\ \n" ) .unwrap(), ".foo {\ \n foo: foo foo, bar bar;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1279.hrx" #[test] fn issue_1279() { assert_eq!( rsass( "@function noop($string) {\ \n @return $string;\ \n}\ \n\ \n.foo {\ \n upper: to-upper-case(\'f\') + str-slice(\'foo\', 2);\ \n lower: to-lower-case(\'f\') + str-slice(\'foo\', 2);\ \n user-upper: to-upper-case(\'f\') + noop(\'oo\');\ \n user-lower: to-lower-case(\'f\') + noop(\'oo\');\ \n}\ \n" ) .unwrap(), ".foo {\ \n upper: \"Foo\";\ \n lower: \"foo\";\ \n user-upper: \"Foo\";\ \n user-lower: \"foo\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1281.hrx" #[test] fn issue_1281() { assert_eq!( rsass( "$quoted: \"green\";\ \n$unquoted: green;\ \n\ \n.test {\ \n string: type-of($quoted);\ \n color: type-of($unquoted);\ \n string: type-of(\"green\");\ \n color: type-of(green);\ \n}\ \n" ) .unwrap(), ".test {\ \n string: string;\ \n color: color;\ \n string: string;\ \n color: color;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1283.hrx" #[test] #[ignore] // unexepected error fn issue_1283() { assert_eq!( rsass( "$map: map-merge((1 2: 3), (2 1: 3));\ \n\ \n.test {\ \n test: inspect($map);\ \n}\ \n" ) .unwrap(), ".test {\ \n test: (1 2: 3, 2 1: 3);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1285.hrx" #[test] fn issue_1285() { assert_eq!( rsass( ".container {\ \n @for $i from 1 through 3 {\ \n @at-root .box-#{$i} {\ \n color: darken(red,($i * 5));\ \n }\ \n }\ \n\ \n // Control\ \n @at-root .outside-child {\ \n background-color: blue;\ \n }\ \n}\ \n" ) .unwrap(), ".box-1 {\ \n color: #e60000;\ \n}\ \n.box-2 {\ \n color: #cc0000;\ \n}\ \n.box-3 {\ \n color: #b30000;\ \n}\ \n.outside-child {\ \n background-color: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1291.hrx" #[test] fn issue_1291() { assert_eq!( rsass( "@mixin spec1($decimal) {\ \n $decimal: unquote($decimal) * -1;\ \n value: $decimal;\ \n}\ \n\ \n@mixin spec2($decimal) {\ \n $decimal: -1 * unquote($decimal);\ \n value: $decimal;\ \n}\ \n\ \n@mixin spec3($decimal) {\ \n value: #{$decimal * -1};\ \n}\ \n\ \n.my-element {\ \n @include spec1(3);\ \n @include spec1(-3);\ \n @include spec2(5);\ \n @include spec2(-5);\ \n @include spec3(7);\ \n @include spec3(-7);\ \n}" ) .unwrap(), ".my-element {\ \n value: -3;\ \n value: 3;\ \n value: -5;\ \n value: 5;\ \n value: -7;\ \n value: 7;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1294.hrx" #[test] fn issue_1294() { assert_eq!( rsass( "/*------------------------------------*\\\ \n #BUTTONS\ \n\\*------------------------------------*/\ \n\ \nfoo {\ \n display: inline-block; /* [1] */\ \n}\ \n" ) .unwrap(), "/*------------------------------------*\\\ \n #BUTTONS\ \n\\*------------------------------------*/\ \nfoo {\ \n display: inline-block;\ \n /* [1] */\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1295.hrx" #[test] fn issue_1295() { assert_eq!( rsass( "foo {\ \n $nothing: null;\ \n foo: \"#{$nothing}\' %\' \'#{$nothing}\";\ \n}\ \n" ) .unwrap(), "foo {\ \n foo: \"\' %\' \'\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1297.hrx" #[test] #[ignore] // wrong result fn issue_1297() { assert_eq!( rsass( ".test .testa {\ \n @at-root #{\"%foo\"} {\ \n color: red;\ \n }\ \n @extend %foo;\ \n}\ \n" ) .unwrap(), ".test .testa {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1298.hrx" #[test] fn issue_1298() { assert_eq!( rsass( "@import url(//fonts.googleapis.com/css?family=Roboto:400,500,700,400italic);\ \nhtml {\ \n font-family: roboto, arial, helvetica, sans-serif;\ \n}\ \n" ) .unwrap(), "@import url(//fonts.googleapis.com/css?family=Roboto:400,500,700,400italic);\ \nhtml {\ \n font-family: roboto, arial, helvetica, sans-serif;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1301.hrx" #[test] fn issue_1301() { assert_eq!( rsass( "$name: \"my-class\";\ \n\ \n.-#{$name} {\ \n content: \"test\";\ \n}\ \n" ) .unwrap(), ".-my-class {\ \n content: \"test\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1303.hrx" #[test] #[ignore] // wrong result fn issue_1303() { assert_eq!( rsass( ".simple {\ \n a: selector-replace(\'foo.bar\', \'foo\', \'foo[baz]\');\ \n}\ \n" ) .unwrap(), ".simple {\ \n a: foo.bar[baz];\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1304.hrx" #[test] fn issue_1304() { assert_eq!( rsass( "foo {\ \n a:&;\ \n > bar {\ \n b:&;\ \n > baz {\ \n c:&;\ \n }\ \n }\ \n}\ \n" ) .unwrap(), "foo {\ \n a: foo;\ \n}\ \nfoo > bar {\ \n b: foo > bar;\ \n}\ \nfoo > bar > baz {\ \n c: foo > bar > baz;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1305.hrx" #[test] fn issue_1305() { assert_eq!( rsass( ".foo {\ \n content: call(\'unquote\', \'foo\', ()...);\ \n}\ \n" ) .unwrap(), ".foo {\ \n content: foo;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_131.hrx" #[test] fn issue_131() { assert_eq!( rsass( "$foo: bar;\r\ \n\r\ \ndiv {\r\ \n content: \"foo #{$foo}\"\r\ \n}" ) .unwrap(), "div {\ \n content: \"foo bar\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1322.hrx" #[test] #[ignore] // wrong result fn issue_1322() { assert_eq!( rsass( "$foo: 400px;\ \n$bar: \"min-width:400px\";\ \n@import url(foo.css) (min-width:400px);\ \n@import url(foo.css) (min-width:$foo);\ \n@import url(foo.css) (min-width:#{$foo});\ \n@import url(foo.css) ($bar);\ \n@import url(foo.css) (#{$bar});\ \n" ) .unwrap(), "@import url(foo.css) (min-width: 400px);\ \n@import url(foo.css) (min-width: 400px);\ \n@import url(foo.css) (min-width: 400px);\ \n@import url(foo.css) (min-width:400px);\ \n@import url(foo.css) (min-width:400px);\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1323.hrx" #[test] fn issue_1323() { assert_eq!( rsass( "@import url(foo.css) only screen;\ \n@import url(foo.css) (min-width:400px);\ \n@import url(foo.css) (min-width:400px) and (max-width:599px);\ \n" ) .unwrap(), "@import url(foo.css) only screen;\ \n@import url(foo.css) (min-width: 400px);\ \n@import url(foo.css) (min-width: 400px) and (max-width: 599px);\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1328.hrx" #[test] #[ignore] // wrong result fn issue_1328() { assert_eq!( rsass( "#{bar},\ \n[foo=\"#{bar}\"],\ \n[foo=\"#{bar}\"] {\ \n content: \"foo\";\ \n}\ \n" ) .unwrap(), "bar,\ \n[foo=bar],\ \n[foo=bar] {\ \n content: \"foo\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1331.hrx" #[test] fn issue_1331() { assert_eq!( rsass( "$m: (foo: 1px, null: 2px, false: 3px, true: 4px);\ \n\ \n@debug $m;\ \n@debug map-get($m, foo);\ \n@debug map-get($m, null);\ \n@debug map-get($m, false);\ \n@debug map-get($m, true);\ \n" ) .unwrap(), "" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1332.hrx" #[test] fn issue_1332() { assert_eq!( rsass( ".box1 {\ \n color: rgb(20%, 20%, 20%);\ \n}\ \n.box2 {\ \n color: rgb(32, 32, 32);\ \n}\ \n.box3 {\ \n color: rgba(20%, 20%, 20%, 0.7);\ \n}\ \n" ) .unwrap(), ".box1 {\ \n color: #333333;\ \n}\ \n.box2 {\ \n color: #202020;\ \n}\ \n.box3 {\ \n color: rgba(51, 51, 51, 0.7);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1333.hrx" #[test] fn issue_1333() { assert_eq!( rsass( "@function baz() {\ \n @return \'baz\';\ \n}\ \n\ \nfoo {\ \n bar: baz()#{\' !important\'};\ \n bar: baz() #{\' !important\'};\ \n}\ \n\ \n" ) .unwrap(), "foo {\ \n bar: \"baz\" !important;\ \n bar: \"baz\" !important;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1336.hrx" #[test] fn issue_1336() { assert_eq!( rsass( "@debug null;\ \n" ) .unwrap(), "" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1355.hrx" // Ignoring "issue_1355", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_137.hrx" #[test] #[ignore] // wrong result fn issue_137() { assert_eq!( rsass( ".foo {\ \n background-color: lime;\ \n a {\ \n color: white;\ \n }\ \n}\ \n\ \n.baz {\ \n @extend .foo;\ \n}" ) .unwrap(), ".foo, .baz {\ \n background-color: lime;\ \n}\ \n.foo a, .baz a {\ \n color: white;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1370.hrx" #[test] fn issue_1370() { assert_eq!( rsass( "@mixin ico-common($imgUrl){\r\ \n display: inline-block;\r\ \n background: url(i/$imgUrl);\r\ \n background-repeat: no-repeat;\r\ \n}\r\ \n\r\ \n@mixin ico-size($width,$height){\r\ \n width: $width;\r\ \n height: $height;\r\ \n}\r\ \n\r\ \n.test{\r\ \n @include ico-common(\"icon.png\");\r\ \n\r\ \n @include ico-size(100px, 100px);\r\ \n}" ) .unwrap(), ".test {\ \n display: inline-block;\ \n background: url(i/\"icon.png\");\ \n background-repeat: no-repeat;\ \n width: 100px;\ \n height: 100px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1376.hrx" #[test] fn issue_1376() { assert_eq!( rsass( ".div{\ \n $foo: 1, null, 2, null, 3;\ \n\ \n content: \"#{$foo}\";\ \n}" ) .unwrap(), ".div {\ \n content: \"1, 2, 3\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1393.hrx" #[test] fn issue_1393() { assert_eq!( rsass( "div {\ \n back#{ground}: {\ \n imag#{e}: url(foo.png);\ \n pos#{it}ion: 50%;\ \n }\ \n}\ \n" ) .unwrap(), "div {\ \n background-image: url(foo.png);\ \n background-position: 50%;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1394.hrx" #[test] fn issue_1394() { assert_eq!( rsass( "foo {\ \n width: \\10 + \\20 \\ ;\ \n}\ \n" ) .unwrap(), "foo {\ \n width: \\10 \\ \\ ;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1396.hrx" #[test] fn issue_1396() { assert_eq!( rsass( "foo {\ \n foo: foo\"bar\"#{baz};\ \n foo: foo\"bar\"baz;\ \n}\ \n" ) .unwrap(), "foo {\ \n foo: foo \"bar\" baz;\ \n foo: foo \"bar\" baz;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1398.hrx" #[test] fn issue_1398() { assert_eq!( rsass( "@media screen and (hux: 3/4) {\ \n foo {\ \n bar: baz;\ \n }\ \n}\ \n" ) .unwrap(), "@media screen and (hux: 3/4) {\ \n foo {\ \n bar: baz;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1399.hrx" #[test] fn issue_1399() { assert_eq!( rsass( "foo {\ \n foo: 3 - \"bar\";\ \n foo: (3 - \"bar\");\ \n foo: 3 / \"bar\";\ \n foo: (3 / \"bar\");\ \n}\ \n" ) .unwrap(), "foo {\ \n foo: 3-\"bar\";\ \n foo: 3-\"bar\";\ \n foo: 3/\"bar\";\ \n foo: 3/\"bar\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1404.hrx" #[test] #[ignore] // wrong result fn issue_1404() { assert_eq!( rsass( ".test {\r\ \n color: #aaabbb--1-2-a;\r\ \n color: type-of(#aaabbb--1-2-a);\r\ \n color: type-of(#aaabbb--1-2);\r\ \n}" ) .unwrap(), ".test {\ \n color: #aaabbb--1-2-a;\ \n color: string;\ \n color: string;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1405.hrx" #[test] #[ignore] // wrong result fn issue_1405() { assert_eq!( rsass( "div {\r\ \n foo: (1a2b3c);\r\ \n\r\ \n length-1: length(1a2b3c);\r\ \n\r\ \n unit-1: unit(1a2b3c);\r\ \n\r\ \n result-1: 1em-.75em;\r\ \n result-2: 2em-1em;\r\ \n result-3: 2em-0.75em;\r\ \n result-4: 1.5em-1em;\r\ \n result-5: 2em-1.5em;\r\ \n\r\ \n type-1: type-of(1em-.75em);\r\ \n type-2: type-of(2em-1em);\r\ \n type-3: type-of(2em-0.75em);\r\ \n type-4: type-of(1.5em-1em);\r\ \n type-5: type-of(2em-1.5em);\r\ \n type-6: type-of(1a2b3c);\r\ \n\r\ \n test-1: (1-em-2-em);\r\ \n test-1: (1-em - 2-em);\r\ \n\r\ \n test-2: (1-0-em-2-0-em);\r\ \n test-2: (1-0-em - 2-0-em);\r\ \n\r\ \n test-3: (1-A-em-2-A-em);\r\ \n test-3: (1-A-em - 2-A-em);\r\ \n\r\ \n test-4: (1_em--_--e-2_em--_--e);\r\ \n test-4: (1_em--_--e - 2_em--_--e);\r\ \n\r\ \n test-5: (1_em--_--e0-2_em--_--e0);\r\ \n test-5: (1_em--_--e0 - 2_em--_--e0);\r\ \n\r\ \n test-6: (1_em--_--e0__-2_em--_--e0__);\r\ \n test-6: (1_em--_--e0__ - 2_em--_--e0__);\r\ \n\r\ \n test-7: (1\\65 _em--_--e0-2\\65 _em--_--e0);\r\ \n test-7: (1\\65 _em--_--e0 - 2\\65 _em--_--e0);\r\ \n}\r\ \n" ) .unwrap(), "div {\ \n foo: 1a2b3c;\ \n length-1: 1;\ \n unit-1: \"a2b3c\";\ \n result-1: 0.25em;\ \n result-2: 1em;\ \n result-3: 1.25em;\ \n result-4: 0.5em;\ \n result-5: 0.5em;\ \n type-1: number;\ \n type-2: number;\ \n type-3: number;\ \n type-4: number;\ \n type-5: number;\ \n type-6: number;\ \n test-1: -1-em;\ \n test-1: -1-em;\ \n test-2: -1-em;\ \n test-2: -1-em;\ \n test-3: -1-A-em;\ \n test-3: -1-A-em;\ \n test-4: -1_em--_--e;\ \n test-4: -1_em--_--e;\ \n test-5: -1_em--_--e0;\ \n test-5: -1_em--_--e0;\ \n test-6: -1_em--_--e0__;\ \n test-6: -1_em--_--e0__;\ \n test-7: -1e_em--_--e0;\ \n test-7: -1e_em--_--e0;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1413.hrx" #[test] fn issue_1413() { assert_eq!( rsass( "div {\r\ \n foo: \'A\'#{B};\r\ \n foo: #{A}\'B\';\r\ \n foo: \'A\'#{B}\'C\';\r\ \n foo: #{A}\'B\'#{C};\r\ \n foo: A#{B}\'C\';\r\ \n foo: \'A\'#{B}C;\r\ \n foo: #{A}B\'C\';\r\ \n foo: \'A\'#{B}C\'D\';\r\ \n foo: \'A\'B#{C}D\'E\';\r\ \n foo: A\'B\'#{C}D\'E\';\r\ \n foo: #{A}\'B\'C\'D\'\'E\';\r\ \n}\r\ \n\r\ \ndiv {\r\ \n foo: type-of(\'A\'#{B});\r\ \n foo: type-of(#{A}\'B\');\r\ \n foo: type-of(\'A\'#{B}\'C\');\r\ \n foo: type-of(#{A}\'B\'#{C});\r\ \n foo: type-of(A#{B}\'C\');\r\ \n foo: type-of(\'A\'#{B}C);\r\ \n foo: type-of(#{A}B\'C\');\r\ \n foo: type-of(\'A\'#{B}C\'D\');\r\ \n foo: type-of(\'A\'B#{C}D\'E\');\r\ \n foo: type-of(A\'B\'#{C}D\'E\');\r\ \n foo: type-of(#{A}\'B\'C\'D\'\'E\');\r\ \n}\r\ \n\r\ \ndiv {\r\ \n foo: length(\'A\'#{B});\r\ \n foo: length(#{A}\'B\');\r\ \n foo: length(\'A\'#{B}\'C\');\r\ \n foo: length(#{A}\'B\'#{C});\r\ \n foo: length(A#{B}\'C\');\r\ \n foo: length(\'A\'#{B}C);\r\ \n foo: length(#{A}B\'C\');\r\ \n foo: length(\'A\'#{B}C\'D\');\r\ \n foo: length(\'A\'B#{C}D\'E\');\r\ \n foo: length(A\'B\'#{C}D\'E\');\r\ \n foo: length(#{A}\'B\'C\'D\'\'E\');\r\ \n}" ) .unwrap(), "div {\ \n foo: \"A\" B;\ \n foo: A \"B\";\ \n foo: \"A\" B \"C\";\ \n foo: A \"B\" C;\ \n foo: AB \"C\";\ \n foo: \"A\" BC;\ \n foo: AB \"C\";\ \n foo: \"A\" BC \"D\";\ \n foo: \"A\" BCD \"E\";\ \n foo: A \"B\" CD \"E\";\ \n foo: A \"B\" C \"D\" \"E\";\ \n}\ \ndiv {\ \n foo: list;\ \n foo: list;\ \n foo: list;\ \n foo: list;\ \n foo: list;\ \n foo: list;\ \n foo: list;\ \n foo: list;\ \n foo: list;\ \n foo: list;\ \n foo: list;\ \n}\ \ndiv {\ \n foo: 2;\ \n foo: 2;\ \n foo: 3;\ \n foo: 3;\ \n foo: 2;\ \n foo: 2;\ \n foo: 2;\ \n foo: 3;\ \n foo: 3;\ \n foo: 4;\ \n foo: 5;\ \n}\ \n" ); } mod issue_1415; // From "sass-spec/spec/libsass-closed-issues/issue_1417.hrx" #[test] #[ignore] // wrong result fn issue_1417() { assert_eq!( rsass( "@function foo($a, $b) {\ \n @return ($a $b);\ \n}\ \n\ \nfoo {\ \n foo: 1px / 2px;\ \n foo: 1px / round(1.5);\ \n foo: foo(1px / 2px, 1px / round(1.5));\ \n foo: missing(1px / 2px, 1px / round(1.5));\ \n foo: call(missing, 1px / 2px, 1px / round(1.5));\ \n}\ \n" ) .unwrap(), "foo {\ \n foo: 1px/2px;\ \n foo: 0.5px;\ \n foo: 0.5 0.5px;\ \n foo: missing(1px/2px, 0.5px);\ \n foo: missing(1px/2px, 0.5px);\ \n}\ \n" ); } mod issue_1418; mod issue_1419; // From "sass-spec/spec/libsass-closed-issues/issue_1422.hrx" #[test] #[ignore] // wrong result fn issue_1422() { assert_eq!( rsass( ".foo {\ \n /*foo*/foo/*foo*/: /*foo*/bar/*foo*/;\ \n /*foo*/ foo /*foo*/ : /*foo*/ bar /*foo*/;\ \n}\ \n" ) .unwrap(), ".foo {\ \n /*foo*/\ \n foo/*foo*/: bar;\ \n /*foo*/\ \n foo: bar;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_143.hrx" #[test] fn issue_143() { assert_eq!( rsass( "$path: \"images\";\ \n$file: \"kittens.jpg\";\ \n$image: \"\";\ \n$other: file_join(\"images\", \"kittens.jpg\");\ \n\ \n@if $image != none {\ \n\t$image: url(file_join($path, $file));\ \n}\ \nbody {\ \n\tbackground: $image;\ \n\tcolor: $other;\ \n}\ \n" ) .unwrap(), "body {\ \n background: url(file_join(\"images\", \"kittens.jpg\"));\ \n color: file_join(\"images\", \"kittens.jpg\");\ \n}\ \n" ); } mod issue_1432; // From "sass-spec/spec/libsass-closed-issues/issue_1434.hrx" #[test] fn issue_1434() { assert_eq!( rsass( ".foo {\ \n a: selector-nest(\'.foo\', \'.bar > .baz\');\ \n b: selector-nest(\'.foo\', \'.bar ~ .baz\');\ \n c: selector-nest(\'.foo\', \'.bar + .baz\');\ \n d: selector-nest(\'.foo > .bar\', \'.baz\');\ \n e: selector-nest(\'.foo ~ .bar\', \'.baz\');\ \n f: selector-nest(\'.foo + .bar\', \'.baz\');\ \n}\ \n" ) .unwrap(), ".foo {\ \n a: .foo .bar > .baz;\ \n b: .foo .bar ~ .baz;\ \n c: .foo .bar + .baz;\ \n d: .foo > .bar .baz;\ \n e: .foo ~ .bar .baz;\ \n f: .foo + .bar .baz;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1437.hrx" #[test] fn issue_1437() { assert_eq!( rsass( "div {\r\ \n\r\ \n @media screen and (min-width: 37.5em) {\r\ \n /* asd */\r\ \n }\r\ \n\r\ \n @media screen and (min-width: 48em) {\r\ \n display: none;\r\ \n }\r\ \n}" ) .unwrap(), "@media screen and (min-width: 37.5em) {\ \n div {\ \n /* asd */\ \n }\ \n}\ \n@media screen and (min-width: 48em) {\ \n div {\ \n display: none;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1438.hrx" #[test] fn issue_1438() { assert_eq!( rsass( "@function foo() {\ \n @return 20150812;\ \n}\ \n\ \nfoo {\ \n background-image: url(../test.png);\ \n}\ \n\ \nbar {\ \n background-image: url(../test.png?v=20150812);\ \n}\ \n\ \nbaz {\ \n background-image: url(../test.png?v=#{test()});\ \n}\ \n\ \nbam {\ \n background-image: url(\"../test.png?v=#{test()}\");\ \n}\ \n" ) .unwrap(), "foo {\ \n background-image: url(../test.png);\ \n}\ \nbar {\ \n background-image: url(../test.png?v=20150812);\ \n}\ \nbaz {\ \n background-image: url(../test.png?v=test());\ \n}\ \nbam {\ \n background-image: url(\"../test.png?v=test()\");\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1440.hrx" #[test] fn issue_1440() { assert_eq!( rsass( "// works fine with plain @each directive\r\ \n$i: 1;\r\ \n$prop1: width;\r\ \n$prop2: background-position;\r\ \n$values: 132px,\r\ \n 100px \"-100px -25px\",\r\ \n 200px \"-500px -100px\";\r\ \n\r\ \n@each $value1, $value2 in $values{\r\ \n .okay#{$i} {\r\ \n #{$prop1}: #{$value1};\r\ \n #{$prop2}: #{$value2};\r\ \n }\r\ \n $i: ($i + 1);\r\ \n}\r\ \n\r\ \n// when using @each inside @mixin with variable arguments($values...),\r\ \n// $value2 is missing and no errors while compiling\r\ \n@mixin eachProp($prop1, $prop2, $values...){\r\ \n $i: 1;\r\ \n @each $value1, $value2 in $values{\r\ \n .error#{$i} {\r\ \n #{$prop1}: #{$value1};\r\ \n #{$prop2}: #{$value2};\r\ \n }\r\ \n $i: ($i + 1);\r\ \n }\r\ \n}\r\ \n\r\ \n@include eachProp($prop1, $prop2,\r\ \n 132px,\r\ \n 100px \"-100px -25px\",\r\ \n 200px \"-500px -100px\"\r\ \n);" ) .unwrap(), ".okay1 {\ \n width: 132px;\ \n}\ \n.okay2 {\ \n width: 100px;\ \n background-position: -100px -25px;\ \n}\ \n.okay3 {\ \n width: 200px;\ \n background-position: -500px -100px;\ \n}\ \n.error1 {\ \n width: 132px;\ \n}\ \n.error2 {\ \n width: 100px;\ \n background-position: -100px -25px;\ \n}\ \n.error3 {\ \n width: 200px;\ \n background-position: -500px -100px;\ \n}\ \n" ); } mod issue_1441; // From "sass-spec/spec/libsass-closed-issues/issue_1448.hrx" #[test] fn issue_1448() { assert_eq!( rsass( ".md-card\r\ \n{\r\ \n .md-info-card-highlight\r\ \n {\r\ \n background: red;\r\ \n color: blue;\r\ \n\r\ \n .ng-md-icon\r\ \n {\r\ \n color: green;\r\ \n }\r\ \n }\r\ \n}" ) .unwrap(), ".md-card .md-info-card-highlight {\ \n background: red;\ \n color: blue;\ \n}\ \n.md-card .md-info-card-highlight .ng-md-icon {\ \n color: green;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1452.hrx" // Ignoring "issue_1452", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1459.hrx" #[test] fn issue_1459() { assert_eq!( rsass( "@font-face {\r\ \n font-family: \"Font Name\";\r\ \n src: local(\"Arial\");\r\ \n unicode-range: U+270C;\r\ \n}" ) .unwrap(), "@font-face {\ \n font-family: \"Font Name\";\ \n src: local(\"Arial\");\ \n unicode-range: U+270C;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1482.hrx" #[test] #[ignore] // wrong result fn issue_1482() { assert_eq!( rsass( ".mango {\ \n color: red;\ \n}\ \n\ \ntype {\ \n &__else {\ \n @extend .mango;\ \n }\ \n}\ \n\ \n.qualified {\ \n &__else {\ \n @extend .mango;\ \n }\ \n}\ \n" ) .unwrap(), ".mango, .qualified__else, type__else {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1484.hrx" // Ignoring "issue_1484", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1486.hrx" #[test] fn issue_1486() { assert_eq!( rsass( "$a: 41px;\ \n\ \n@function a() {\ \n @return 42px;\ \n}\ \n\ \nfoo {\ \n foo: $a -121px;\ \n foo: ($a -122px);\ \n foo: $a*3-123px;\ \n foo: ($a*3-124px);\ \n foo: $a*3 -123px;\ \n foo: ($a*3 -124px);\ \n foo: $a*3 - 123px;\ \n foo: ($a*3 - 124px);\ \n foo: $a*3- 123px;\ \n foo: ($a*3- 124px);\ \n foo: $a*3- 123px;\ \n foo: ($a*3- 124px);\ \n}\ \n\ \nbar {\ \n bar: a() -121px;\ \n bar: (a() -122px);\ \n bar: a()*3-123px;\ \n bar: (a()*3-124px);\ \n bar: a()*3 -123px;\ \n bar: (a()*3 -124px);\ \n bar: a()*3 - 123px;\ \n bar: (a()*3 - 124px);\ \n bar: a()*3- 123px;\ \n bar: (a()*3- 124px);\ \n bar: a()*3- 123px;\ \n bar: (a()*3- 124px);\ \n}\ \n\ \nbaz {\ \n baz: 43px -121px;\ \n baz: (43px -122px);\ \n baz: 43px*3-123px;\ \n baz: (43px*3-124px);\ \n baz: 43px*3 -123px;\ \n baz: (43px*3 -124px);\ \n baz: 43px*3 - 123px;\ \n baz: (43px*3 - 124px);\ \n baz: 43px*3- 123px;\ \n baz: (43px*3- 124px);\ \n baz: 43px*3- 123px;\ \n baz: (43px*3- 124px);\ \n}\ \n" ) .unwrap(), "foo {\ \n foo: 41px -121px;\ \n foo: 41px -122px;\ \n foo: 0px;\ \n foo: -1px;\ \n foo: 123px -123px;\ \n foo: 123px -124px;\ \n foo: 0px;\ \n foo: -1px;\ \n foo: 0px;\ \n foo: -1px;\ \n foo: 0px;\ \n foo: -1px;\ \n}\ \nbar {\ \n bar: 42px -121px;\ \n bar: 42px -122px;\ \n bar: 3px;\ \n bar: 2px;\ \n bar: 126px -123px;\ \n bar: 126px -124px;\ \n bar: 3px;\ \n bar: 2px;\ \n bar: 3px;\ \n bar: 2px;\ \n bar: 3px;\ \n bar: 2px;\ \n}\ \nbaz {\ \n baz: 43px -121px;\ \n baz: 43px -122px;\ \n baz: 6px;\ \n baz: 5px;\ \n baz: 129px -123px;\ \n baz: 129px -124px;\ \n baz: 6px;\ \n baz: 5px;\ \n baz: 6px;\ \n baz: 5px;\ \n baz: 6px;\ \n baz: 5px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1487.hrx" // Ignoring "issue_1487", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1488.hrx" #[test] #[ignore] // wrong result fn issue_1488() { assert_eq!( rsass( "@function foo($arg2) {\ \n @return type-of($arg2);\ \n}\ \n\ \n@function foo_($arg2...) {\ \n @return type-of($arg2);\ \n}\ \n\ \n@function bar($arg1, $arg2) {\ \n @return type-of($arg1) + \"::\" + type-of($arg2);\ \n}\ \n\ \n@function bar_($arg1, $arg2...) {\ \n @return type-of($arg1) + \"::\" + type-of($arg2);\ \n}\ \n\ \nfoo {\ \n foo: foo(one);\ \n foo: foo(one...);\ \n bar: bar(one, two);\ \n bar: bar(one, two...);\ \n foo: call(\'foo\', one);\ \n foo: call(\'foo\', one...);\ \n bar: call(\'bar\', one, two);\ \n bar: call(\'bar\', one, two...);\ \n}\ \n\ \nbar {\ \n foo: foo_(one);\ \n foo: foo_(one...);\ \n bar: bar_(one, two);\ \n bar: bar_(one, two...);\ \n foo: call(\'foo_\', one);\ \n foo: call(\'foo_\', one...);\ \n bar: call(\'bar_\', one, two);\ \n bar: call(\'bar_\', one, two...);\ \n}" ) .unwrap(), "foo {\ \n foo: string;\ \n foo: string;\ \n bar: string::string;\ \n bar: string::string;\ \n foo: string;\ \n foo: string;\ \n bar: string::string;\ \n bar: string::string;\ \n}\ \nbar {\ \n foo: arglist;\ \n foo: arglist;\ \n bar: string::arglist;\ \n bar: string::arglist;\ \n foo: arglist;\ \n foo: arglist;\ \n bar: string::arglist;\ \n bar: string::arglist;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_151.hrx" // Ignoring "issue_151", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_152.hrx" // Ignoring "issue_152", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1526.hrx" #[test] #[ignore] // wrong result fn issue_1526() { assert_eq!( rsass( "foo {\ \n bar: (1--em-2--em);\ \n baz: (1--em - 2--em);\ \n}\ \n" ) .unwrap(), "foo {\ \n bar: 1 --em-2--em;\ \n baz: 1 --em-2 --em;\ \n}\ \n" ); } mod issue_1527; // From "sass-spec/spec/libsass-closed-issues/issue_1535.hrx" #[test] #[ignore] // wrong result fn issue_1535() { assert_eq!( rsass( "foo {\ \n test: type-of(1--em);\ \n test: (1--em-2--em);\ \n test: (1--em- 2--em);\ \n test: (1--em -2--em);\ \n}\ \n" ) .unwrap(), "foo {\ \n test: list;\ \n test: 1 --em-2--em;\ \n test: 1 --em- 2 --em;\ \n test: 1 --em -2 --em;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1537.hrx" // Ignoring "issue_1537", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_154.hrx" #[test] fn issue_154() { assert_eq!( rsass( "test {\r\ \n filter:alpha(opacity=75);\r\ \n}" ) .unwrap(), "test {\ \n filter: alpha(opacity=75);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1546.hrx" mod issue_1550; // From "sass-spec/spec/libsass-closed-issues/issue_1557.hrx" #[test] #[ignore] // wrong result fn issue_1557() { assert_eq!( rsass( "$xs-break: 30em;@media ALL AND (max-width: $xs-break) {header {display: none;}}\ \n" ) .unwrap(), "@media ALL and (max-width: 30em) {\ \n header {\ \n display: none;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1566.hrx" #[test] #[ignore] // wrong result fn issue_1566() { assert_eq!( rsass( "@function foo($predicate) {\ \n @return call(\'bar\', $predicate);\ \n}\ \n\ \n@function bar($predicate) {\ \n @return type-of($predicate);\ \n}\ \n\ \ntest {\ \n test: foo(1 2 3);\ \n}\ \n" ) .unwrap(), "test {\ \n test: list;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1567.hrx" #[test] #[ignore] // unexepected error fn issue_1567() { assert_eq!( rsass( "/* any */@media/* first */\ \n/* screen */screen /*something */ , /* else */\ \n/* not */not/* print */print /* final */ { /* whatever */\ \n body { line-height: 1.2 }\ \n}\ \n" ) .unwrap(), "/* any */\ \n@media screen, not print {\ \n /* whatever */\ \n body {\ \n line-height: 1.2;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1568.hrx" #[test] fn issue_1568() { assert_eq!( rsass( "body {\ \n font-weight: bold; // test\ \n font-size: 10px // test\ \n}\ \n" ) .unwrap(), "body {\ \n font-weight: bold;\ \n font-size: 10px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1569.hrx" // Ignoring "issue_1569", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1570.hrx" #[test] fn issue_1570() { assert_eq!( rsass( "a {\ \n font: 12px/normal serif;\ \n}\ \n\ \nb {\ \n font: normal 12px/normal serif;\ \n}\ \n" ) .unwrap(), "a {\ \n font: 12px/normal serif;\ \n}\ \nb {\ \n font: normal 12px/normal serif;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1574.hrx" #[test] #[ignore] // wrong result fn issue_1574() { assert_eq!( rsass( ".foo {\ \n bar: baz;\ \n}\ \n\ \ninput[type=\"text\"],\ \ninput[type=\"search\"],\ \ninput[type=\"url\"],\ \ninput[type=\"email\"],\ \ninput[type=\"password\"],\ \ninput[type=\"number\"],\ \ninput[type=\"tel\"],\ \ninput[type=\"date\"],\ \ninput[type=\"range\"],\ \ntextarea {\ \n @extend .foo;\ \n}\ \n" ) .unwrap(), ".foo, input[type=text],\ \ninput[type=search],\ \ninput[type=url],\ \ninput[type=email],\ \ninput[type=password],\ \ninput[type=number],\ \ninput[type=tel],\ \ninput[type=date],\ \ninput[type=range],\ \ntextarea {\ \n bar: baz;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1577.hrx" // Ignoring "issue_1577", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1578.hrx" // From "sass-spec/spec/libsass-closed-issues/issue_1579.hrx" #[test] #[ignore] // wrong result fn issue_1579() { assert_eq!( rsass( "@function foo($a, $b: null, $c: false) {\ \n @return $c;\ \n}\ \n\ \n@function bar($args...) {\ \n @return call(foo, $args...);\ \n}\ \n\ \ntest {\ \n test: bar(3, $c: true);\ \n}\ \n" ) .unwrap(), "test {\ \n test: true;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1583.hrx" #[test] #[ignore] // wrong result fn issue_1583() { assert_eq!( rsass( "$ls: ((foo,));\ \n\ \nfoo {\ \n baz: length($ls);\ \n baz: type-of($ls);\ \n baz: inspect($ls);\ \n}\ \n\ \nbar {\ \n baz: length(&);\ \n baz: type-of(&);\ \n baz: inspect(&);\ \n}\ \n\ \nfoo {\ \n string: inspect(&);\ \n str-length: str-length(inspect(&));\ \n list-length: length(&);\ \n}\ \n\ \nfoo, bar {\ \n string: inspect(&);\ \n str-length: str-length(inspect(&));\ \n list-length: length(&);\ \n}\ \n" ) .unwrap(), "foo {\ \n baz: 1;\ \n baz: list;\ \n baz: (foo,);\ \n}\ \nbar {\ \n baz: 1;\ \n baz: list;\ \n baz: (bar,);\ \n}\ \nfoo {\ \n string: (foo,);\ \n str-length: 6;\ \n list-length: 1;\ \n}\ \nfoo, bar {\ \n string: foo, bar;\ \n str-length: 8;\ \n list-length: 2;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1584.hrx" #[test] fn issue_1584() { assert_eq!( rsass( "@mixin foo($out: false) {\ \n @if $out {\ \n @at-root { @content; }\ \n }\ \n}\ \n\ \n@mixin bar() {\ \n @at-root { @content; }\ \n}\ \n\ \n@mixin baz($string) {\ \n @at-root .#{$string} { @content; }\ \n}\ \n\ \n.test {\ \n @include foo(true) {\ \n .nest1 {\ \n color: red;\ \n }\ \n }\ \n @include bar() {\ \n .nest2 {\ \n color: green;\ \n }\ \n }\ \n @include baz(\'nest3\') {\ \n color: blue;\ \n }\ \n @at-root {\ \n .nest4 {\ \n color: yellow;\ \n }\ \n }\ \n}\ \n" ) .unwrap(), ".nest1 {\ \n color: red;\ \n}\ \n.nest2 {\ \n color: green;\ \n}\ \n.nest3 {\ \n color: blue;\ \n}\ \n.nest4 {\ \n color: yellow;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1585.hrx" // Ignoring "issue_1585", error tests are not supported yet. mod issue_1590; // From "sass-spec/spec/libsass-closed-issues/issue_1596.hrx" #[test] #[ignore] // wrong result fn issue_1596() { assert_eq!( rsass( "@document url(http://www.w3.org/),\ \n url-prefix(http://www.w3.org/Style/),\ \n domain(mozilla.org),\ \n regexp(\"https:.*\");\ \n" ) .unwrap(), "@document url(http://www.w3.org/),\ \n url-prefix(http://www.w3.org/Style/),\ \n domain(mozilla.org),\ \n regexp(\"https:.*\");\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1601.hrx" // Ignoring "issue_1601", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1604.hrx" #[test] #[ignore] // wrong result fn issue_1604() { assert_eq!( rsass( "@function test($args...) {\ \n $all: ();\ \n\ \n @each $arg in $args {\ \n $all: append($all, $arg);\ \n }\ \n\ \n @return inspect($all);\ \n}\ \n\ \ntest {\ \n args-1: test(1 2 3);\ \n args-2: test(1 2, 3 4);\ \n args-3: test(1, 2, 3);\ \n}\ \n" ) .unwrap(), "test {\ \n args-1: (1 2 3);\ \n args-2: (1 2) (3 4);\ \n args-3: 1 2 3;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1610.hrx" #[test] fn issue_1610() { assert_eq!( rsass( "@function foo() {\ \n @return \"bar\";\ \n}\ \n\ \n@function bar() {\ \n @return \"foo\" + \",\" + bar;\ \n}\ \n\ \na {\ \n b: foo(), \"bar\";\ \n b: foo(), \"bar\"\ \n}\ \n\ \nb {\ \n b: #{foo(), \"bar\"};\ \n b: #{foo(), \"bar\"}\ \n}\ \n\ \nc {\ \n b: \"foo\", bar;\ \n}\ \n\ \nd {\ \n b: #{\"foo\", bar};\ \n b: #{\"foo\", bar}\ \n}\ \n\ \ne {\ \n b: #{bar()};\ \n b: #{bar()}\ \n}\ \n\ \nf {\ \n b: \"foo\" + \",\" + bar;\ \n b: \"foo\" + \",\" + bar\ \n}\ \n" ) .unwrap(), "a {\ \n b: \"bar\", \"bar\";\ \n b: \"bar\", \"bar\";\ \n}\ \nb {\ \n b: bar, bar;\ \n b: bar, bar;\ \n}\ \nc {\ \n b: \"foo\", bar;\ \n}\ \nd {\ \n b: foo, bar;\ \n b: foo, bar;\ \n}\ \ne {\ \n b: foo,bar;\ \n b: foo,bar;\ \n}\ \nf {\ \n b: \"foo,bar\";\ \n b: \"foo,bar\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1612.hrx" #[test] fn issue_1612() { assert_eq!( rsass( "c {\ \n b: \"foo\", bar;\ \n b: \"foo\", bar\ \n}\ \n" ) .unwrap(), "c {\ \n b: \"foo\", bar;\ \n b: \"foo\", bar;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1622.hrx" #[test] #[ignore] // wrong result fn issue_1622() { assert_eq!( rsass( "@function foo($list) {\ \n @return call(bar, $list);\ \n}\ \n\ \n@function bar($list, $args...) {\ \n @return length($list);\ \n}\ \n\ \ntest {\ \n test: foo(1 2 3);\ \n}\ \n" ) .unwrap(), "test {\ \n test: 3;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1624.hrx" #[test] fn issue_1624() { assert_eq!( rsass( "@function foo($foo) {\ \n @return $foo;\ \n}\ \n\ \n@function data($foo) {\ \n @return \'[data-\' + $foo + \']\';\ \n}\ \n\ \n#{foo(foo)} {\ \n #{data(\'bar\')} {\ \n baz: bam;\ \n }\ \n}\ \n" ) .unwrap(), "foo [data-bar] {\ \n baz: bam;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1629.hrx" #[test] fn issue_1629() { assert_eq!( rsass( "foo {\ \n background: url(...) 2rem 3rem / auto 2rem;\ \n}\ \n" ) .unwrap(), "foo {\ \n background: url(...) 2rem 3rem/auto 2rem;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1632.hrx" #[test] fn issue_1632() { assert_eq!( rsass( "$foo: \\/ !global;\ \n.foo#{$foo}bar { a: b; }\ \n" ) .unwrap(), ".foo\\/bar {\ \n a: b;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1634.hrx" #[test] fn issue_1634() { assert_eq!( rsass( "$empty-list: ();\ \n\ \n@function foo($args...) {\ \n @return call(bar, $args...);\ \n}\ \n\ \n@function bar($list) {\ \n @return length($list);\ \n}\ \n\ \ntest {\ \n test: foo($empty-list);\ \n}" ) .unwrap(), "test {\ \n test: 0;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1640.hrx" #[test] #[ignore] // unexepected error fn issue_1640() { assert_eq!( rsass( "@mixin foo() {\ \n @if false {\ \n a { b: c }\ \n } @else {\ \n @content;\ \n }\ \n}\ \n\ \n@include foo() {\ \n .foo {\ \n bar: baz;\ \n }\ \n}\ \n" ) .unwrap(), ".foo {\ \n bar: baz;\ \n}\ \n" ); } mod issue_1644; // From "sass-spec/spec/libsass-closed-issues/issue_1645.hrx" #[test] #[ignore] // wrong result fn issue_1645() { assert_eq!( rsass( "@function foo($a, $should-be-empty...) {\ \n @return length($should-be-empty);\ \n}\ \n\ \n@function bar($args...) {\ \n @return call(foo, $args...);\ \n}\ \n\ \n@function args($args...) {\ \n @return $args;\ \n}\ \n\ \n$a: args(1, 2, 3);\ \n\ \ntest {\ \n test: bar($a);\ \n}\ \n" ) .unwrap(), "test {\ \n test: 0;\ \n}\ \n" ); } mod issue_1647; // From "sass-spec/spec/libsass-closed-issues/issue_1648.hrx" #[test] #[ignore] // wrong result fn issue_1648() { assert_eq!( rsass( "$x: 3px;\ \n/* comment 1 */\ \n@if/* pre 1 */$x == 3px/* post 1 */{\ \n /* if 1 */\ \n}\ \n/* comment 2 */\ \n@elseif/* pre 2 */$x == 2px/* post 2 */{\ \n /* else if 2 */\ \n}\ \n/* comment 3 */\ \n@else/* middle 3 */if/* pre 3 */$x == 3px/* post 3 */{\ \n /* else if 3 */\ \n}\ \n/* comment 4 */\ \n@else/* post 4 */{\ \n /* else 4 */\ \n}\ \n/* comment 5 */" ) .unwrap(), "/* comment 1 */\ \n/* if 1 */\ \n/* comment 5 */\ \n" ); } mod issue_1650; mod issue_1651; mod issue_1654; // From "sass-spec/spec/libsass-closed-issues/issue_1658.hrx" // Ignoring "issue_1658", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1667.hrx" #[test] fn issue_1667() { assert_eq!( rsass( "$map: (\r\ \n 1: 1,\r\ \n 1px: 1px\r\ \n);\r\ \n\r\ \nfoo {\r\ \n a: map-get($map, 1);\r\ \n b: map-get($map, 1px);\r\ \n}\r\ \n\r\ \n$type-scale: (\r\ \n\t-15:0.066667rem,\r\ \n\t-10:0.186rem,\r\ \n\t-9:0.211rem,\r\ \n\t-8:0.26rem,\r\ \n\t-7:0.295rem,\r\ \n\t-6:0.364rem,\r\ \n\t-5:0.413rem,\r\ \n\t-4:0.51rem,\r\ \n\t-3:0.578rem,\r\ \n\t-2:0.714rem,\r\ \n\t-1:0.809rem,\r\ \n\t0:1rem,\r\ \n\t1:1.133rem,\r\ \n\t2:1.4rem,\r\ \n\t3:1.586rem,\r\ \n\t4:1.96rem,\r\ \n\t5:2.221rem,\r\ \n\t6:2.744rem,\r\ \n\t7:3.109rem,\r\ \n\t8:3.842rem,\r\ \n\t9:4.353rem,\r\ \n\t10:5.378rem,\r\ \n\t11:6.094rem,\r\ \n\t12:7.53rem,\r\ \n\t13:8.531rem,\r\ \n\t14:10.541rem,\r\ \n\t15:11.943rem,\r\ \n\t16:14.758rem\r\ \n);\r\ \n\r\ \n@function get-size($size) {\r\ \n\t@if map-has-key($type-scale, $size) {\r\ \n\t\t@return map-get($type-scale, $size);\r\ \n\t}\r\ \n\r\ \n\t@warn \"Not a valid size.\";\r\ \n\t@return null;\r\ \n}\r\ \n\r\ \n@function scale-size($rem-size, $steps) {\r\ \n\t$size-key: get-key-for-value($type-scale, $rem-size);\r\ \n\r\ \n\t@if $size-key {\r\ \n\t\t$new-size: $size-key + $steps;\r\ \n\t\t@return get-size($new-size);\r\ \n\t}\r\ \n\r\ \n\t@warn \"Not able to find size for \" + $rem-size;\r\ \n\t@return null;\r\ \n}\r\ \n\r\ \n@function get-key-for-value($map, $value) {\r\ \n\t@each $map-key, $map-value in $map {\r\ \n\t\t@if $map-value == $value {\r\ \n\t\t\t@return $map-key\r\ \n\t\t}\r\ \n\t}\r\ \n\r\ \n\t@warn $value + \" not found in \" + $map;\r\ \n\t@return null;\r\ \n}\r\ \n\r\ \n$h1-font-size: get-size(5);\r\ \n\r\ \n\r\ \nh1 {\r\ \n font-size: $h1-font-size;\r\ \n\r\ \n small {\r\ \n font-size: scale-size($h1-font-size, -2);\r\ \n color: red;\r\ \n }\r\ \n}\r\ \n\r\ \n" ) .unwrap(), "foo {\ \n a: 1;\ \n b: 1px;\ \n}\ \nh1 {\ \n font-size: 2.221rem;\ \n}\ \nh1 small {\ \n font-size: 1.586rem;\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1669.hrx" #[test] fn issue_1669() { assert_eq!( rsass( "foo {\ \n bar: #{100%/3}\ \n}\ \n\ \n" ) .unwrap(), "foo {\ \n bar: 100%/3;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_167.hrx" #[test] #[ignore] // wrong result fn issue_167() { assert_eq!( rsass( "%l-cell, .l-cell {\r\ \n margin: 0 auto;\r\ \n max-width: 1000px;\r\ \n}" ) .unwrap(), ".l-cell {\ \n margin: 0 auto;\ \n max-width: 1000px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1670.hrx" // Ignoring "issue_1670", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1671.hrx" #[test] fn issue_1671() { assert_eq!( rsass( "$foo: 5px;\ \na {\ \n background: url(\'img.png\') no-repeat 6px 0 / #{$foo};\ \n background: url(\'img.png\') no-repeat 6px 1 / #{$foo};\ \n background: url(\'img.png\') no-repeat 6px 1px / #{$foo};\ \n background: url(\'img.png\') no-repeat 6px #{$foo} / 0;\ \n background: url(\'img.png\') no-repeat 6px #{$foo} / 1;\ \n background: url(\'img.png\') no-repeat 6px #{$foo} / 1px;\ \n}\ \n" ) .unwrap(), "a {\ \n background: url(\"img.png\") no-repeat 6px 0/5px;\ \n background: url(\"img.png\") no-repeat 6px 1/5px;\ \n background: url(\"img.png\") no-repeat 6px 1px/5px;\ \n background: url(\"img.png\") no-repeat 6px 5px/0;\ \n background: url(\"img.png\") no-repeat 6px 5px/1;\ \n background: url(\"img.png\") no-repeat 6px 5px/1px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1672.hrx" #[test] fn issue_1672() { assert_eq!( rsass( "$breakpoint: \'tablet\';\ \n\ \n.-#{$breakpoint} {\ \n color: #FFF;\ \n}" ) .unwrap(), ".-tablet {\ \n color: #FFF;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1673.hrx" #[test] #[ignore] // wrong result fn issue_1673() { assert_eq!( rsass( "%foo {\ \n test: outer;\ \n\ \n &-inner {\ \n test: inner;\ \n }\ \n}\ \n\ \n.foo {\ \n @extend %foo;\ \n\ \n &.inner { @extend %foo-inner; }\ \n}" ) .unwrap(), ".foo {\ \n test: outer;\ \n}\ \n.foo.inner {\ \n test: inner;\ \n}\ \n" ); } mod issue_1681; mod issue_1683; // From "sass-spec/spec/libsass-closed-issues/issue_1685.hrx" #[test] fn issue_1685() { assert_eq!( rsass( "@function foo($x, $y...) { @return null }\ \n\ \na {\ \n b: foo(1 2 3...);\ \n}" ) .unwrap(), "" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1706.hrx" #[test] fn issue_1706() { assert_eq!( rsass( "@function calc($e) { @return custom; }\ \n@function -foo-calc($e) { @return custom; }\ \n\ \n.test {\ \n a: calc(1px * 1%);\ \n b: -foo-calc(2px * 2%);\ \n c: call(calc, 3px * 3%);\ \n}\ \n" ) .unwrap(), ".test {\ \n a: calc(1px * 1%);\ \n b: -foo-calc(2px * 2%);\ \n c: custom;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1709.hrx" #[test] #[ignore] // wrong result fn issue_1709() { assert_eq!( rsass( "@mixin transition( $prefix_properties, $transitions... ) {\ \n\ \n @if not str-index( inspect( $transitions ), \',\') {\ \n $transitions: ( $transitions );\ \n }\ \n\ \n @each $prefix in -webkit-, -moz-, -ms-, -o-, \'\' {\ \n\ \n $prefixed: \'\';\ \n\ \n @each $transition in $transitions {\ \n\ \n @if $prefix_properties and \'\' != $prefix {\ \n $prefixed: #{$prefix}$transition,$transition;\ \n } @else {\ \n $prefixed: $transition;\ \n }\ \n\ \n\ \n }\ \n\ \n #{$prefix}transition: $prefixed;\ \n }\ \n}\ \n\ \n.my-element {\ \n @include transition( true, transform 0.25s linear );\ \n}\ \n" ) .unwrap(), ".my-element {\ \n -webkit-transition: -webkit- transform 0.25s linear, transform 0.25s linear;\ \n -moz-transition: -moz- transform 0.25s linear, transform 0.25s linear;\ \n -ms-transition: -ms- transform 0.25s linear, transform 0.25s linear;\ \n -o-transition: -o- transform 0.25s linear, transform 0.25s linear;\ \n transition: transform 0.25s linear;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1710.hrx" #[test] #[ignore] // wrong result fn issue_1710() { assert_eq!( rsass( "ul, ol {\ \n & & {\ \n display: block;\ \n }\ \n }\ \n" ) .unwrap(), "ul ul, ul ol, ol ul, ol ol {\ \n display: block;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1715.hrx" // Ignoring "issue_1715", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1720.hrx" // Ignoring "issue_1720", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1722.hrx" #[test] fn issue_1722() { assert_eq!( rsass( "$score: (item-height: 1.12em);\ \n.test {\ \n background-position: 0 -#{map-get($score, item-height)};\ \n}\ \n\ \n" ) .unwrap(), ".test {\ \n background-position: 0 -1.12em;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1723.hrx" #[test] #[ignore] // wrong result fn issue_1723() { assert_eq!( rsass( "test-1 test-2 test-3 test-4 test-5,\r\ \ntest-6 test-7 test-8 test-9 test-10 {\r\ \n @each $set in & {\r\ \n set: inspect($set);\r\ \n\r\ \n @each $selector in $set {\r\ \n selector: inspect($selector);\r\ \n }\r\ \n }\r\ \n}\r\ \n\r\ \ntest-1 test-2 test-3 test-4 test-5,\r\ \ntest-6 test-7 test-8 test-9 test-10 {\r\ \n @for $i from 1 through length(&) {\r\ \n $set: nth(&, $i);\r\ \n set: inspect($set);\r\ \n\r\ \n @each $selector in $set {\r\ \n selector: inspect($selector);\r\ \n }\r\ \n }\r\ \n}" ) .unwrap(), "test-1 test-2 test-3 test-4 test-5,\ \ntest-6 test-7 test-8 test-9 test-10 {\ \n set: test-1 test-2 test-3 test-4 test-5;\ \n selector: test-1;\ \n selector: test-2;\ \n selector: test-3;\ \n selector: test-4;\ \n selector: test-5;\ \n set: test-6 test-7 test-8 test-9 test-10;\ \n selector: test-6;\ \n selector: test-7;\ \n selector: test-8;\ \n selector: test-9;\ \n selector: test-10;\ \n}\ \ntest-1 test-2 test-3 test-4 test-5,\ \ntest-6 test-7 test-8 test-9 test-10 {\ \n set: test-1 test-2 test-3 test-4 test-5;\ \n selector: test-1;\ \n selector: test-2;\ \n selector: test-3;\ \n selector: test-4;\ \n selector: test-5;\ \n set: test-6 test-7 test-8 test-9 test-10;\ \n selector: test-6;\ \n selector: test-7;\ \n selector: test-8;\ \n selector: test-9;\ \n selector: test-10;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1726.hrx" #[test] fn issue_1726() { assert_eq!( rsass( "item {\ \n background: #{2px} 2px /*red*/;\ \n}\ \n" ) .unwrap(), "item {\ \n background: 2px 2px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1729.hrx" #[test] #[ignore] // wrong result fn issue_1729() { assert_eq!( rsass( "%place-to-go {\ \n font-size: 1em;\ \n}\ \n\ \na::foo(1){\ \n @extend %place-to-go;\ \n}\ \na::foo(2){\ \n @extend %place-to-go;\ \n}\ \nb::foo(1){\ \n @extend %place-to-go;\ \n}\ \nb::foo(2){\ \n @extend %place-to-go;\ \n}\ \n\ \n:bar(1){\ \n @extend %place-to-go;\ \n}\ \n:bar(2){\ \n @extend %place-to-go;\ \n}\ \n:bar(3){\ \n @extend %place-to-go;\ \n}\ \n\ \n[foo]{\ \n @extend %place-to-go;\ \n}\ \n[bar]{\ \n @extend %place-to-go;\ \n}\ \n[baz]{\ \n @extend %place-to-go;\ \n}\ \n\ \n[bar=\"1\"]{\ \n @extend %place-to-go;\ \n}\ \n[bar=\"2\"]{\ \n @extend %place-to-go;\ \n}\ \n[bar=\"3\"]{\ \n @extend %place-to-go;\ \n}\ \n" ) .unwrap(), "[bar=\"3\"], [bar=\"2\"], [bar=\"1\"], [baz], [bar], [foo], :bar(3), :bar(2), :bar(1), b::foo(2), b::foo(1), a::foo(2), a::foo(1) {\ \n font-size: 1em;\ \n}\ \n" ); } mod issue_1732; // From "sass-spec/spec/libsass-closed-issues/issue_1733.hrx" #[test] fn issue_1733() { assert_eq!( rsass( "foo {\ \n a: #ff6600;\ \n b: #ff6600\ \n}\ \n" ) .unwrap(), "foo {\ \n a: #ff6600;\ \n b: #ff6600;\ \n}\ \n" ); } mod issue_1739; // From "sass-spec/spec/libsass-closed-issues/issue_1741.hrx" #[test] #[ignore] // wrong result fn issue_1741() { assert_eq!( rsass( ".header {\r\ \n .nav-text-link:not(&.popover-link) {\r\ \n margin: 10px;\r\ \n }\r\ \n}" ) .unwrap(), ".nav-text-link:not(.header.popover-link) {\ \n margin: 10px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1752.hrx" #[test] fn issue_1752() { assert_eq!( rsass( "@mixin some-fn($args...) {\ \n @each $item in $args {\ \n @debug($item);\ \n }\ \n}\ \n\ \nfoo {\ \n @include some-fn(());\ \n}" ) .unwrap(), "" ); } mod issue_1757; // From "sass-spec/spec/libsass-closed-issues/issue_1765.hrx" #[test] fn issue_1765() { assert_eq!( rsass( "foo {\ \n bar: 20px /* height */ + 2*5px /* padding */ + 2*1px /*border*/;\ \n}\ \n" ) .unwrap(), "foo {\ \n bar: 32px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1766.hrx" #[test] #[ignore] // unexepected error fn issue_1766() { assert_eq!( rsass( "@media all { @import \"foo.scss\" }\ \n@media all { @import \"foo.scss\"; }\ \n" ) .unwrap(), "@media all {\ \n foo {\ \n bar: baz;\ \n }\ \n}\ \n@media all {\ \n foo {\ \n bar: baz;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1768.hrx" #[test] fn issue_1768() { assert_eq!( rsass( "@debug(());\ \n@debug(foo, (), bar);\ \n@debug(foo () bar);\ \n@debug((foo: (), bar: baz));" ) .unwrap(), "" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1770.hrx" #[test] fn issue_1770() { assert_eq!( rsass( "@function returns-string() {\ \n @return \"selector\";\ \n}\ \n\ \n#{\"selector\"} {\ \n color: red;\ \n}\ \n\ \n#{returns-string()} {\ \n color: red;\ \n}\ \n\ \n#{\"selector\"} selector2 {\ \n color: red;\ \n}\ \n\ \n#{returns-string()} selector2 {\ \n color: red;\ \n}" ) .unwrap(), "selector {\ \n color: red;\ \n}\ \nselector {\ \n color: red;\ \n}\ \nselector selector2 {\ \n color: red;\ \n}\ \nselector selector2 {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1776.hrx" #[test] fn issue_1776() { assert_eq!( rsass( "h1 {\r\ \n width :calc(100% - 110px);\r\ \n}" ) .unwrap(), "h1 {\ \n width: calc(100% - 110px);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1786" #[test] #[ignore] // wrong result fn issue_1786() { assert_eq!( rsass( "$input: \"\\0_\\a_\\A\";\ \n\ \ntest {\ \n bug1: \"#{\"_\\a\" + b}\";\ \n bug2: \"#{a $input}\";\ \n}\ \n" ) .unwrap(), "@charset \"UTF-8\";\ \ntest {\ \n bug1: \"_\\a b\";\ \n bug2: \"a �_ _ \";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1792.hrx" #[test] #[ignore] // wrong result fn issue_1792() { assert_eq!( rsass( "test {\ \n test1: (3px*4in) / 1in;\ \n test2: ((1px*2in) + (3px*4in)) / 1in;\ \n}" ) .unwrap(), "test {\ \n test1: 0.125in;\ \n test2: 0.1458333333in;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1793.hrx" // Ignoring "issue_1793", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1794.hrx" #[test] #[ignore] // wrong result fn issue_1794() { assert_eq!( rsass( "@media (max-width /*comment*/ : 500px) {\ \n foo { bar: baz; }\ \n}" ) .unwrap(), "@media (max-width: 500px) {\ \n foo {\ \n bar: baz;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1796.hrx" #[test] #[ignore] // wrong result fn issue_1796() { assert_eq!( rsass( ".parent {\ \n .brother, .sister, .cousin {\ \n color: green;\ \n sel: &;\ \n\ \n $new-sel: ();\ \n @each $s in & {\ \n $last: nth($s, -1);\ \n $new-sel: append($new-sel, $s #{\'+\'} $last, comma);\ \n x: $new-sel;\ \n }\ \n @at-root #{$new-sel} {\ \n debug: foo;\ \n }\ \n }\ \n}" ) .unwrap(), ".parent .brother, .parent .sister, .parent .cousin {\ \n color: green;\ \n sel: .parent .brother, .parent .sister, .parent .cousin;\ \n x: .parent .brother + .brother;\ \n x: .parent .brother + .brother, .parent .sister + .sister;\ \n x: .parent .brother + .brother, .parent .sister + .sister, .parent .cousin + .cousin;\ \n}\ \n.parent .brother + .brother, .parent .sister + .sister, .parent .cousin + .cousin {\ \n debug: foo;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1797.hrx" #[test] #[ignore] // wrong result fn issue_1797() { assert_eq!( rsass( "%not {\ \n color: red;\ \n}\ \n.not {\ \n @extend %not;\ \n}\ \ndiv:has(%not) {\ \n color: black;\ \n}\ \n\ \nbar {\ \n span:not(%not) {\ \n color: black;\ \n }\ \n span:not(&.foo) {\ \n color: black;\ \n }\ \n span:not(&%not) {\ \n color: black;\ \n }\ \n}" ) .unwrap(), ".not {\ \n color: red;\ \n}\ \ndiv:has(.not) {\ \n color: black;\ \n}\ \nbar span:not(.not) {\ \n color: black;\ \n}\ \nspan:not(bar.foo) {\ \n color: black;\ \n}\ \nspan:not(bar.not) {\ \n color: black;\ \n}\ \n" ); } mod issue_1798; mod issue_1801; mod issue_1803; mod issue_1804; // From "sass-spec/spec/libsass-closed-issues/issue_1812.hrx" #[test] fn issue_1812() { assert_eq!( rsass( "@svg-load test url(foo.svg) {\r\ \n fill: red;\r\ \n}\r\ \n\r\ \n.foo {\r\ \n background: svg-inline(test);\r\ \n}" ) .unwrap(), "@svg-load test url(foo.svg) {\ \n fill: red;\ \n}\ \n.foo {\ \n background: svg-inline(test);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1813.hrx" #[test] fn issue_1813() { assert_eq!( rsass( "@function foo($value) {\ \n $a: bar($value);\ \n @return $value;\ \n}\ \n\ \n@function bar($list) {\ \n @while (true) {\ \n @return true;\ \n }\ \n}\ \n\ \na {\ \n b: foo(true);\ \n}\ \n" ) .unwrap(), "a {\ \n b: true;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1819.hrx" #[test] #[ignore] // wrong result fn issue_1819() { assert_eq!( rsass( "foo {\ \n bar: type-of(selector-unify(\'p\', \'a\'));\ \n}" ) .unwrap(), "foo {\ \n bar: null;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1822.hrx" // Ignoring "issue_1822", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1825.hrx" #[test] fn issue_1825() { assert_eq!( rsass( "foo {\ \n &-- {\ \n &baz {\ \n color: red;\ \n } \ \n } \ \n} " ) .unwrap(), "foo--baz {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1839.hrx" #[test] fn issue_1839() { assert_eq!( rsass("@custom-media --large-viewport (min-width: 1001px);").unwrap(), "@custom-media --large-viewport (min-width: 1001px);\ \n" ); } mod issue_185; // From "sass-spec/spec/libsass-closed-issues/issue_1873.hrx" // Ignoring "issue_1873", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1886.hrx" #[test] fn issue_1886() { assert_eq!( rsass( "body {\ \n background: url()\ \n}" ) .unwrap(), "body {\ \n background: url();\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1889.hrx" #[test] fn issue_1889() { assert_eq!( rsass( "@media (min-width: 640px) { \ \n /* comment */\ \n}\ \n\ \ndiv {\ \n @media (min-width: 320px) { \ \n /* comment */\ \n }\ \n}" ) .unwrap(), "@media (min-width: 640px) {\ \n /* comment */\ \n}\ \n@media (min-width: 320px) {\ \n div {\ \n /* comment */\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1890.hrx" #[test] #[ignore] // unexepected error fn issue_1890() { assert_eq!( rsass( ".wrap {\ \n @media (min-width: 480px) { \ \n display: block;\ \n @at-root (without: media){ \ \n .box { \ \n display: inline-block;\ \n }\ \n } \ \n }\ \n}" ) .unwrap(), "@media (min-width: 480px) {\ \n .wrap {\ \n display: block;\ \n }\ \n}\ \n.wrap .box {\ \n display: inline-block;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1898.hrx" #[test] fn issue_1898() { assert_eq!( rsass( "@media (min-width: 640px) { \ \n /* comment */\ \n}\ \n\ \ndiv {\ \n @media (min-width: 320px) { \ \n /* comment */\ \n }\ \n}" ) .unwrap(), "@media (min-width: 640px) {\ \n /* comment */\ \n}\ \n@media (min-width: 320px) {\ \n div {\ \n /* comment */\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1901.hrx" #[test] fn issue_1901() { assert_eq!( rsass( "a, b {\ \n &:not(c) {\ \n d: e;\ \n }\ \n}\ \n" ) .unwrap(), "a:not(c), b:not(c) {\ \n d: e;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1904.hrx" #[test] fn issue_1904() { assert_eq!( rsass( ".foo {\ \n &--#{\'bar\'} {\ \n color: red;\ \n }\ \n}" ) .unwrap(), ".foo--bar {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1907.hrx" #[test] fn issue_1907() { assert_eq!( rsass( "foo {\ \n bar: \'test\' + \'1 #{2} 3\';\ \n}" ) .unwrap(), "foo {\ \n bar: \"test1 2 3\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1915.hrx" #[test] #[ignore] // wrong result fn issue_1915() { assert_eq!( rsass( "@mixin wrapper() {\ \n .wrapped {\ \n @content;\ \n }\ \n}\ \n\ \n%ext {\ \n background: #000;\ \n}\ \n\ \n@include wrapper() {\ \n @extend %ext;\ \n}" ) .unwrap(), ".wrapped {\ \n background: #000;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1916.hrx" // Ignoring "issue_1916", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_192.hrx" #[test] fn issue_192() { assert_eq!( rsass( "@function test($from, $to) {\r\ \n @warn \'Starting loop\';\r\ \n @for $i from $from through $to {\r\ \n @warn \'Step #{$i}\' ;\r\ \n }\r\ \n @warn \'Finished loop\';\r\ \n @return 100%;\r\ \n}\r\ \nbody {\r\ \n width: test(0, 1);\r\ \n height: test(-1, 1);\r\ \n}" ) .unwrap(), "body {\ \n width: 100%;\ \n height: 100%;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1923.hrx" // Ignoring "issue_1923", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1926.hrx" // From "sass-spec/spec/libsass-closed-issues/issue_1927.hrx" #[test] #[ignore] // unexepected error fn issue_1927() { assert_eq!( rsass( "@media screen {\ \n $variable: dynamic;\ \n .foo-#{$variable} {a: b}\ \n .bar {\ \n @extend .foo-dynamic\ \n }\ \n}" ) .unwrap(), "@media screen {\ \n .foo-dynamic, .bar {\ \n a: b;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1931.hrx" #[test] fn issue_1931() { assert_eq!( rsass( "$var: \'http://test.com\';\ \nbody {\ \n background-image: url( #{$var});\ \n}" ) .unwrap(), "body {\ \n background-image: url(http://test.com);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1940.hrx" #[test] fn issue_1940() { assert_eq!( rsass( "// ----\r\ \n// libsass (v3.3.2)\r\ \n// ----\r\ \n\r\ \n$prefix:(\r\ \n\tfoo: foo,\r\ \n\tbar: #bar\r\ \n);\r\ \n\r\ \n#{map-get($prefix, foo)} {\r\ \n color: red;\r\ \n}\r\ \n#{map-get($prefix, bar)} {\r\ \n color: red;\r\ \n}\r\ \n\r\ \n#{map-get($prefix, foo)} .baz {\r\ \n color: red;\r\ \n}\r\ \n#{map-get($prefix, bar)} .baz {\r\ \n color: red;\r\ \n}" ) .unwrap(), "foo {\ \n color: red;\ \n}\ \n#bar {\ \n color: red;\ \n}\ \nfoo .baz {\ \n color: red;\ \n}\ \n#bar .baz {\ \n color: red;\ \n}\ \n" ); } mod issue_1941; // From "sass-spec/spec/libsass-closed-issues/issue_1944.hrx" #[test] fn issue_1944() { assert_eq!( rsass( "$count: 0;\ \n\ \n@function foo() {\ \n $count: $count + 1 !global;\ \n $selector: (\'.bar\' \'baz\');\ \n @return $selector;\ \n}\ \n\ \n\ \n#{foo()} {\ \n count: $count;\ \n}\ \n" ) .unwrap(), ".bar baz {\ \n count: 1;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1945.hrx" #[test] fn issue_1945() { assert_eq!( rsass( "foo {\ \n bar: #{\"\\\\\"}#{\"baz\"};\ \n}" ) .unwrap(), "foo {\ \n bar: \\baz;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1947.hrx" #[test] fn issue_1947() { assert_eq!( rsass( ".a-#{quote(\'\' + b)} {\ \n c: d;\ \n}\ \n\ \n.a-#{\'\' + b} {\ \n c: d;\ \n}" ) .unwrap(), ".a-b {\ \n c: d;\ \n}\ \n.a-b {\ \n c: d;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1960.hrx" #[test] #[ignore] // wrong result fn issue_1960() { assert_eq!( rsass( "foo:not(.missing) {\ \n a: b;\ \n\ \n &:hover { c: d; }\ \n}\ \n\ \nbar {\ \n @extend .missing;\ \n}" ) .unwrap(), "foo:not(.missing):not(bar) {\ \n a: b;\ \n}\ \nfoo:not(.missing):not(bar):hover {\ \n c: d;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1969.hrx" #[test] fn issue_1969() { assert_eq!( rsass( "$base-text-color: #666;\ \n\ \n@function calcNavbarTextColor ($base-text-color) {\ \n @return $base-text-color;\ \n}\ \n\ \n$header-text-color: calcNavbarTextColor($base-text-color);\ \n\ \n.test_class {\ \n color: lighten($header-text-color, 20%);\ \n}" ) .unwrap(), ".test_class {\ \n color: #999999;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1971.hrx" #[test] #[ignore] // wrong result fn issue_1971() { assert_eq!( rsass( "%foo1 {\ \n @supports (flex-wrap: wrap) {\ \n flex: auto;\ \n }\ \n}\ \n\ \n@supports (flex-wrap: wrap) {\ \n %foo2 {\ \n flex: auto;\ \n }\ \n}\ \n\ \n.bar {\ \n @extend %foo1;\ \n @extend %foo2;\ \n}\ \n" ) .unwrap(), "@supports (flex-wrap: wrap) {\ \n .bar {\ \n flex: auto;\ \n }\ \n}\ \n@supports (flex-wrap: wrap) {\ \n .bar {\ \n flex: auto;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1977" #[test] fn issue_1977() { assert_eq!( rsass( "body#some-\\(selector\\) {\ \ncolor: red;\ \n}\ \n\ \n#äöü {\ \n color: reds;\ \n}" ) .unwrap(), "@charset \"UTF-8\";\ \nbody#some-\\(selector\\) {\ \n color: red;\ \n}\ \n#äöü {\ \n color: reds;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1991.hrx" #[test] fn issue_1991() { assert_eq!( rsass( "$tests: (\ \n 0: \'foo\',\ \n false: \'bar\',\ \n);" ) .unwrap(), "" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1993.hrx" #[test] #[ignore] // unexepected error fn issue_1993() { assert_eq!( rsass( ".test {\ \n @extend #{\'%test\'} !optional\ \n}" ) .unwrap(), "" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1994.hrx" #[test] #[ignore] // wrong result fn issue_1994() { assert_eq!( rsass( "%hoverbrighter {\ \n &:hover,\ \n &:focus {\ \n opacity: .8;\ \n\ \n @supports (filter: brightness(120%)) {\ \n filter: brightness(120%);\ \n }\ \n }\ \n}\ \n\ \n.productportal-link {\ \n @extend %hoverbrighter;\ \n}" ) .unwrap(), ".productportal-link:hover, .productportal-link:focus {\ \n opacity: 0.8;\ \n}\ \n@supports (filter: brightness(120%)) {\ \n .productportal-link:hover, .productportal-link:focus {\ \n filter: brightness(120%);\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_1996.hrx" #[test] #[ignore] // wrong result fn issue_1996() { assert_eq!( rsass( "$foo: \"bar\";\ \n\ \n%class //#{$foo}\ \n{\ \n &_baz {\ \n color: red;\ \n }\ \n}" ) .unwrap(), "" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2000.hrx" #[test] #[ignore] // wrong result fn issue_2000() { assert_eq!( rsass( ".m__exhibit-header--medium {\ \n @extend #{&}--plain;\ \n &--plain {\ \n font-size: --&;\ \n }\ \n}" ) .unwrap(), ".m__exhibit-header--medium--plain, .m__exhibit-header--medium {\ \n font-size: -- .m__exhibit-header--medium--plain;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2006.hrx" #[test] fn issue_2006() { assert_eq!( rsass( "@mixin main() {\ \n bar {\ \n baz: 1;\ \n }\ \n}\ \n\ \nfoo {\ \n @at-root {\ \n @include main();\ \n }\ \n}\ \n" ) .unwrap(), "bar {\ \n baz: 1;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2007.hrx" #[test] #[ignore] // wrong result fn issue_2007() { assert_eq!( rsass( "@mixin foo() {\ \n @media (mix-width: 100px) {\ \n @extend %bar;\ \n }\ \n}\ \n\ \nfoo {\ \n @media (mix-width: 100px) {\ \n %bar {\ \n foo: bar;\ \n }\ \n }\ \n\ \n @include foo;\ \n}\ \n" ) .unwrap(), "@media (mix-width: 100px) {\ \n foo foo {\ \n foo: bar;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2009.hrx" #[test] #[ignore] // wrong result fn issue_2009() { assert_eq!( rsass( "@mixin breakpoint() {\ \n @media (min-width: 200px) {\ \n @content;\ \n }\ \n}\ \n\ \n@mixin foo() {\ \n @include breakpoint {\ \n @extend %reveal-centered;\ \n }\ \n}\ \n\ \n\ \nfoo {\ \n @include breakpoint {\ \n %reveal-centered {\ \n left: auto;\ \n right: auto;\ \n margin: 0 auto;\ \n }\ \n }\ \n\ \n @include foo;\ \n}\ \n" ) .unwrap(), "@media (min-width: 200px) {\ \n foo foo {\ \n left: auto;\ \n right: auto;\ \n margin: 0 auto;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_201.hrx" #[test] fn issue_201() { assert_eq!( rsass("a, b, { color: red; }").unwrap(), "a, b {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2017.hrx" #[test] #[ignore] // wrong result fn issue_2017() { assert_eq!( rsass( "foo {\r\ \n bar: baz;\r\ \n}\r\ \n\r\ \n@mixin link() {\r\ \n a:not(.btn) {\r\ \n color: red;\r\ \n }\r\ \n}\r\ \n\r\ \nfoo {\r\ \n @include link;\r\ \n @extend .btn;\r\ \n @include link;\r\ \n}" ) .unwrap(), "foo {\ \n bar: baz;\ \n}\ \nfoo a:not(.btn):not(foo) {\ \n color: red;\ \n}\ \nfoo a:not(.btn):not(foo) {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2020.hrx" #[test] fn issue_2020() { assert_eq!( rsass( "form {\r\ \n $selector: nth(&, 1);\r\ \n sel: inspect($selector);\r\ \n $selector: nth($selector, 1);\r\ \n sel: inspect($selector);\r\ \n} " ) .unwrap(), "form {\ \n sel: form;\ \n sel: form;\ \n}\ \n" ); } mod issue_2023; mod issue_2031; // From "sass-spec/spec/libsass-closed-issues/issue_2034.hrx" #[test] #[ignore] // wrong result fn issue_2034() { assert_eq!( rsass( ":not(.thing) {\r\ \n color: red;\r\ \n}\r\ \n:not(.bar) {\r\ \n @extend .thing;\r\ \n background: blue;\r\ \n}" ) .unwrap(), ":not(.thing) {\ \n color: red;\ \n}\ \n:not(.bar) {\ \n background: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2042.hrx" #[test] #[ignore] // wrong result fn issue_2042() { assert_eq!( rsass( ".wizard-editor {\r\ \n transform: scale(50/1);\r\ \n transform: scale((50/1));\r\ \n transform: scale( (50/1) );\r\ \n}" ) .unwrap(), ".wizard-editor {\ \n transform: scale(50/1);\ \n transform: scale(50);\ \n transform: scale(50);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2053.hrx" #[test] #[ignore] // wrong result fn issue_2053() { assert_eq!( rsass( ".foo[disabled] {\ \n @extend .foo;\ \n background: blue;\ \n }\ \n.bar[disabled] {\ \n foo {\ \n @extend .bar;\ \n background: blue;\ \n }\ \n}\ \nfoo {\ \n .baz[disabled] {\ \n @extend .baz;\ \n background: blue;\ \n }\ \n}" ) .unwrap(), ".foo[disabled] {\ \n background: blue;\ \n}\ \n.bar[disabled] foo {\ \n background: blue;\ \n}\ \nfoo .baz[disabled] {\ \n background: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2054.hrx" #[test] #[ignore] // wrong result fn issue_2054() { assert_eq!( rsass( ":not(.thing) {\r\ \n color: red;\r\ \n}\r\ \n:not(.bar) {\r\ \n @extend .thing;\r\ \n background: blue;\r\ \n}" ) .unwrap(), ":not(.thing) {\ \n color: red;\ \n}\ \n:not(.bar) {\ \n background: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2055.hrx" #[test] #[ignore] // wrong result fn issue_2055() { assert_eq!( rsass( ":not(.thing) {\ \n color: red;\ \n}\ \n:not(.thing[disabled]) {\ \n @extend .thing;\ \n background: blue;\ \n}\ \n:has(:not(.thing[disabled])) {\ \n @extend .thing;\ \n background: blue;\ \n}\ \n" ) .unwrap(), ":not(.thing) {\ \n color: red;\ \n}\ \n:not(.thing[disabled]):not([disabled]:has(:not(.thing[disabled]):not([disabled]:not(.thing[disabled])))):not([disabled]:not(.thing[disabled]):not([disabled]:has(:not(.thing[disabled]):not([disabled]:not(.thing[disabled]))))) {\ \n background: blue;\ \n}\ \n:has(:not(.thing[disabled]):not([disabled]:has(:not(.thing[disabled]):not([disabled]:not(.thing[disabled])))):not([disabled]:not(.thing[disabled]):not([disabled]:has(:not(.thing[disabled]):not([disabled]:not(.thing[disabled])))))) {\ \n background: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2056.hrx" #[test] fn issue_2056() { assert_eq!( rsass( ":foobar(.baz) {\ \n color: red;\ \n}\ \n" ) .unwrap(), ":foobar(.baz) {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2057.hrx" #[test] #[ignore] // wrong result fn issue_2057() { assert_eq!( rsass( ":not(.thing) {\r\ \n color: red;\r\ \n}\r\ \n:not(.bar) {\r\ \n @extend .thing;\r\ \n background: blue;\r\ \n}" ) .unwrap(), ":not(.thing) {\ \n color: red;\ \n}\ \n:not(.bar) {\ \n background: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2074.hrx" #[test] fn issue_2074() { assert_eq!( rsass( "@function calc_foo() {\r\ \n @return \"bar\";\r\ \n}\r\ \nfoo {\r\ \n test1: calc-foo();\r\ \n test2: calc_foo();\r\ \n}" ) .unwrap(), "foo {\ \n test1: \"bar\";\ \n test2: \"bar\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2081.hrx" // Ignoring "issue_2081", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_2095.hrx" #[test] #[ignore] // wrong result fn issue_2095() { assert_eq!( rsass( "@media all {\ \n @mixin foo() {}\ \n}\ \n" ) .unwrap(), "" ); } mod issue_2106; // From "sass-spec/spec/libsass-closed-issues/issue_2112.hrx" #[test] fn issue_2112() { assert_eq!( rsass( "$color: #1caf9a;\r\ \n\r\ \nbody {\r\ \n test-01: change-color($color, $hue: -240);\r\ \n test-03: change-color($color, $hue: 120);\r\ \n test-02: change-color($color, $hue: 480);\r\ \n}" ) .unwrap(), "body {\ \n test-01: #1caf1c;\ \n test-03: #1caf1c;\ \n test-02: #1caf1c;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2116.hrx" #[test] #[ignore] // wrong result fn issue_2116() { assert_eq!( rsass( "@function foo() {\ \n @return if(& != null, green, red);\ \n}\ \n\ \ntest {\ \n color: foo();\ \n}\ \n" ) .unwrap(), "test {\ \n color: green;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2120" #[test] fn issue_2120() { assert_eq!( rsass("@import url(//xyz.cöm/ürl)").unwrap(), "@charset \"UTF-8\";\ \n@import url(//xyz.cöm/ürl);\ \n" ); } mod issue_2123; // From "sass-spec/spec/libsass-closed-issues/issue_2124.hrx" #[test] fn issue_2124() { assert_eq!( rsass( "test {\r\ \n test-01: #{if(&, \'true\', \'false\')};\r\ \n test-01: #{if(0, \'true\', \'false\')};\r\ \n test-01: #{if(\'\', \'true\', \'false\')};\r\ \n test-01: #{if(\'0\', \'true\', \'false\')};\r\ \n test-01: #{if(null, \'true\', \'false\')};\r\ \n test-01: #{if(false, \'true\', \'false\')};\r\ \n}\r\ \n\r\ \n#{if(&, \'has-parent\', \'parentless\')} {\r\ \n test: parent;\r\ \n}\r\ \n\r\ \n@mixin with-js() {\r\ \n .js:root #{if(&, \'&\', \'\')} {\r\ \n @content;\r\ \n }\r\ \n}\r\ \n\r\ \n@include with-js() {\r\ \n .bou {\r\ \n content: \'bar\';\r\ \n }\r\ \n}\r\ \n\r\ \n.bou {\r\ \n @include with-js() {\r\ \n .bar {\r\ \n content: \'baz\';\r\ \n }\r\ \n }\r\ \n}\r\ \n\r\ \n" ) .unwrap(), "test {\ \n test-01: true;\ \n test-01: true;\ \n test-01: true;\ \n test-01: true;\ \n test-01: false;\ \n test-01: false;\ \n}\ \nparentless {\ \n test: parent;\ \n}\ \n.js:root .bou {\ \n content: \"bar\";\ \n}\ \n.js:root .bou .bar {\ \n content: \"baz\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2139.hrx" #[test] #[ignore] // wrong result fn issue_2139() { assert_eq!( rsass( ".foo {\ \n color: #FFF;\ \n}\ \n\ \n.bar .baz {\ \n @extend .foo;\ \n\ \n border: \'1px\';\ \n}\ \n\ \n*:not(.foo) {\ \n display: none;\ \n}\ \n" ) .unwrap(), ".foo, .bar .baz {\ \n color: #FFF;\ \n}\ \n.bar .baz {\ \n border: \"1px\";\ \n}\ \n*:not(.foo) {\ \n display: none;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2140.hrx" #[test] #[ignore] // wrong result fn issue_2140() { assert_eq!( rsass( "$red: red;\ \n$foo: red;\ \n\ \n:root {\ \n --red: #f00;\ \n // --red: $red;\ \n // --red: $foo;\ \n}\ \n\ \na { content: var(--red) }\ \na { content: var(--$red) }\ \na { content: var(--$foo) }\ \n\ \nb { content: (- red) }\ \nb { content: (- $red) }\ \nb { content: (- $foo) }\ \n\ \nc { content: (+- red) }\ \nc { content: (+- $red) }\ \nc { content: (+- $foo) }\ \n\ \nd { content: (-red) }\ \nd { content: (-$red) }\ \nd { content: (-$foo) }\ \n\ \ne { content: (+ red) }\ \ne { content: (+ $red) }\ \ne { content: (+ $foo) }" ) .unwrap(), ":root {\ \n --red: #f00;\ \n}\ \na {\ \n content: var(--red);\ \n}\ \na {\ \n content: var(-- red);\ \n}\ \na {\ \n content: var(-- red);\ \n}\ \nb {\ \n content: -red;\ \n}\ \nb {\ \n content: -red;\ \n}\ \nb {\ \n content: -red;\ \n}\ \nc {\ \n content: +-red;\ \n}\ \nc {\ \n content: +-red;\ \n}\ \nc {\ \n content: +-red;\ \n}\ \nd {\ \n content: -red;\ \n}\ \nd {\ \n content: -red;\ \n}\ \nd {\ \n content: -red;\ \n}\ \ne {\ \n content: +red;\ \n}\ \ne {\ \n content: +red;\ \n}\ \ne {\ \n content: +red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2143.hrx" // Ignoring "issue_2143", error tests are not supported yet. mod issue_2147; // From "sass-spec/spec/libsass-closed-issues/issue_2149.hrx" #[test] fn issue_2149() { assert_eq!( rsass( ".foo {\ \n background: url(\'background.png\') -10px -10px/110% no-repeat\ \n}\ \n" ) .unwrap(), ".foo {\ \n background: url(\"background.png\") -10px -10px/110% no-repeat;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2150.hrx" #[test] #[ignore] // wrong result fn issue_2150() { assert_eq!( rsass( "@media (min-width: 100px) {\ \n .parent > %child {\ \n color: blue;\ \n }\ \n}\ \n\ \n.foo {\ \n @extend %child;\ \n}\ \n" ) .unwrap(), "@media (min-width: 100px) {\ \n .parent > .foo {\ \n color: blue;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2153.hrx" #[test] fn issue_2153() { assert_eq!( rsass( "foo {\ \n a: \"\\\"foo\\\"\" + \"\";\ \n b: \"\" + \"\\\"foo\\\"\";\ \n c: \"\" + \"\\\"foo\";\ \n d: \"\\\"foo\\\"\" + \"bar\";\ \n}\ \n" ) .unwrap(), "foo {\ \n a: \'\"foo\"\';\ \n b: \'\"foo\"\';\ \n c: \'\"foo\';\ \n d: \'\"foo\"bar\';\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2154.hrx" #[test] #[ignore] // wrong result fn issue_2154() { assert_eq!( rsass( "@media (min-width: 1px) {\ \n .first {\ \n font-weight: 100;\ \n\ \n @media (min-width: 2px) {}\ \n }\ \n .second {\ \n font-weight: 200;\ \n }\ \n}\ \n" ) .unwrap(), "@media (min-width: 1px) {\ \n .first {\ \n font-weight: 100;\ \n }\ \n .second {\ \n font-weight: 200;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2155.hrx" // Ignoring "issue_2155", error tests are not supported yet. mod issue_2156; // From "sass-spec/spec/libsass-closed-issues/issue_2169.hrx" #[test] fn issue_2169() { assert_eq!( rsass( "@function test($a, $b) {\ \n @return \"#{$a}\" + \"#{$b}\" + \"\" + \"\";\ \n}\ \n\ \nfoo {\ \n content: test(\'bim\', \'baz\');\ \n}" ) .unwrap(), "foo {\ \n content: \"bimbaz\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2175.hrx" // Ignoring "issue_2175", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_2177.hrx" // From "sass-spec/spec/libsass-closed-issues/issue_2179.hrx" #[test] #[ignore] // wrong result fn issue_2179() { assert_eq!( rsass( "@mixin sprite-arrow() {\ \n @extend %hidden-text;\ \n}\ \n\ \n%hidden-text {\ \n text-indent: -999em;\ \n}\ \n\ \n// button.scss\ \n.button-left,\ \n.button-right,\ \n.button-plus,\ \n.button-min {\ \n &:after {\ \n @include sprite-arrow();\ \n }\ \n}\ \n\ \n.banner {\ \n &:after {\ \n @include sprite-arrow();\ \n }\ \n}\ \n\ \n.calculator {\ \n .btn-down,\ \n .btn-up {\ \n &:after {\ \n @include sprite-arrow();\ \n }\ \n }\ \n}" ) .unwrap(), ".calculator .btn-down:after,\ \n.calculator .btn-up:after, .banner:after, .button-left:after,\ \n.button-right:after,\ \n.button-plus:after,\ \n.button-min:after {\ \n text-indent: -999em;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2185.hrx" #[test] #[ignore] // wrong result fn issue_2185() { assert_eq!( rsass( "$bar: true;\r\ \n\r\ \n@mixin mixin() {\r\ \n mix: in;\r\ \n}\r\ \n\r\ \n@mixin include() {\r\ \n @content;\r\ \n}\r\ \n\r\ \np {\r\ \n @at-root {\r\ \n @if $bar {\r\ \n #if {\r\ \n height: 100px;\r\ \n }\r\ \n }\r\ \n @if (not $bar) {\r\ \n } @else if($bar) {\r\ \n #elseif {\r\ \n width: 100px;\r\ \n }\r\ \n }\r\ \n @if (not $bar) {\r\ \n } @else {\r\ \n #else {\r\ \n width: 100px;\r\ \n }\r\ \n }\r\ \n @for $i from 1 through 1 {\r\ \n #for {\r\ \n foo: bar#{$i};\r\ \n }\r\ \n }\r\ \n $i: 0;\r\ \n @while ($i == 0) {\r\ \n $i: $i + 1;\r\ \n #while {\r\ \n foo: bar#{$i};\r\ \n }\r\ \n }\r\ \n @each $i in (1) {\r\ \n #each {\r\ \n foo: bar#{$i};\r\ \n }\r\ \n }\r\ \n #inc {\r\ \n @include mixin();\r\ \n @include include() {\r\ \n inc: lude;\r\ \n }\r\ \n }\r\ \n @supports (display: flex) {\r\ \n a {display: flex}\r\ \n }\r\ \n @foo {\r\ \n bar: bat;\r\ \n }\r\ \n }\r\ \n}" ) .unwrap(), "#if {\ \n height: 100px;\ \n}\ \n#elseif {\ \n width: 100px;\ \n}\ \n#else {\ \n width: 100px;\ \n}\ \n#for {\ \n foo: bar1;\ \n}\ \n#while {\ \n foo: bar1;\ \n}\ \n#each {\ \n foo: bar1;\ \n}\ \n#inc {\ \n mix: in;\ \n inc: lude;\ \n}\ \n@supports (display: flex) {\ \n a {\ \n display: flex;\ \n }\ \n}\ \n@foo {\ \n bar: bat;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2198.hrx" #[test] fn issue_2198() { assert_eq!( rsass( "@mixin test() {\ \n @at-root {\ \n @include foo();\ \n }\ \n}\ \n\ \n@mixin foo() {\ \n #{\'.foo\'} {\ \n bar: baz;\ \n }\ \n}\ \n\ \n.test {\ \n @include test();\ \n}\ \n" ) .unwrap(), ".foo {\ \n bar: baz;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2200.hrx" #[test] #[ignore] // wrong result fn issue_2200() { assert_eq!( rsass( ".media-object-section:last-child:not(:nth-child(2)) {\ \n color: blue;\ \n}\ \n\ \n%orbit-control {\ \n color: red;\ \n}\ \n\ \n.orbit-previous {\ \n @extend %orbit-control;\ \n}\ \n" ) .unwrap(), ".media-object-section:last-child:not(:nth-child(2)) {\ \n color: blue;\ \n}\ \n.orbit-previous {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2202.hrx" #[test] fn issue_2202() { assert_eq!( rsass( "@customAtRule;\r\ \ntest {\r\ \n content: bar\r\ \n}" ) .unwrap(), "@customAtRule;\ \ntest {\ \n content: bar;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2205.hrx" #[test] #[ignore] // wrong result fn issue_2205() { assert_eq!( rsass( "$params1: #fff .5;\r\ \ntest {\r\ \n color: rgba($params1...);\r\ \n}\r\ \n\r\ \n$params2: 10 250 130 .5;\r\ \ntest {\r\ \n color: rgba($params2...);\r\ \n}" ) .unwrap(), "test {\ \n color: rgba(255, 255, 255, 0.5);\ \n}\ \ntest {\ \n color: rgba(10, 250, 130, 0.5);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_221255.hrx" // Ignoring "issue_221255", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_221289.hrx" #[test] fn issue_221289() { assert_eq!( rsass( "foo {\r\ \n bar: if(0,0<0,0);\r\ \n}" ) .unwrap(), "foo {\ \n bar: false;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2233.hrx" #[test] #[ignore] // unexepected error fn issue_2233() { assert_eq!( rsass( "@media all and (min-width: 100px) {\ \n @import \"foo\"\ \n}\ \n" ) .unwrap(), "@media all and (min-width: 100px) {\ \n a {\ \n b: c;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_224.hrx" #[test] fn issue_224() { assert_eq!( rsass( "$list: (\"a\", \"b\", \"c\");\ \n\ \ntest {\ \n content: nth($list, -1);\ \n content: nth($list, -2);\ \n content: nth($list, -3);\ \n content: nth($list, -1) == nth($list, length($list));\ \n}\ \n" ) .unwrap(), "test {\ \n content: \"c\";\ \n content: \"b\";\ \n content: \"a\";\ \n content: true;\ \n}\ \n" ); } mod issue_2243; // From "sass-spec/spec/libsass-closed-issues/issue_2246.hrx" #[test] #[ignore] // wrong result fn issue_2246() { assert_eq!( rsass( "@mixin foo($option: \'foo\') {\ \n // Create a unique, random placeholder to store styles\ \n $placeholder : $option + random(9999);\ \n\ \n // Store the styles in the placeholder\ \n @at-root %#{$placeholder} {\ \n content: \'foo\';\ \n }\ \n\ \n @at-root {\ \n .bar {\ \n @extend %#{$placeholder};\ \n }\ \n }\ \n}\ \n\ \n@mixin bar($option) {\ \n @include foo($option);\ \n}\ \n\ \n.foo {\ \n @include bar(\'baz\');\ \n}" ) .unwrap(), ".bar {\ \n content: \"foo\";\ \n}\ \n" ); } mod issue_2260; // From "sass-spec/spec/libsass-closed-issues/issue_2261.hrx" #[test] fn issue_2261() { assert_eq!( rsass( "$seven: 7;\ \n\ \n.test {\ \n\ \n equal-01: (7 == 7);\ \n equal-02: (\'7\' == \'7\');\ \n equal-03: (\'#{7}\' == \'#{7}\');\ \n\ \n equal-04: (7 == \'7\');\ \n equal-05: (\'7\' == 7);\ \n equal-06: (7 == \'#{7}\');\ \n equal-07: (\'#{7}\' == 7);\ \n equal-08: (\'7\' == \'#{7}\');\ \n equal-09: (\'#{7}\' == \'7\');\ \n\ \n equal-10: ($seven == 7);\ \n equal-11: ($seven == \'7\');\ \n equal-13: ($seven == \'#{7}\');\ \n\ \n equal-14: (7 == $seven);\ \n equal-15: (\'7\' == $seven);\ \n equal-16: (\'#{7}\' == $seven);\ \n\ \n equal-17: (\'#{$seven}\' == 7);\ \n equal-18: (\'#{$seven}\' == \'7\');\ \n equal-19: (\'#{$seven}\' == \'#{7}\');\ \n\ \n equal-20: (7 == \'#{$seven}\');\ \n equal-21: (\'7\' == \'#{$seven}\');\ \n equal-22: (\'#{7}\' == \'#{$seven}\');\ \n\ \n equal-23: (\'#{$seven}\' == $seven);\ \n equal-24: (\'#{$seven}\' == \'#{$seven}\');\ \n\ \n}" ) .unwrap(), ".test {\ \n equal-01: true;\ \n equal-02: true;\ \n equal-03: true;\ \n equal-04: false;\ \n equal-05: false;\ \n equal-06: false;\ \n equal-07: false;\ \n equal-08: true;\ \n equal-09: true;\ \n equal-10: true;\ \n equal-11: false;\ \n equal-13: false;\ \n equal-14: true;\ \n equal-15: false;\ \n equal-16: false;\ \n equal-17: false;\ \n equal-18: true;\ \n equal-19: true;\ \n equal-20: false;\ \n equal-21: true;\ \n equal-22: true;\ \n equal-23: false;\ \n equal-24: true;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2289.hrx" #[test] #[ignore] // wrong result fn issue_2289() { assert_eq!( rsass( ".foo:baz:baz {\ \n float: left;\ \n}\ \n\ \n.bar {\ \n @extend .foo;\ \n}\ \n" ) .unwrap(), ".foo:baz:baz, .bar:baz:baz {\ \n float: left;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2291.hrx" #[test] #[ignore] // wrong result fn issue_2291() { assert_eq!( rsass( ".m__exhibit-header--medium {\ \n @extend #{&}--plain;\ \n &--plain {\ \n font-size: 1em;\ \n }\ \n}\ \n\ \nfoo {\ \n bar[baz=\"#{&}\"][str=\"&\"] {\ \n asd: qwe;\ \n }\ \n}\ \n\ \nA, B, C {\ \n #{&}-foo#{&}-bar {\ \n color: blue;\ \n }\ \n #{\"A, B, C\"}-foo#{\"A, B, C\"}-bar {\ \n color: blue;\ \n }\ \n}\ \n\ \nA {\ \n B#{&}C {\ \n .b, .c, .d {\ \n #{&}-foo {\ \n parent: &bar;\ \n itpl: #{&}bar;\ \n }\ \n #{\"A .b, A .c, A .d\"}-foo {\ \n parent: &bar;\ \n itpl: #{&}bar;\ \n }\ \n }\ \n }\ \n}" ) .unwrap(), ".m__exhibit-header--medium--plain, .m__exhibit-header--medium {\ \n font-size: 1em;\ \n}\ \nfoo bar[baz=foo][str=\"&\"] {\ \n asd: qwe;\ \n}\ \nA A, A B, A C-fooA, A B, A C-bar, B A, B B, B C-fooA, B B, B C-bar, C A, C B, C C-fooA, C B, C C-bar {\ \n color: blue;\ \n}\ \nA A, A B, A C-fooA, A B, A C-bar, B A, B B, B C-fooA, B B, B C-bar, C A, C B, C C-fooA, C B, C C-bar {\ \n color: blue;\ \n}\ \nA BAC .b A BAC .b, A BAC .b A BAC .c, A BAC .b A BAC .d-foo, A BAC .c A BAC .b, A BAC .c A BAC .c, A BAC .c A BAC .d-foo, A BAC .d A BAC .b, A BAC .d A BAC .c, A BAC .d A BAC .d-foo {\ \n parent: A BAC .b A BAC .b, A BAC .b A BAC .c, A BAC .b A BAC .d-foo, A BAC .c A BAC .b, A BAC .c A BAC .c, A BAC .c A BAC .d-foo, A BAC .d A BAC .b, A BAC .d A BAC .c, A BAC .d A BAC .d-foo bar;\ \n itpl: A BAC .b A BAC .b, A BAC .b A BAC .c, A BAC .b A BAC .d-foo, A BAC .c A BAC .b, A BAC .c A BAC .c, A BAC .c A BAC .d-foo, A BAC .d A BAC .b, A BAC .d A BAC .c, A BAC .d A BAC .d-foobar;\ \n}\ \nA BAC .b A .b, A BAC .b A .c, A BAC .b A .d-foo, A BAC .c A .b, A BAC .c A .c, A BAC .c A .d-foo, A BAC .d A .b, A BAC .d A .c, A BAC .d A .d-foo {\ \n parent: A BAC .b A .b, A BAC .b A .c, A BAC .b A .d-foo, A BAC .c A .b, A BAC .c A .c, A BAC .c A .d-foo, A BAC .d A .b, A BAC .d A .c, A BAC .d A .d-foo bar;\ \n itpl: A BAC .b A .b, A BAC .b A .c, A BAC .b A .d-foo, A BAC .c A .b, A BAC .c A .c, A BAC .c A .d-foo, A BAC .d A .b, A BAC .d A .c, A BAC .d A .d-foobar;\ \n}\ \n" ); } mod issue_2295; // From "sass-spec/spec/libsass-closed-issues/issue_2303.hrx" #[test] #[ignore] // wrong result fn issue_2303() { assert_eq!( rsass( ".wrapper-class {\r\ \n @import \'module\';\r\ \n}" ) .unwrap(), ".wrapper-class .okay {\ \n background: green;\ \n}\ \n.wrapper-class .broken {\ \n background: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2304.hrx" // Ignoring "issue_2304", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_2307.hrx" // Ignoring "issue_2307", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_2309.hrx" #[test] #[ignore] // wrong result fn issue_2309() { assert_eq!( rsass( "$button-sizes: (\r\ \n \'xs\': (\r\ \n \'line-height\': 16 / 12,\r\ \n ),\r\ \n \'s\': (\r\ \n \'line-height\': 18 / 14,\r\ \n ),\r\ \n \'m\': (\r\ \n \'line-height\': 18 / 14,\r\ \n ),\r\ \n \'l\': (\r\ \n \'line-height\': 22 / 16,\r\ \n )\r\ \n);\r\ \n\r\ \n@each $size in $button-sizes {\r\ \n $size-metrics: nth($size, 2);\r\ \n\r\ \n .c-button__icon {\r\ \n min-height: map-get($size-metrics, \'line-height\') * 1em;\r\ \n }\r\ \n}" ) .unwrap(), ".c-button__icon {\ \n min-height: 1.3333333333em;\ \n}\ \n.c-button__icon {\ \n min-height: 1.2857142857em;\ \n}\ \n.c-button__icon {\ \n min-height: 1.2857142857em;\ \n}\ \n.c-button__icon {\ \n min-height: 1.375em;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_231.hrx" #[test] fn issue_231() { assert_eq!( rsass( "// test.scss:\r\ \na {\r\ \n background-image: url(fn(\"s\"));\r\ \n}" ) .unwrap(), "a {\ \n background-image: url(fn(\"s\"));\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2320" #[test] fn issue_2320() { assert_eq!( rsass( "$char-f: \'\\66\';\r\ \n$char-g: \'\\67\';\r\ \n\r\ \n.test-1 {\r\ \n content: \'#{$char-f}\\feff\';\r\ \n}\r\ \n\r\ \n.test-2 {\r\ \n content: \'#{$char-g}\\feff\';\r\ \n}\r\ \n\r\ \n// this is broken\r\ \n.test-3 {\r\ \n content: \'\\feff#{$char-f}\';\r\ \n}\r\ \n\r\ \n.test-4 {\r\ \n content: \'\\feff#{$char-g}\';\r\ \n}" ) .unwrap(), "@charset \"UTF-8\";\ \n.test-1 {\ \n content: \"f\u{feff}\";\ \n}\ \n.test-2 {\ \n content: \"g\u{feff}\";\ \n}\ \n.test-3 {\ \n content: \"\u{feff}f\";\ \n}\ \n.test-4 {\ \n content: \"\u{feff}g\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2321.hrx" #[test] #[ignore] // wrong result fn issue_2321() { assert_eq!( rsass( "a {\ \n b: if(true, b, c...);\ \n c: if(false, b, c...);\ \n}\ \n" ) .unwrap(), "a {\ \n b: b;\ \n c: c;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2330.hrx" #[test] fn issue_2330() { assert_eq!( rsass( "@function test () {\r\ \n $m: ();\r\ \n $abc: (a b c d e f g h i j k);\r\ \n\r\ \n @for $index from 1 through length($abc) {;\r\ \n $m: map-merge($m, (nth($abc, $index):$index) );\r\ \n }\r\ \n\r\ \n @return $m;\r\ \n}\r\ \n\r\ \ntest {\r\ \n content: inspect(test());\r\ \n}" ) .unwrap(), "test {\ \n content: (a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10, k: 11);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2333.hrx" #[test] #[ignore] // wrong result fn issue_2333() { assert_eq!( rsass("test { test: inspect((a:1,b:(foo,bar),c:3)); }").unwrap(), "test {\ \n test: (a: 1, b: (foo, bar), c: 3);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2341.hrx" #[test] #[ignore] // wrong result fn issue_2341() { assert_eq!( rsass( "@function aFunction() {\r\ \n @return 1em;\r\ \n}\r\ \n\r\ \n@media (max-width: 1em) {\r\ \n %placeholder {\r\ \n color: red;\r\ \n }\r\ \n}\r\ \n\r\ \n@media (max-width: aFunction()) {\r\ \n .test {\r\ \n @extend %placeholder;\r\ \n }\r\ \n}" ) .unwrap(), "@media (max-width: 1em) {\ \n .test {\ \n color: red;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2346.hrx" #[test] #[ignore] // wrong result fn issue_2346() { assert_eq!( rsass( "$items: 3;\r\ \nli {\r\ \n &:nth-child(#{$items}n - #{$items}) {\r\ \n color: red;\r\ \n }\r\ \n}" ) .unwrap(), "li:nth-child(3n-3) {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2347.hrx" #[test] #[ignore] // unexepected error fn issue_2347() { assert_eq!( rsass( "%baz2 {\r\ \n display: flex;\r\ \n}\r\ \n%baz3 {\r\ \n display: flex;\r\ \n}\r\ \n\r\ \ncustom2, [custom2], .custom2 {\r\ \n @extend %baz2\r\ \n}\r\ \n\r\ \n[custom3], custom3, .custom3 {\r\ \n @extend %baz3\r\ \n}" ) .unwrap(), "custom2, [custom2], .custom2 {\ \n display: flex;\ \n}\ \n[custom3], custom3, .custom3 {\ \n display: flex;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2349.hrx" #[test] fn issue_2349() { assert_eq!( rsass( "$path1: assets/images; // no errors thrown\r\ \n$path2: /images; // errors thrown\r\ \n.test {\r\ \n background: url(#{$path1}/image.png);\r\ \n background: url(#{$path2}/image.png);\r\ \n}" ) .unwrap(), ".test {\ \n background: url(assets/images/image.png);\ \n background: url(/images/image.png);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2352.hrx" // Ignoring "issue_2352", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_2358.hrx" #[test] #[ignore] // wrong result fn issue_2358() { assert_eq!( rsass( ".outer {\r\ \n @at-root .root {\r\ \n .inner {\r\ \n .element {\r\ \n --modifier#{&}--another-modifier {\r\ \n content: \"#{&}\";\r\ \n }\r\ \n &--modifier#{&}--another-modifier {\r\ \n content: \"#{&}\";\r\ \n }\r\ \n }\r\ \n }\r\ \n }\r\ \n}\r\ \n\r\ \n@at-root .block {\r\ \n &__element {\r\ \n #{&} {\r\ \n content: \"#{&}\";\r\ \n }\r\ \n &--modifier {\r\ \n content: \"#{&}\";\r\ \n }\r\ \n --modifier#{&}--another-modifier {\r\ \n content: \"#{&}\";\r\ \n }\r\ \n &--modifier#{&}--another-modifier {\r\ \n content: \"#{&}\";\r\ \n }\r\ \n }\r\ \n}\r\ \n" ) .unwrap(), ".root .inner .element --modifier.root .inner .element--another-modifier {\ \n content: \".root .inner .element --modifier.root .inner .element--another-modifier\";\ \n}\ \n.root .inner .element--modifier.root .inner .element--another-modifier {\ \n content: \".root .inner .element--modifier.root .inner .element--another-modifier\";\ \n}\ \n.block__element .block__element {\ \n content: \".block__element .block__element\";\ \n}\ \n.block__element--modifier {\ \n content: \".block__element--modifier\";\ \n}\ \n.block__element --modifier.block__element--another-modifier {\ \n content: \".block__element --modifier.block__element--another-modifier\";\ \n}\ \n.block__element--modifier.block__element--another-modifier {\ \n content: \".block__element--modifier.block__element--another-modifier\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2360.hrx" // From "sass-spec/spec/libsass-closed-issues/issue_2365.hrx" // Ignoring "issue_2365", error tests are not supported yet. mod issue_2366; // From "sass-spec/spec/libsass-closed-issues/issue_2369.hrx" // Ignoring "issue_2369", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_2371.hrx" // Ignoring "issue_2371", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_2374.hrx" #[test] #[ignore] // wrong result fn issue_2374() { assert_eq!( rsass( "$colors: (\r\ \n yellow: #ffeb3b\r\ \n);\r\ \n@each $name, $color in $colors {\r\ \n $amount: 40;\r\ \n @for $i from 0 through 9 {\r\ \n .#{$name}-#{($i*100)} { background-color: lighten($color, $amount) };\r\ \n $amount: $amount - 2;\r\ \n }\r\ \n}\r\ \n\r\ \n$colors: (\r\ \n yellow: yellow,\r\ \n red: red,\r\ \n blue: blue,\r\ \n \r\ \n);\r\ \n@each $name, $color in $colors {\r\ \n @for $i from 0 through 2 {\r\ \n .#{$name}-#{($i*100)} { \r\ \n background-color: lighten($color, 10) \r\ \n };\r\ \n }\r\ \n}\r\ \n\r\ \n" ) .unwrap(), ".yellow-0 {\ \n background-color: white;\ \n}\ \n.yellow-100 {\ \n background-color: #fffffd;\ \n}\ \n.yellow-200 {\ \n background-color: #fffef3;\ \n}\ \n.yellow-300 {\ \n background-color: #fffde8;\ \n}\ \n.yellow-400 {\ \n background-color: #fffcde;\ \n}\ \n.yellow-500 {\ \n background-color: #fffbd4;\ \n}\ \n.yellow-600 {\ \n background-color: #fffaca;\ \n}\ \n.yellow-700 {\ \n background-color: #fff9c0;\ \n}\ \n.yellow-800 {\ \n background-color: #fff7b5;\ \n}\ \n.yellow-900 {\ \n background-color: #fff6ab;\ \n}\ \n.yellow-0 {\ \n background-color: #ffff33;\ \n}\ \n.yellow-100 {\ \n background-color: #ffff33;\ \n}\ \n.yellow-200 {\ \n background-color: #ffff33;\ \n}\ \n.red-0 {\ \n background-color: #ff3333;\ \n}\ \n.red-100 {\ \n background-color: #ff3333;\ \n}\ \n.red-200 {\ \n background-color: #ff3333;\ \n}\ \n.blue-0 {\ \n background-color: #3333ff;\ \n}\ \n.blue-100 {\ \n background-color: #3333ff;\ \n}\ \n.blue-200 {\ \n background-color: #3333ff;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2376.hrx" #[test] fn issue_2376() { assert_eq!( rsass( ".test {\r\ \n\tbackground:url(//img12.360buyimg.com/..);\r\ \n\t.a{\r\ \n\t\theight: 100px;\r\ \n\t}\r\ \n}" ) .unwrap(), ".test {\ \n background: url(//img12.360buyimg.com/..);\ \n}\ \n.test .a {\ \n height: 100px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2382.hrx" #[test] fn issue_2382() { assert_eq!( rsass( ".test {\r\ \n font: normal normal 400 16px/calc(16px * 1.4) Oxygen;\r\ \n}" ) .unwrap(), ".test {\ \n font: normal normal 400 16px/calc(16px * 1.4) Oxygen;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_238760.hrx" // Ignoring "issue_238760", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_239.hrx" #[test] #[ignore] // wrong result fn issue_239() { assert_eq!( rsass( "$gutter: 100% / 36.2;\r\ \n $gutter_em: 1rem; //This needs to be rem to not mess up margins\r\ \n\r\ \n// This calculate the gutter\r\ \n@function col_width($n, $use_calc: false) {\r\ \n $divisor: 12 / $n;\r\ \n @if ($use_calc) {\r\ \n $gutter_offset: $gutter_em * ($divisor - 1);\r\ \n @return calc((100% - #{$gutter_offset}) / #{$divisor});\r\ \n }\r\ \n @else {\r\ \n @return (100% - $gutter * ($divisor - 1)) / $divisor;\r\ \n }\r\ \n}\r\ \n\r\ \n// Each number here becomes a grid: onecol, twocol etc. \r\ \n$grids: one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve;\r\ \n$i: 1;\r\ \n@each $grid in $grids {\r\ \n .#{$grid}col {\r\ \n width: col_width( $i );\r\ \n width: col_width( $i, true );\r\ \n }\r\ \n\r\ \n %#{$grid}col {\r\ \n width: col_width( $i );\r\ \n width: col_width( $i, true );\r\ \n }\r\ \n $i: $i + 1;\r\ \n}" ) .unwrap(), ".onecol {\ \n width: 5.8011049724%;\ \n width: calc((100% - 11rem) / 12);\ \n}\ \n.twocol {\ \n width: 14.364640884%;\ \n width: calc((100% - 5rem) / 6);\ \n}\ \n.threecol {\ \n width: 22.9281767956%;\ \n width: calc((100% - 3rem) / 4);\ \n}\ \n.fourcol {\ \n width: 31.4917127072%;\ \n width: calc((100% - 2rem) / 3);\ \n}\ \n.fivecol {\ \n width: 40.0552486188%;\ \n width: calc((100% - 1.4rem) / 2.4);\ \n}\ \n.sixcol {\ \n width: 48.6187845304%;\ \n width: calc((100% - 1rem) / 2);\ \n}\ \n.sevencol {\ \n width: 57.182320442%;\ \n width: calc((100% - 0.7142857143rem) / 1.7142857143);\ \n}\ \n.eightcol {\ \n width: 65.7458563536%;\ \n width: calc((100% - 0.5rem) / 1.5);\ \n}\ \n.ninecol {\ \n width: 74.3093922652%;\ \n width: calc((100% - 0.3333333333rem) / 1.3333333333);\ \n}\ \n.tencol {\ \n width: 82.8729281768%;\ \n width: calc((100% - 0.2rem) / 1.2);\ \n}\ \n.elevencol {\ \n width: 91.4364640884%;\ \n width: calc((100% - 0.0909090909rem) / 1.0909090909);\ \n}\ \n.twelvecol {\ \n width: 100%;\ \n width: calc((100% - 0rem) / 1);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2394.hrx" #[test] #[ignore] // unexepected error fn issue_2394() { assert_eq!( rsass( "@mixin brokenTest($color: red, $variableArguments...) {\r\ \n $width: map-get(keywords($variableArguments), width);\r\ \n a {\r\ \n width: $width;\r\ \n color: $color;\r\ \n }\r\ \n}\r\ \n\r\ \n@mixin workingTest($variableArguments...) {\r\ \n $width: map-get(keywords($variableArguments), width);\r\ \n $color: map-get(keywords($variableArguments), color);\r\ \n a {\r\ \n width: $width;\r\ \n color: $color;\r\ \n }\r\ \n}\r\ \n\r\ \n@include brokenTest($width: 30px, $color: blue); // #1 fails\r\ \n@include brokenTest($color: blue, $width: 30px); // #2 fails\r\ \n@include brokenTest(blue, $width: 30px); // #3 works (!)\r\ \n@include workingTest($width: 30px, $color: blue); // #4 works\r\ \n@include workingTest($color: blue, $width: 30px); // #5 works\r\ \n" ) .unwrap(), "a {\ \n width: 30px;\ \n color: blue;\ \n}\ \na {\ \n width: 30px;\ \n color: blue;\ \n}\ \na {\ \n width: 30px;\ \n color: blue;\ \n}\ \na {\ \n width: 30px;\ \n color: blue;\ \n}\ \na {\ \n width: 30px;\ \n color: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2399.hrx" #[test] #[ignore] // wrong result fn issue_2399() { assert_eq!( rsass( ".thing {\r\ \n\tcolor: black;\r\ \n}\r\ \n\r\ \n.a,\r\ \n.b,\r\ \n.c,\r\ \n.d,\r\ \n.e {\r\ \n\t&:not(.thing) { @extend .thing; }\r\ \n}" ) .unwrap(), ".thing, .a:not(.thing),\ \n.b:not(.thing),\ \n.c:not(.thing),\ \n.d:not(.thing),\ \n.e:not(.thing) {\ \n color: black;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2429.hrx" #[test] fn issue_2429() { assert_eq!( rsass( "input[type=url] {\r\ \n content: bar\r\ \n}" ) .unwrap(), "input[type=url] {\ \n content: bar;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2444.hrx" #[test] #[ignore] // unexepected error fn issue_2444() { assert_eq!( rsass( "a {\ \n @at-root (with: rule) {\ \n b: c;\ \n }\ \n}\ \n" ) .unwrap(), "a {\ \n b: c;\ \n}\ \n" ); } // Ignoring "issue_2446", tests with expected error not implemented yet. // Ignoring "issue_245443", tests with expected error not implemented yet. // From "sass-spec/spec/libsass-closed-issues/issue_246.hrx" #[test] fn issue_246() { assert_eq!( rsass( "$content-width: 960px;\r\ \n\r\ \n/* demo.css: */\r\ \n.selector {\r\ \n padding: 0 calc(100%/2 - #{$content-width/2})\r\ \n}\r\ \n\r\ \n\r\ \n/* bin/sassc demo.scss */\r\ \n.selector {\r\ \n padding: 0 calc(100%/2 - #{$content-width/2}); }" ) .unwrap(), "/* demo.css: */\ \n.selector {\ \n padding: 0 calc(100%/2 - 480px);\ \n}\ \n/* bin/sassc demo.scss */\ \n.selector {\ \n padding: 0 calc(100%/2 - 480px);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2462.hrx" #[test] fn issue_2462() { assert_eq!( rsass( "b {\ \n color: lighten(Crimson, 10%);\ \n}\ \n" ) .unwrap(), "b {\ \n color: #ed365b;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2464.hrx" #[test] fn issue_2464() { assert_eq!( rsass( ":host(:not(.foo)) {\r\ \n left: 0;\r\ \n}\r\ \n\r\ \nfoobar {\r\ \n :host(:not(.foo)) {\r\ \n left: 0;\r\ \n }\r\ \n}" ) .unwrap(), ":host(:not(.foo)) {\ \n left: 0;\ \n}\ \nfoobar :host(:not(.foo)) {\ \n left: 0;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2465.hrx" #[test] #[ignore] // wrong result fn issue_2465() { assert_eq!( rsass( "foo {\ \n a: 4e2px;\ \n b: 5e-2px;\ \n c: 6e2px + 3px;\ \n d: 7e-2px + 3px;\ \n}\ \n" ) .unwrap(), "foo {\ \n a: 400px;\ \n b: 0.05px;\ \n c: 603px;\ \n d: 3.07px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2467.hrx" #[test] fn issue_2467() { assert_eq!( rsass( "foo {\ \n a: [footer-right] / 120px;\ \n b: [footer-right]/ 120px;\ \n c: [footer-right] /120px;\ \n d: [footer-right]/120px;\ \n e: [footer-right] / 120px 1fr;\ \n f: [footer-right]/ 120px 1fr;\ \n g: [footer-right] /120px 1fr;\ \n h: [footer-right]/120px 1fr;\ \n}\ \n" ) .unwrap(), "foo {\ \n a: [footer-right]/120px;\ \n b: [footer-right]/120px;\ \n c: [footer-right]/120px;\ \n d: [footer-right]/120px;\ \n e: [footer-right]/120px 1fr;\ \n f: [footer-right]/120px 1fr;\ \n g: [footer-right]/120px 1fr;\ \n h: [footer-right]/120px 1fr;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2468.hrx" #[test] #[ignore] // wrong result fn issue_2468() { assert_eq!( rsass( "%matches {\ \n :matches(oh, no) {\ \n x: 1;\ \n y: 2;\ \n }\ \n}\ \nmatches {\ \n @extend %matches;\ \n @extend oh;\ \n}\ \n\ \n%any {\ \n :any(oh, no) {\ \n x: 1;\ \n y: 2;\ \n }\ \n}\ \nany {\ \n @extend %any;\ \n @extend oh;\ \n}\ \n" ) .unwrap(), "matches :matches(oh, any, matches, no) {\ \n x: 1;\ \n y: 2;\ \n}\ \nany :any(oh, any, matches, no) {\ \n x: 1;\ \n y: 2;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2472.hrx" #[test] #[ignore] // unexepected error fn issue_2472() { assert_eq!( rsass( "@function dark(\r\ \n $color,\r\ \n $args...\r\ \n) {\r\ \n @return call(\'darken\', $color, $args...);\r\ \n}\r\ \n\r\ \n@function dark2(\r\ \n $args...\r\ \n) {\r\ \n @return call(\'darken\', $args...);\r\ \n}\r\ \n\r\ \n$arg: join((), 5%);\r\ \n\r\ \n.single {\r\ \n direct: darken(#102030, 5%);\r\ \n arg: darken(#102030, $arg...);\r\ \n call: call(\'darken\', #102030, $arg...);\r\ \n function: dark(#102030, 5%);\r\ \n function2: dark2(#102030, 5%);\r\ \n}" ) .unwrap(), ".single {\ \n direct: #0a131d;\ \n arg: #0a131d;\ \n call: #0a131d;\ \n function: #0a131d;\ \n function2: #0a131d;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2480.hrx" #[test] #[ignore] // wrong result fn issue_2480() { assert_eq!( rsass( "@mixin main(\r\ \n $param1: param1,\r\ \n $param2: param2,\r\ \n $param3: param3\r\ \n) {\r\ \n param1-value: $param1;\r\ \n param2-value: $param2;\r\ \n param3-value: $param3;\r\ \n}\r\ \n\r\ \n@mixin router($args...) {\r\ \n @if (true) { @include main($args...) }\r\ \n @else { @include main2($args...) }\r\ \n}\r\ \n\r\ \n@mixin helper($args...) {\r\ \n @include router($param2: param__2, $args...)\r\ \n}\r\ \n\r\ \n.ordinal-arguments {\r\ \n @include helper(param___1);\r\ \n}\r\ \n\r\ \n.named-arguments {\r\ \n @include helper($param1: param___1);\r\ \n}" ) .unwrap(), ".ordinal-arguments {\ \n param1-value: param___1;\ \n param2-value: param__2;\ \n param3-value: param3;\ \n}\ \n.named-arguments {\ \n param1-value: param___1;\ \n param2-value: param__2;\ \n param3-value: param3;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2482.hrx" // Ignoring "issue_2482", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_2509.hrx" #[test] #[ignore] // unexepected error fn issue_2509() { assert_eq!( rsass( "[charset i] {\r\ \n\tdisplay: block;\r\ \n}\r\ \n\r\ \n[charset I] {\r\ \n\tdisplay: block;\r\ \n}\r\ \n\r\ \n[charset=\"utf-8\" i] {\r\ \n\tdisplay: block;\r\ \n}\r\ \n\r\ \n[charset=\"utf-8\" I] {\r\ \n\tdisplay: block;\r\ \n}" ) .unwrap(), "[charset i] {\ \n display: block;\ \n}\ \n[charset I] {\ \n display: block;\ \n}\ \n[charset=\"utf-8\" i] {\ \n display: block;\ \n}\ \n[charset=\"utf-8\" I] {\ \n display: block;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2520.hrx" #[test] #[ignore] // wrong result fn issue_2520() { assert_eq!( rsass( "// ----\r\ \n// Sass (v3.4.21)\r\ \n// Compass (v1.0.3)\r\ \n// ----\r\ \n\r\ \n@function remove-modifiers($selector) {\r\ \n // convert selector to a string\r\ \n $selector: inspect(nth($selector, 1));\r\ \n \r\ \n $modifier: \'\';\r\ \n \r\ \n // Find out where the first modifier starts\r\ \n $modifier-index: str-index($selector, \'\"--\');\r\ \n \r\ \n @if $modifier-index {\r\ \n // Strip the first part of the selector up until the first modifier\r\ \n $modifier: str-slice($selector, $modifier-index);\r\ \n // Find out where the modifier ends\r\ \n $modifier-end: str-index($modifier, \'\"]\');\r\ \n // Isolate the modifier\r\ \n $modifier: str-slice($modifier, 0, $modifier-end);\r\ \n // Remove the modifier from the selector\r\ \n $selector: str-replace($selector, $modifier, \'\');\r\ \n // Remove junk characters\r\ \n $selector: str-replace($selector, \'[class*=]\', \'\');\r\ \n // Recurse the function to eliminate any remainig modifiers\r\ \n $selector: remove-modifiers($selector);\r\ \n }\r\ \n \r\ \n @return $selector;\r\ \n }\r\ \n \r\ \n @function remove-duplicates($list, $recursive: false) {\r\ \n $result: ();\r\ \n \r\ \n @each $item in $list {\r\ \n @if not index($result, $item) {\r\ \n @if length($item) > 1 and $recursive {\r\ \n $result: append($result, remove-duplicates($item, $recursive));\r\ \n }\r\ \n @else {\r\ \n $result: append($result, $item);\r\ \n }\r\ \n }\r\ \n }\r\ \n \r\ \n @return $result;\r\ \n }\r\ \n \r\ \n @function str-replace($string, $search, $replace) { \r\ \n $index: str-index($string, $search);\r\ \n \r\ \n @if $index {\r\ \n @return str-slice($string, 1, $index - 1) + $replace + str-replace(\r\ \n str-slice($string, $index + str-length($search)), $search, $replace\r\ \n );\r\ \n }\r\ \n \r\ \n @return $string;\r\ \n }\r\ \n \r\ \n @function module-tree($selector) {\r\ \n $parent-module: $module;\r\ \n \r\ \n // Remove any modifers\r\ \n $selectors: remove-modifiers($selector);\r\ \n \r\ \n // Remove any junk characters\r\ \n $selectors: str-replace($selectors, \'.\', \'\');\r\ \n $selectors: str-replace($selectors, \'[class*=\"--\', \'\');\r\ \n $selectors: str-replace($selectors, \'[class*=\"\', \'\');\r\ \n $selectors: str-replace($selectors, \'--\"]\', \'\');\r\ \n $selectors: str-replace($selectors, \'\"]\', \'\');\r\ \n \r\ \n // Spoof our modules into a list\r\ \n $selectors: str-replace($selectors, \' \', \', \');\r\ \n $selectors: selector-parse($selectors);\r\ \n \r\ \n @return $selectors;\r\ \n }\r\ \n \r\ \n @function list-remove($list, $value, $recursive: false) { \r\ \n $result: ();\r\ \n \r\ \n @for $i from 1 through length($list) {\r\ \n @if type-of(nth($list, $i)) == list and $recursive {\r\ \n $result: append($result, list-remove(nth($list, $i), $value, $recursive), comma);\r\ \n } @else if nth($list, $i) != $value {\r\ \n $result: append($result, nth($list, $i), comma);\r\ \n }\r\ \n }\r\ \n \r\ \n @return $result;\r\ \n }\r\ \n \r\ \n @function this($options...) {\r\ \n $value: map-get($config, $options...);\r\ \n $debug: true;\r\ \n \r\ \n $this: &;\r\ \n \r\ \n @if length($this) > 0 {\r\ \n @if str-index(inspect(nth($this, 1)), \'%\') == 1 {\r\ \n $debug: false;\r\ \n }\r\ \n }\r\ \n \r\ \n @if $debug and not $value and $value != false {\r\ \n @warn \'#{$options} not found in #{$module} config\';\r\ \n }\r\ \n \r\ \n @return $value;\r\ \n }\r\ \n \r\ \n @function config($map-old, $map-new) {\r\ \n // Merge default and custom options\r\ \n $map-merged: map-merge($map-old, $map-new);\r\ \n \r\ \n // Store config in global variable\r\ \n $config: $map-merged !global;\r\ \n \r\ \n // Return merged map\r\ \n @return $map-merged;\r\ \n }\r\ \n \r\ \n @mixin module($module: $module) {\r\ \n $nested: &;\r\ \n \r\ \n @if not $nested {\r\ \n $module: $module !global;\r\ \n }\r\ \n \r\ \n $selectors: ();\r\ \n \r\ \n @each $item in $module {\r\ \n $selectors: join($selectors, \'.#{$module}\', comma);\r\ \n $selectors: join($selectors, \'[class*=\"#{$module}--\"]\', comma);\r\ \n }\r\ \n \r\ \n #{$selectors} {\r\ \n @content;\r\ \n }\r\ \n }\r\ \n \r\ \n @mixin component($components: null, $glue: \'__\') {\r\ \n $selectors: \'[class*=\"#{$module}#{$glue}\"]\';\r\ \n $this: &;\r\ \n $tree: module-tree($this);\r\ \n $namespace: nth($tree, length($tree));\r\ \n \r\ \n @if $components {\r\ \n $selectors: ();\r\ \n \r\ \n @each $component in $components {\r\ \n $selectors: join(\r\ \n $selectors, \r\ \n \'.#{$namespace}#{$glue}#{$component}, [class*=\"#{$namespace}#{$glue}#{$component}-\"]\', \r\ \n comma\r\ \n );\r\ \n }\r\ \n }\r\ \n \r\ \n $parents: ();\r\ \n \r\ \n @each $selector in & {\r\ \n // spoof the selector into a list\r\ \n $selector: str-replace(inspect($selector), \' \', \', \');\r\ \n $selector: selector-parse($selector);\r\ \n \r\ \n // if the last item isn\'t a modifier, remove it\r\ \n @if not str-index(inspect(nth($selector, length($selector))), \'[class*=\"--\') {\r\ \n $selector: list-remove($selector, nth($selector, length($selector)));\r\ \n }\r\ \n \r\ \n // convert the selector back into a string\r\ \n @if length($selector) == 1 {\r\ \n $selector: nth($selector, 1);\r\ \n }\r\ \n $selector: str-replace(inspect($selector), \', \', \' \');\r\ \n \r\ \n // Re-build the parent selector\r\ \n $parents: append($parents, $selector, comma);\r\ \n }\r\ \n \r\ \n // remove duplicate selectors\r\ \n $parents: remove-duplicates($parents);\r\ \n \r\ \n @if length($parents) == 1 {\r\ \n $parents: nth($parents, 1);\r\ \n }\r\ \n \r\ \n @if ($parents == \'()\') {\r\ \n @at-root #{$selectors} {\r\ \n @content;\r\ \n }\r\ \n } @else {\r\ \n @at-root #{$parents} {\r\ \n #{$selectors} {\r\ \n @content;\r\ \n }\r\ \n }\r\ \n }\r\ \n \r\ \n }\r\ \n \r\ \n @mixin modifier($modifier) {\r\ \n $selectors: &;\r\ \n \r\ \n @if str-index(inspect(&), \'.#{$module}\') {\r\ \n $selectors: ();\r\ \n \r\ \n @for $i from 1 through length(&) {\r\ \n @if $i % 2 == 0 {\r\ \n $selectors: append($selectors, nth(&, $i), comma);\r\ \n }\r\ \n }\r\ \n }\r\ \n \r\ \n @at-root #{$selectors} {\r\ \n $modifier-selectors: ();\r\ \n \r\ \n @each $item in $modifier {\r\ \n $modifier-selectors: join(\r\ \n $modifier-selectors, \'&[class*=\"--#{$modifier}\"]\', comma\r\ \n );\r\ \n }\r\ \n \r\ \n #{$modifier-selectors} {\r\ \n @content;\r\ \n }\r\ \n }\r\ \n }\r\ \n \r\ \n @mixin button($custom:()) {\r\ \n $buttons: config((\r\ \n \'group-spacing\': 1em\r\ \n ), $custom);\r\ \n \r\ \n @include module(\'button\') {\r\ \n @include component(\'group\') {\r\ \n content: \'fizzbuzz\';\r\ \n @include module {\r\ \n margin-left: this(\'group-spacing\');\r\ \n &:first-child {\r\ \n margin-left: 0;\r\ \n }\r\ \n }\r\ \n }\r\ \n }\r\ \n }\r\ \n \r\ \n @include button();\r\ \n \r\ \n @include module(\'modal\') {\r\ \n @include modifier(\'animate\') {\r\ \n @include modifier(\'zoom\') {\r\ \n content: \"fizzbuzz\"\r\ \n }\r\ \n }\r\ \n }" ) .unwrap(), ".button__group, [class*=\"button__group-\"] {\ \n content: \'fizzbuzz\';\ \n}\ \n.button__group .button, .button__group [class*=\"button--\"], [class*=\"button__group-\"] .button, [class*=\"button__group-\"] [class*=\"button--\"] {\ \n margin-left: 1em;\ \n}\ \n.button__group .button:first-child, .button__group [class*=\"button--\"]:first-child, [class*=\"button__group-\"] .button:first-child, [class*=\"button__group-\"] [class*=\"button--\"]:first-child {\ \n margin-left: 0;\ \n}\ \n[class*=\"modal--\"][class*=\"--animate\"][class*=\"--zoom\"] {\ \n content: \"fizzbuzz\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_254.hrx" #[test] fn issue_254() { assert_eq!( rsass( "@mixin simple-media-query($max-width, $min-width) {\r\ \n @media only screen and (max-width: $max-width) and (min-width: $min-width) {\r\ \n @content;\r\ \n }\r\ \n}\r\ \n\r\ \n@mixin test($value) {\r\ \n border-color: $value;\r\ \n}\r\ \n\r\ \nbody \r\ \n{\r\ \n @include test(\"#ccc\");\r\ \n @include simple-media-query(900px, 400px) {\r\ \n border-color: black;\r\ \n }\r\ \n}" ) .unwrap(), "body {\ \n border-color: \"#ccc\";\ \n}\ \n@media only screen and (max-width: 900px) and (min-width: 400px) {\ \n body {\ \n border-color: black;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2560.hrx" #[test] fn issue_2560() { assert_eq!( rsass( "$x: 10px / 5px;\r\ \n\r\ \ntest {\r\ \n font-size: $x;\r\ \n font-size: #{$x};\r\ \n}" ) .unwrap(), "test {\ \n font-size: 2;\ \n font-size: 2;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2569.hrx" // Ignoring "issue_2569", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_257.hrx" #[test] fn issue_257() { assert_eq!( rsass("body{background:blue; a{color:black;}}").unwrap(), "body {\ \n background: blue;\ \n}\ \nbody a {\ \n color: black;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2582.hrx" #[test] fn issue_2582() { assert_eq!( rsass( ".test {\r\ \n font-size: (16px / 16px) + 0em;\r\ \n font-size: (16px / 16px + 0em);\r\ \n font-size: 16px / 16px + 0em;\r\ \n}" ) .unwrap(), ".test {\ \n font-size: 1em;\ \n font-size: 1em;\ \n font-size: 1em;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2625.hrx" #[test] fn issue_2625() { assert_eq!( rsass( "something\\:{ padding: 2px; }\ \n" ) .unwrap(), "something\\: {\ \n padding: 2px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2633.hrx" #[test] #[ignore] // unexepected error fn issue_2633() { assert_eq!( rsass( "$sel1: \'.something__child + .something__child--mod1\';\ \n$sel2: \'.something__child ~ .something__child--mod2\';\ \n$result1: selector-unify($sel1, $sel2);\ \n\ \n#{$result1} {\ \n /* nothing */\ \n}\ \n\ \n.a {\ \n color: blue;\ \n & > * {\ \n @at-root #{selector-unify(&, \'.b\')} {\ \n color: red;\ \n }\ \n }\ \n}\ \n\ \n.a, .b {\ \n color: blue;\ \n & > * {\ \n @at-root #{selector-unify(&, \'.c, .d\')} {\ \n color: red;\ \n }\ \n }\ \n}\ \n" ) .unwrap(), ".something__child + .something__child--mod1.something__child--mod2 {\ \n /* nothing */\ \n}\ \n.a {\ \n color: blue;\ \n}\ \n.a > .b {\ \n color: red;\ \n}\ \n.a, .b {\ \n color: blue;\ \n}\ \n.a > .c, .a > .d, .b > .c, .b > .d {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_267.hrx" #[test] fn issue_267() { assert_eq!( rsass( "$x: foo;\r\ \n@keyframes $x {\r\ \n to {\r\ \n blah: blah;\r\ \n }\r\ \n}" ) .unwrap(), "@keyframes $x {\ \n to {\ \n blah: blah;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2697.hrx" #[test] fn issue_2697() { assert_eq!( rsass( ".Card {\ \n &:not(.is-open, .is-static) {\ \n .CardContents {\ \n display: none;\ \n }\ \n }\ \n}\ \n" ) .unwrap(), ".Card:not(.is-open, .is-static) .CardContents {\ \n display: none;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_274.hrx" #[test] #[ignore] // wrong result fn issue_274() { assert_eq!( rsass( "input[type=submit],\r\ \ninput[type=reset],\r\ \ninput[type=button]\r\ \n{\r\ \n filter:chroma(color=#000000);\r\ \n}" ) .unwrap(), "input[type=submit],\ \ninput[type=reset],\ \ninput[type=button] {\ \n filter: chroma(color=#000000);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2779.hrx" // Ignoring "issue_2779", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_279.hrx" #[test] #[ignore] // wrong result fn issue_279() { assert_eq!( rsass( ".theme {\ \n @import \"foo.scss\";\ \n}\ \n" ) .unwrap(), ".theme .test-hello, .theme .test-world {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2808.hrx" #[test] fn issue_2808() { assert_eq!( rsass( "test {\ \n content: str-slice(abcdef, -10, 2)\ \n}\ \n" ) .unwrap(), "test {\ \n content: ab;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2863.hrx" // From "sass-spec/spec/libsass-closed-issues/issue_2884.hrx" #[test] #[ignore] // wrong result fn issue_2884() { assert_eq!( rsass( "$titles: \"foo\", \"bar\", \"BaZ\";\ \n\ \n%border {\ \n border: 1px solid;\ \n}\ \n\ \n@mixin border-red {\ \n border-color: red;\ \n}\ \n\ \n@mixin border-blue {\ \n border-color: blue;\ \n}\ \n\ \n@each $t in $titles {\ \n p[title=\"#{$t}\" i] {\ \n @extend %border;\ \n @include border-red;\ \n }\ \n p[title=\"#{$t}\"] {\ \n @extend %border;\ \n @include border-blue;\ \n }\ \n}\ \n" ) .unwrap(), "p[title=BaZ], p[title=BaZ i], p[title=bar], p[title=bar i], p[title=foo], p[title=foo i] {\ \n border: 1px solid;\ \n}\ \np[title=foo i] {\ \n border-color: red;\ \n}\ \np[title=foo] {\ \n border-color: blue;\ \n}\ \np[title=bar i] {\ \n border-color: red;\ \n}\ \np[title=bar] {\ \n border-color: blue;\ \n}\ \np[title=BaZ i] {\ \n border-color: red;\ \n}\ \np[title=BaZ] {\ \n border-color: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_289.hrx" #[test] fn issue_289() { assert_eq!( rsass( "@import url(http://fonts.googleapis.com/css?family=Titillium+Web:400,300,200,600);" ) .unwrap(), "@import url(http://fonts.googleapis.com/css?family=Titillium+Web:400,300,200,600);\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2959.hrx" #[test] #[ignore] // wrong result fn issue_2959() { assert_eq!( rsass( "%color {\ \n\tcolor: blue;\ \n}\ \n\ \n@mixin getOverridedSelector {\ \n\t&#{&} {\ \n\t\t@content;\ \n\t}\ \n}\ \n\ \n.foo {\ \n\t@include getOverridedSelector {\ \n\t\t@extend %color;\ \n\t}\ \n}\ \n\ \n.bar {\ \n\t@include getOverridedSelector {\ \n\t\tcolor: red;\ \n\t}\ \n}\ \n" ) .unwrap(), ".foo.foo {\ \n color: blue;\ \n}\ \n.bar.bar {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2975.hrx" #[test] fn issue_2975() { assert_eq!( rsass( "@mixin test($name: false) {\ \n $a: \"\";\ \n $b: \"\";\ \n @if $name {\ \n $a: \"-#{$name}\"; // works as expected\ \n $b: -$name; // here occurs the bug\ \n } @else {\ \n $a: \"\";\ \n $b: \"\";\ \n }\ \n \ \n .test-a#{$a} {\ \n display: block;\ \n }\ \n .test-b#{$b} {\ \n display: block;\ \n }\ \n}\ \n\ \n@include test;\ \n@include test(asdf);\ \n@include test(foo1);\ \n@include test(bar1);\ \n// @include test(\"foo2\");\ \n// @include test(\"bar2\");\ \n" ) .unwrap(), ".test-a {\ \n display: block;\ \n}\ \n.test-b {\ \n display: block;\ \n}\ \n.test-a-asdf {\ \n display: block;\ \n}\ \n.test-b-asdf {\ \n display: block;\ \n}\ \n.test-a-foo1 {\ \n display: block;\ \n}\ \n.test-b-foo1 {\ \n display: block;\ \n}\ \n.test-a-bar1 {\ \n display: block;\ \n}\ \n.test-b-bar1 {\ \n display: block;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2980.hrx" #[test] fn issue_2980() { assert_eq!( rsass( "$config: (\ \n phone: (\ \n break-point-width:0px,\ \n break-point-name: xs\ \n ),\ \n tablet: (\ \n break-point-width:600px,\ \n break-point-name: sm\ \n ),\ \n laptop: (\ \n break-point-width:900px,\ \n break-point-name: md\ \n ),\ \n desktop: (\ \n break-point-width:1200px,\ \n break-point-name:lg\ \n ),\ \n);\ \n\ \n@each $key, $map in $config {\ \n $break-point-width: map_get($map, break-point-width);\ \n $break-point-name: map_get($map, break-point-name);\ \n $infix: if($break-point-width == 0px, null, -$break-point-name);\ \n .foo#{$infix} {\ \n content: \'#{$break-point-name}\';\ \n }\ \n}\ \n" ) .unwrap(), ".foo {\ \n content: \"xs\";\ \n}\ \n.foo-sm {\ \n content: \"sm\";\ \n}\ \n.foo-md {\ \n content: \"md\";\ \n}\ \n.foo-lg {\ \n content: \"lg\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_2994.hrx" #[test] #[ignore] // wrong result fn issue_2994() { assert_eq!( rsass( ".one-screen-page {\ \n\t@extend %context-dark;\ \n}\ \n\ \n%context-dark {\ \n\t.button-secondary-outline {\ \n\t\t&:hover,\ \n\t\t&:focus,\ \n\t\t&:active,\ \n\t\t&:hover {\ \n\t\t\tcolor: #fca;\ \n\t\t}\ \n\t}\ \n}\ \n" ) .unwrap(), ".one-screen-page .button-secondary-outline:hover, .one-screen-page .button-secondary-outline:focus, .one-screen-page .button-secondary-outline:active {\ \n color: #fca;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_308.hrx" #[test] fn issue_308() { assert_eq!( rsass( "$var: orange;\ \n\ \n.test {\ \n color: $var;\ \n}\ \n\ \n.#{$var} {\ \n color: #C0362C;\ \n}\ \n" ) .unwrap(), ".test {\ \n color: orange;\ \n}\ \n.orange {\ \n color: #C0362C;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_309.hrx" #[test] fn issue_309() { assert_eq!( rsass( "$zzz: zzz;\r\ \na[data-foo=\"#{$zzz}\"] { a: b; }" ) .unwrap(), "a[data-foo=zzz] {\ \n a: b;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_312.hrx" #[test] fn issue_312() { assert_eq!( rsass( "@for $i from 0 through 10 {\r\ \n .foo [index = \"#{$i}\"] {\r\ \n transform: translateY($i * 100%);\r\ \n }\r\ \n}" ) .unwrap(), ".foo [index=\"0\"] {\ \n transform: translateY(0%);\ \n}\ \n.foo [index=\"1\"] {\ \n transform: translateY(100%);\ \n}\ \n.foo [index=\"2\"] {\ \n transform: translateY(200%);\ \n}\ \n.foo [index=\"3\"] {\ \n transform: translateY(300%);\ \n}\ \n.foo [index=\"4\"] {\ \n transform: translateY(400%);\ \n}\ \n.foo [index=\"5\"] {\ \n transform: translateY(500%);\ \n}\ \n.foo [index=\"6\"] {\ \n transform: translateY(600%);\ \n}\ \n.foo [index=\"7\"] {\ \n transform: translateY(700%);\ \n}\ \n.foo [index=\"8\"] {\ \n transform: translateY(800%);\ \n}\ \n.foo [index=\"9\"] {\ \n transform: translateY(900%);\ \n}\ \n.foo [index=\"10\"] {\ \n transform: translateY(1000%);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_338.hrx" #[test] #[ignore] // unexepected error fn issue_338() { assert_eq!( rsass( "$list: (\"a\", \"b\");\ \n\ \ntest {\ \n content: if( length($list) > 2, nth($list, 3), nth($list, 1) );\ \n}\ \n" ) .unwrap(), "test {\ \n content: \"a\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_344.hrx" #[test] fn issue_344() { assert_eq!( rsass( "$variable: 1;\ \n\ \n$foo: #{$variable}px;\ \n$bar: #{1}px;\ \n$baz: \"1px\";\ \n\ \ndiv {\ \n top: -$foo;\ \n top: -$bar;\ \n top: -$baz;\ \n}\ \n" ) .unwrap(), "div {\ \n top: -1px;\ \n top: -1px;\ \n top: -\"1px\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_346.hrx" #[test] fn issue_346() { assert_eq!( rsass( "$mediaquery: \'and (min-width: 300px)\';\ \n\ \n@media all #{$mediaquery} {\ \n div {\ \n display: block;\ \n }\ \n}\ \n" ) .unwrap(), "@media all and (min-width: 300px) {\ \n div {\ \n display: block;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_349.hrx" #[test] fn issue_349() { assert_eq!( rsass( "div {\ \n blah: not true;\ \n}\ \n" ) .unwrap(), "div {\ \n blah: false;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_368.hrx" #[test] fn issue_368() { assert_eq!( rsass( "@if true {\ \n div {\ \n background: green;\ \n }\ \n}\ \n@if not true {\ \n div {\ \n background: red;\ \n }\ \n}\ \n@if not not true {\ \n div {\ \n background: blue;\ \n }\ \n}\ \n@if not (true or false) {\ \n div {\ \n background: black;\ \n }\ \n}" ) .unwrap(), "div {\ \n background: green;\ \n}\ \ndiv {\ \n background: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_394.hrx" #[test] fn issue_394() { assert_eq!( rsass( "$list1: alpha beta gamma;\ \n$list2: one two three;\ \n\ \n$map: (alpha: one, beta: two, gamma: three);\ \n\ \n.ma-list {\ \n @each $item1, $item2 in zip($list1, $list2) {\ \n #{$item1}: $item2;\ \n }\ \n}\ \n\ \n.ma-map {\ \n @each $key, $value in $map {\ \n #{$key}: $value;\ \n }\ \n}" ) .unwrap(), ".ma-list {\ \n alpha: one;\ \n beta: two;\ \n gamma: three;\ \n}\ \n.ma-map {\ \n alpha: one;\ \n beta: two;\ \n gamma: three;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_424.hrx" #[test] fn issue_424() { assert_eq!( rsass( "footer {\r\ \n color: red;\r\ \n}\r\ \n\r\ \n// Ampersand in SassScript:\r\ \n/*.button {\r\ \n &-primary {\r\ \n background: orange;\r\ \n }\r\ \n\r\ \n &-secondary {\r\ \n background: blue;\r\ \n }\r\ \n}*/\r\ \n\r\ \n// Output:\r\ \n.button-primary {\r\ \n background: orange;\r\ \n}\r\ \n\r\ \n.button-secondary {\r\ \n background: blue;\r\ \n}" ) .unwrap(), "footer {\ \n color: red;\ \n}\ \n/*.button {\ \n &-primary {\ \n background: orange;\ \n }\ \n &-secondary {\ \n background: blue;\ \n }\ \n}*/\ \n.button-primary {\ \n background: orange;\ \n}\ \n.button-secondary {\ \n background: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_435.hrx" #[test] fn issue_435() { assert_eq!( rsass( "$skin-name: \"CMS_Black\";\r\ \n\r\ \n$QUOTE: unquote(\'\"\');\r\ \n$EMPTY_STRING: unquote( \"\" );\r\ \n$SLASH: unquote(\"/\");\r\ \n\r\ \n$SKINS_PATH: unquote(\"/CMS/Skins\");\r\ \n$URL_SEPARATOR: $SLASH;\r\ \n$URL_PREFIX: $EMPTY_STRING;\r\ \n$URL_SUFFIX: $EMPTY_STRING;\r\ \n\r\ \n$_URL_PREFIX: $URL_PREFIX + $EMPTY_STRING;\r\ \n$_URL_SUFFIX: $URL_SUFFIX + $EMPTY_STRING;\r\ \n$_URL_SEPARATOR: $URL_SEPARATOR + $EMPTY_STRING;\r\ \n$_SKINS_PATH: $SKINS_PATH + $EMPTY_STRING;\r\ \n\r\ \n@function webresource-image-url( $skin, $control, $file ) \r\ \n{\r\ \n\t$_url: $EMPTY_STRING;\r\ \n\t$_path: $_SKINS_PATH $skin $control;\r\ \n\r\ \n\t@each $_part in $_path {\r\ \n\t\t$_url: $_url + $_part + $_URL_SEPARATOR\r\ \n\t}\r\ \n\r\ \n\t@return $_URL_PREFIX + $QUOTE + $_url + $file + $QUOTE + $_URL_SUFFIX;\r\ \n}\r\ \n\r\ \n@function global-image-url( $skin, $control, $file ) {\r\ \n\t@return webresource-image-url( $skin, $control, $file );\r\ \n}\r\ \n\r\ \n@function skin-image-url( $control, $file ) {\r\ \n\t@return global-image-url( $skin-name, $control, $file );\r\ \n}\r\ \n\r\ \n$actions-sprite: skin-image-url( \"Common\", \"radActionsSprite.png\" );\r\ \n\r\ \n.test \r\ \n{\r\ \n\tbackground-image: url( $actions-sprite );\r\ \n}\r\ \n\r\ \n" ) .unwrap(), ".test {\ \n background-image: url(\"/CMS/Skins/CMS_Black/Common/radActionsSprite.png\");\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_439.hrx" #[test] #[ignore] // wrong result fn issue_439() { assert_eq!( rsass( "@mixin odd( $selector, $n) {\ \n $selector: \"& + \" + $selector + \" + \" + $selector;\ \n $placeholder: unique_id();\ \n %#{$placeholder} { @content; }\ \n #{$selector}:first-child {\ \n #{$selector} { @extend %#{$placeholder}; }\ \n }\ \n}\ \n\ \nul > {\ \n @include odd( li, 5 ) { background: #ccc; }\ \n}\ \n" ) .unwrap(), "ul > + li + li:first-child + li + li {\ \n background: #ccc;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_442.hrx" #[test] fn issue_442() { assert_eq!( rsass( "$lhs: (100/10)#{rem};\ \n$rhs: 10rem;\ \n\ \nfoo {\ \n a: $lhs;\ \n a: $rhs;\ \n a: $lhs == $rhs;\ \n}\ \n" ) .unwrap(), "foo {\ \n a: 10 rem;\ \n a: 10rem;\ \n a: false;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_45.hrx" #[test] #[ignore] // unexepected error fn issue_45() { assert_eq!( rsass( "p:after {\r\ \ncontent:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwYAAAABGdBTUEAALGOfPtRkwAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAAF2+SX8VGAAACeElEQVR42nySy29McRTHP/fOnTvT6bQNrdHKMGGhFkTSELGxwoJY8Q9YWFhYEUJsRSKCsJWikjYSJBIbinpVPJLSRlEkKK2WTnXmvl+/Y4F4tPVJPqtvzjcnJ0cTEQxdY/miFH6gcAJpaWrQl86t05rR9axSKD8UZ6KqJscm5bMdyDDgAYgIBoCORm2G1u0b6w8unJ/bmDG1QtpUmIYiZ8Zk0zEpYmW76tujV9J3/Ep04v0XdR2IDYAdWxYt27Sa8/l8btWIlaYSupgqpNaMUYbC0DUa8qKXWpLGNSvZEETpZO/Z4B5gGQCRMio1xdVfioUIa3AQJ/ZARWhJgkQJKq3wfJ3RwETGhRtPgx7ABtBEhCVNBqViU2tn5+5bLfXmgurIYwJrGFEJmqZh2T4jo2X0YIreZ+7dfeejrcCEiKADfCon3O4fHzp25Nx+8nnqF65lXnEphQUtNBYKaKkMcRgxVY29093JUWCCn+gAORMaTLh0dbCjo/1KO3X1kC6BGIR+QLVioSc+F+9HnW/G1DX+QAcw0j8c/QaHj3UfeN0/MMicEmSL+J5P6DkMDUcfLvZGJ4FwWoHl/lAEXo344zv3dO3ynXJIpg7XdnBtj46bwSnblwH+QQdQ8lsNeNg32nOm/fIh3CGS0OXOQHCv90XYwUyICM2NNX85f26WUnOu5smFzX0vu9qktZjeNtusAbB+XdvfAWDZnjeurX2XST1Y8X6s7zmzYABUrHBaYNshYRC4k340FcZU/1vg2JVpgeP4uJXypHK8soD134In/W+mb+AJvffvvC022It/ve1MaCJCXU6f4UCQy1CbNVONH7/Gw7Md8fsAtddMUh5fveYAAAAASUVORK5CYII=);\r\ \n}" ) .unwrap(), "p:after {\ \n content: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwYAAAABGdBTUEAALGOfPtRkwAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAAF2+SX8VGAAACeElEQVR42nySy29McRTHP/fOnTvT6bQNrdHKMGGhFkTSELGxwoJY8Q9YWFhYEUJsRSKCsJWikjYSJBIbinpVPJLSRlEkKK2WTnXmvl+/Y4F4tPVJPqtvzjcnJ0cTEQxdY/miFH6gcAJpaWrQl86t05rR9axSKD8UZ6KqJscm5bMdyDDgAYgIBoCORm2G1u0b6w8unJ/bmDG1QtpUmIYiZ8Zk0zEpYmW76tujV9J3/Ep04v0XdR2IDYAdWxYt27Sa8/l8btWIlaYSupgqpNaMUYbC0DUa8qKXWpLGNSvZEETpZO/Z4B5gGQCRMio1xdVfioUIa3AQJ/ZARWhJgkQJKq3wfJ3RwETGhRtPgx7ABtBEhCVNBqViU2tn5+5bLfXmgurIYwJrGFEJmqZh2T4jo2X0YIreZ+7dfeejrcCEiKADfCon3O4fHzp25Nx+8nnqF65lXnEphQUtNBYKaKkMcRgxVY29093JUWCCn+gAORMaTLh0dbCjo/1KO3X1kC6BGIR+QLVioSc+F+9HnW/G1DX+QAcw0j8c/QaHj3UfeN0/MMicEmSL+J5P6DkMDUcfLvZGJ4FwWoHl/lAEXo344zv3dO3ynXJIpg7XdnBtj46bwSnblwH+QQdQ8lsNeNg32nOm/fIh3CGS0OXOQHCv90XYwUyICM2NNX85f26WUnOu5smFzX0vu9qktZjeNtusAbB+XdvfAWDZnjeurX2XST1Y8X6s7zmzYABUrHBaYNshYRC4k340FcZU/1vg2JVpgeP4uJXypHK8soD134In/W+mb+AJvffvvC022It/ve1MaCJCXU6f4UCQy1CbNVONH7/Gw7Md8fsAtddMUh5fveYAAAAASUVORK5CYII=);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_453.hrx" #[test] fn issue_453() { assert_eq!( rsass( "div {\ \n --a: 2px;\ \n top: var(--a);\ \n}\ \n" ) .unwrap(), "div {\ \n --a: 2px;\ \n top: var(--a);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_456.hrx" #[test] fn issue_456() { assert_eq!( rsass( "body {\ \n -webkit-filter: invert(100%);\ \n}\ \n" ) .unwrap(), "body {\ \n -webkit-filter: invert(100%);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_469.hrx" #[test] #[ignore] // wrong result fn issue_469() { assert_eq!( rsass( "/*!\ \n*/\ \n\ \n@charset \"utf-8\";\ \n\ \na {\ \n color: red;\ \n}\ \n\ \n@import url(\"x\");\ \n" ) .unwrap(), "/*!\ \n*/\ \n@import url(\"x\");\ \na {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_472.hrx" #[test] #[ignore] // wrong result fn issue_472() { assert_eq!( rsass( "div {\ \n display: block;\ \n @keyframes {\ \n from {\ \n foo: bar;\ \n }\ \n }\ \n}\ \n" ) .unwrap(), "div {\ \n display: block;\ \n}\ \n@keyframes {\ \n from {\ \n foo: bar;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_478.hrx" #[test] fn issue_478() { assert_eq!( rsass( "$x: \"x\";\ \n$y: \"y\";\ \n#{$x}--#{$y} {\ \n a: 1\ \n}\ \n" ) .unwrap(), "x--y {\ \n a: 1;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_485.hrx" #[test] #[ignore] // wrong result fn issue_485() { assert_eq!( rsass( "@media not all and (monochrome) { a {foo: bar} }\ \n@media not screen and (color), print and (color) { a {foo: bar} }\ \n@media (not (screen and (color))), print and (color) { a {foo: bar} }\ \n" ) .unwrap(), "@media not all and (monochrome) {\ \n a {\ \n foo: bar;\ \n }\ \n}\ \n@media not screen and (color), print and (color) {\ \n a {\ \n foo: bar;\ \n }\ \n}\ \n@media (false), print and (color) {\ \n a {\ \n foo: bar;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_487.hrx" #[test] fn issue_487() { assert_eq!( rsass( "\ \n@mixin flex($grow: 1, $shrink: null, $basis: null) {\ \n -webkit-box-flex: $grow;\ \n -webkit-flex: $grow $shrink $basis;\ \n -moz-box-flex: $grow;\ \n -moz-flex: $grow $shrink $basis;\ \n -ms-flex: $grow $shrink $basis;\ \n flex: $grow $shrink $basis;\ \n}\ \n\ \n[flex] {\ \n @include flex;\ \n}\ \n" ) .unwrap(), "[flex] {\ \n -webkit-box-flex: 1;\ \n -webkit-flex: 1;\ \n -moz-box-flex: 1;\ \n -moz-flex: 1;\ \n -ms-flex: 1;\ \n flex: 1;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_492.hrx" #[test] fn issue_492() { assert_eq!( rsass( "$map: (\ \n foo: bar,\ \n baz: monkey,\ \n);\ \n\ \n.css {\ \n @each $key, $value in $map {\ \n #{$key}: $value;\ \n }\ \n}\ \n\ \n$list: one two, three four five, six seven;\ \n\ \n.list {\ \n @each $foo, $bar, $baz in $list {\ \n #{$foo}: $bar $baz;\ \n }\ \n}\ \n" ) .unwrap(), ".css {\ \n foo: bar;\ \n baz: monkey;\ \n}\ \n.list {\ \n one: two;\ \n three: four five;\ \n six: seven;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_495.hrx" #[test] fn issue_495() { assert_eq!( rsass( "/* Testing to make sure that a trailing comma doesn\'t break the tests */\ \n$map: (\ \n hello: world,\ \n);\ \n" ) .unwrap(), "/* Testing to make sure that a trailing comma doesn\'t break the tests */\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_502.hrx" #[test] #[ignore] // unexepected error fn issue_502() { assert_eq!( rsass( "$a: 1;;\ \n;;\ \n" ) .unwrap(), "" ); } // From "sass-spec/spec/libsass-closed-issues/issue_506.hrx" #[test] fn issue_506() { assert_eq!( rsass( "$list: foo bar baz;\ \n$list--comma: foo, bar, baz;\ \n$single: foo;\ \n\ \ndiv {\ \n _list-space: list-separator($list);\ \n _list-comma: list-separator($list--comma);\ \n _single-item: list-separator($single);\ \n}" ) .unwrap(), "div {\ \n _list-space: space;\ \n _list-comma: comma;\ \n _single-item: space;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_509.hrx" #[test] #[ignore] // unexepected error fn issue_509() { assert_eq!( rsass( "$foo: (\ \n (key1): (value-1-0),\ \n key2: value-2-0,\ \n (key6): (value-6-0),\ \n key-3-0 key-3-1 key-3-2: value-3-0 value-3-1 value-3-2,\ \n key4: (value-4-0, value-4-1, value-4-2),\ \n key5: (key-5-0: value-5-1),\ \n (key-7-0: key-7-1): (value-7-0: value-7-1),\ \n (key-8-0, key-8-1, key-8-2): (value-8-0, value-8-1, value-8-2),\ \n);\ \n\ \ndiv {\ \n foo: map-get((foo: 1, bar: 2), foo);\ \n foo: map-get((foo: 1, bar: 2), bar);\ \n foo: map-get((foo: 1, bar: 2), baz);\ \n foo: map-get((), foo);\ \n foo: map-get($foo, (key-5-0: value-5-1));\ \n foo: map-get($foo, (key2));\ \n foo: map-get($foo, (key-3-0 key-3-1 key-3-2));\ \n}\ \n" ) .unwrap(), "div {\ \n foo: 1;\ \n foo: 2;\ \n foo: value-2-0;\ \n foo: value-3-0 value-3-1 value-3-2;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_510.hrx" #[test] fn issue_510() { assert_eq!( rsass( "$before: map-remove((foo: 1, bar: 2, baz: 3, burp: 4), bar, baz);\ \n$after: (foo: 1, burp: 4);\ \n\ \ndiv {\ \n foo: $before == $after;\ \n}" ) .unwrap(), "div {\ \n foo: true;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_512.hrx" #[test] fn issue_512() { assert_eq!( rsass( "$list: a b c;\ \n.css {\ \n debug: index($list, a);\ \n\ \n @if type-of(index($list, 2)) == \"null\" {\ \n debug: foo;\ \n }\ \n}\ \n" ) .unwrap(), ".css {\ \n debug: 1;\ \n debug: foo;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_534.hrx" #[test] fn issue_534() { assert_eq!( rsass( "$foo: (\ \n 1: foo1 bar1,\ \n 10: foo2 bar2,\ \n 100: foo3 bar3,\ \n);\ \n\ \ndiv {\ \n foo: map-get($foo, 1);\ \n foo: map-get($foo, 10);\ \n foo: map-get($foo, 100);\ \n}\ \n" ) .unwrap(), "div {\ \n foo: foo1 bar1;\ \n foo: foo2 bar2;\ \n foo: foo3 bar3;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_535.hrx" #[test] fn issue_535() { assert_eq!( rsass( "$width: 10;\ \n\ \n.test {\ \n margin-left: - 54 * $width - 1;\ \n}\ \n" ) .unwrap(), ".test {\ \n margin-left: -541;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_54.hrx" #[test] #[ignore] // wrong result fn issue_54() { assert_eq!( rsass( "@mixin opacity($percent) {\r\ \n foo { test: opacity($percent); }\r\ \n}\r\ \n\r\ \n@-webkit-keyframes uiDelayedFadeIn {\r\ \n 0% { @include opacity(0.01); }\r\ \n 50% { @include opacity(0.01); }\r\ \n 100% { @include opacity(1); }\r\ \n}\r\ \n\r\ \n@-webkit-keyframes bounce {\r\ \n from {\r\ \n left: 0px;\r\ \n }\r\ \n to {\r\ \n left: 200px;\r\ \n }\r\ \n}\r\ \n" ) .unwrap(), "@-webkit-keyframes uiDelayedFadeIn {\ \n 0% {\ \n foo {\ \n test: opacity(0.01);\ \n }\ \n }\ \n 50% {\ \n foo {\ \n test: opacity(0.01);\ \n }\ \n }\ \n 100% {\ \n foo {\ \n test: opacity(1);\ \n }\ \n }\ \n}\ \n@-webkit-keyframes bounce {\ \n from {\ \n left: 0px;\ \n }\ \n to {\ \n left: 200px;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_548.hrx" #[test] fn issue_548() { assert_eq!( rsass( ".parent-sel-value {\ \n font-family: &;\ \n .parent-sel-interpolation {\ \n font-family: #{&};\ \n .parent-sel-value-concat {\ \n font-family: \"Current parent: \" + &;\ \n }\ \n }\ \n}\ \n" ) .unwrap(), ".parent-sel-value {\ \n font-family: .parent-sel-value;\ \n}\ \n.parent-sel-value .parent-sel-interpolation {\ \n font-family: .parent-sel-value .parent-sel-interpolation;\ \n}\ \n.parent-sel-value .parent-sel-interpolation .parent-sel-value-concat {\ \n font-family: \"Current parent: .parent-sel-value .parent-sel-interpolation .parent-sel-value-concat\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_549.hrx" #[test] #[ignore] // wrong result fn issue_549() { assert_eq!( rsass( "$value: 10;\ \n\ \nfoo {\ \n filter: foo(opacity=$value*100);\ \n}\ \n" ) .unwrap(), "foo {\ \n filter: foo(opacity=1000);\ \n}\ \n" ); } mod issue_550; // From "sass-spec/spec/libsass-closed-issues/issue_552.hrx" #[test] #[ignore] // wrong result fn issue_552() { assert_eq!( rsass( "a,\ \ndiv {\ \n top: 0;\ \n}\ \n\ \n.a,\ \n.b {\ \n &.c {\ \n color: red;\ \n }\ \n}\ \n" ) .unwrap(), "a,\ \ndiv {\ \n top: 0;\ \n}\ \n.a.c,\ \n.b.c {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_553.hrx" #[test] #[ignore] // wrong result fn issue_553() { assert_eq!( rsass( "$foo\\bar: 1;\ \n\ \n@function foo\\func() { @return 1; }\ \n@mixin foo\\mixin() { mixin-value: 1; }\ \n\ \n.test {\ \n var-value: $foo\\bar;\ \n func-value: foo\\func();\ \n @include foo\\mixin();\ \n}\ \n" ) .unwrap(), ".test {\ \n var-value: 1;\ \n func-value: 1;\ \n mixin-value: 1;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_555.hrx" #[test] #[ignore] // wrong result fn issue_555() { assert_eq!( rsass( "\ \n@function hello($name) {\ \n @return $name;\ \n}\ \n\ \n$foo: (\ \n bar() : baz,\ \n bar(\"foo\") : blah,\ \n hello(\"bob\") : bam,\ \n);\ \n\ \na {\ \n foo: map-get($foo, \"bar()\");\ \n foo: map-get($foo, \"bar(\\\"foo\\\")\");\ \n foo: map-get($foo, \'bar(\"foo\")\');\ \n foo: map-get($foo, \"bob\");\ \n}\ \n" ) .unwrap(), "a {\ \n foo: baz;\ \n foo: blah;\ \n foo: blah;\ \n foo: bam;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_556.hrx" #[test] #[ignore] // wrong result fn issue_556() { assert_eq!( rsass( "$test: (\ \n one: 1,\ \n two: 2,\ \n);\ \n\ \n$expect: (\ \n two: 2,\ \n one: 1,\ \n);\ \n\ \n.test {\ \n equal: $test == $expect;\ \n}\ \n" ) .unwrap(), ".test {\ \n equal: true;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_557.hrx" #[test] fn issue_557() { assert_eq!( rsass( "\ \na {\ \n foo: map-get((foo: 1, bar: 2), \"bar\");\ \n}\ \n" ) .unwrap(), "a {\ \n foo: 2;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_558.hrx" #[test] fn issue_558() { assert_eq!( rsass( "@function is_gold($c) {\r\ \n @if ($c == gold) {\r\ \n @return \'yes\';\r\ \n }\r\ \n @return \'no\';\r\ \n}\r\ \n\r\ \ndiv {\r\ \n foo: is_gold(gold);\r\ \n bar: is_gold(white);\r\ \n}" ) .unwrap(), "div {\ \n foo: \"yes\";\ \n bar: \"no\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_56.hrx" #[test] fn issue_56() { assert_eq!( rsass( "@media (min-width: 980px) {\r\ \n a {\r\ \n color: red;\r\ \n }\r\ \n}" ) .unwrap(), "@media (min-width: 980px) {\ \n a {\ \n color: red;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_574.hrx" #[test] fn issue_574() { assert_eq!( rsass( "$flow: left;\ \n\ \n$map: (\ \n margin-#{$flow}: 3em,\ \n foo: bar,\ \n);\ \n\ \n.test {\ \n margin-left: map-get($map, margin-left);\ \n}\ \n" ) .unwrap(), ".test {\ \n margin-left: 3em;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_575.hrx" #[test] fn issue_575() { assert_eq!( rsass( ".test {\ \n @if (foo: bar) == (foo: bar) {\ \n foo: bar;\ \n }\ \n}\ \n" ) .unwrap(), ".test {\ \n foo: bar;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_577.hrx" #[test] fn issue_577() { assert_eq!( rsass( "@function map-each($map) {\ \n $values: ();\ \n\ \n @each $key, $value in $map {\ \n $values: append($values, $value);\ \n }\ \n\ \n @return $values;\ \n}\ \n\ \n$map: (foo: bar);\ \n\ \n.test {\ \n -map-test: map-each($map);\ \n}\ \n" ) .unwrap(), ".test {\ \n -map-test: bar;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_578.hrx" #[test] fn issue_578() { assert_eq!( rsass( "$list: one foo three bar six seven;\ \n$pos: set-nth($list, 2, two);\ \n$neg: set-nth($pos, -3, four five);\ \n\ \n.test {\ \n -positive: $pos;\ \n -negative: $neg;\ \n}\ \n" ) .unwrap(), ".test {\ \n -positive: one two three bar six seven;\ \n -negative: one two three four five six seven;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_579.hrx" #[test] #[ignore] // wrong result fn issue_579() { assert_eq!( rsass( "$map: (\ \n foo: fump,\ \n bar: bump,\ \n);\ \n\ \n@mixin vararg-test($foo, $bar) {\ \n foo: $foo;\ \n bar: $bar;\ \n}\ \n\ \n.test {\ \n @include vararg-test($map...);\ \n}\ \n" ) .unwrap(), ".test {\ \n foo: fump;\ \n bar: bump;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_58.hrx" #[test] fn issue_58() { assert_eq!( rsass( "test {\r\ \n background: url(/static_loc/img/beta.png);\r\ \n}" ) .unwrap(), "test {\ \n background: url(/static_loc/img/beta.png);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_59.hrx" #[test] fn issue_59() { assert_eq!( rsass( "@mixin apply-to-ie6-only {\r\ \n * html {\r\ \n @content;\r\ \n }\r\ \n}\r\ \n@include apply-to-ie6-only {\r\ \n #logo {\r\ \n background-image: url(/logo.gif);\r\ \n }\r\ \n}" ) .unwrap(), "* html #logo {\ \n background-image: url(/logo.gif);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_590.hrx" #[test] fn issue_590() { assert_eq!( rsass( "foo {\ \n foo: 1/2;\ \n foo: 0.5;\ \n foo: (1/2);\ \n foo: 1/2 == 0.5;\ \n foo: (1/2) == 0.5;\ \n}\ \n" ) .unwrap(), "foo {\ \n foo: 1/2;\ \n foo: 0.5;\ \n foo: 0.5;\ \n foo: true;\ \n foo: true;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_592.hrx" #[test] #[ignore] // wrong result fn issue_592() { assert_eq!( rsass( "%a::-webkit-scrollbar {\ \n color: green;\ \n}\ \n\ \n.a {\ \n .b {\ \n @extend %a;\ \n }\ \n\ \n .c .b {\ \n @extend %a;\ \n }\ \n}\ \n" ) .unwrap(), ".a .c .b::-webkit-scrollbar, .a .b::-webkit-scrollbar {\ \n color: green;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_593.hrx" #[test] #[ignore] // wrong result fn issue_593() { assert_eq!( rsass( "h1:nth-of-type(#{2 + \'n + 1\'}) {\ \n color: red;\ \n}\ \n\ \nh1:nth-of-type(#{2 + \'n + 1\'}) {\ \n color: red;\ \n}\ \n" ) .unwrap(), "h1:nth-of-type(2n + 1) {\ \n color: red;\ \n}\ \nh1:nth-of-type(2n + 1) {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_595.hrx" #[test] fn issue_595() { assert_eq!( rsass( "a {\ \n color: red;\ \n};\ \n" ) .unwrap(), "a {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_6.hrx" #[test] fn issue_6() { assert_eq!( rsass( "*[class|=\"has-background\"] {\r\ \n background: #efefef;\r\ \n padding: 7px;\r\ \n border: 1px solid #888;\r\ \n margin-bottom: 5px;\r\ \n }" ) .unwrap(), "*[class|=has-background] {\ \n background: #efefef;\ \n padding: 7px;\ \n border: 1px solid #888;\ \n margin-bottom: 5px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_602" #[test] fn issue_602() { assert_eq!( rsass( "#foo.\\bar {\ \n color: red;\ \n}\ \n\ \n#foo.b\\ar {\ \n color: red;\ \n}\ \n\ \n#foo\\.bar {\ \n color: red;\ \n}\ \n\ \n#foo\\bar {\ \n color: red;\ \n}\ \n\ \n#fo\\o.bar {\ \n color: red;\ \n}\ \n" ) .unwrap(), "@charset \"UTF-8\";\ \n#foo.ºr {\ \n color: red;\ \n}\ \n#foo.b\\a r {\ \n color: red;\ \n}\ \n#foo\\.bar {\ \n color: red;\ \n}\ \n#fooºr {\ \n color: red;\ \n}\ \n#foo.bar {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_610.hrx" #[test] #[ignore] // wrong result fn issue_610() { assert_eq!( rsass( "@mixin vararg-test($a, $b, $c, $d) {\ \n a: $a;\ \n b: $b;\ \n c: $c;\ \n d: $d;\ \n}\ \n\ \nfoo {\ \n @include vararg-test(a, b, c, d);\ \n}\ \n\ \nfoo {\ \n @include vararg-test(a b c d...);\ \n}\ \n\ \nfoo {\ \n @include vararg-test((a b c d)...);\ \n}\ \n\ \nfoo {\ \n @include vararg-test((a, b, c, d)...);\ \n}\ \n\ \nfoo {\ \n @include vararg-test((a: a, b: b, c: c, d: d)...);\ \n}\ \n\ \nfoo {\ \n @include vararg-test((\"a\": a, \"b\": b, \"c\": c, \"d\": d)...);\ \n}\ \n\ \nfoo {\ \n @include vararg-test(a b..., (c: c, d: d)...);\ \n}\ \n\ \nfoo {\ \n @include vararg-test(a, b c..., (d: d)...);\ \n}\ \n\ \nfoo {\ \n @include vararg-test($c: c, (a: a, b: b, d: d)...);\ \n}\ \n" ) .unwrap(), "foo {\ \n a: a;\ \n b: b;\ \n c: c;\ \n d: d;\ \n}\ \nfoo {\ \n a: a;\ \n b: b;\ \n c: c;\ \n d: d;\ \n}\ \nfoo {\ \n a: a;\ \n b: b;\ \n c: c;\ \n d: d;\ \n}\ \nfoo {\ \n a: a;\ \n b: b;\ \n c: c;\ \n d: d;\ \n}\ \nfoo {\ \n a: a;\ \n b: b;\ \n c: c;\ \n d: d;\ \n}\ \nfoo {\ \n a: a;\ \n b: b;\ \n c: c;\ \n d: d;\ \n}\ \nfoo {\ \n a: a;\ \n b: b;\ \n c: c;\ \n d: d;\ \n}\ \nfoo {\ \n a: a;\ \n b: b;\ \n c: c;\ \n d: d;\ \n}\ \nfoo {\ \n a: a;\ \n b: b;\ \n c: c;\ \n d: d;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_613.hrx" #[test] fn issue_613() { assert_eq!( rsass( "$var: 1;\ \n\ \n@mixin test {\ \n $var: 2;\ \n}\ \n\ \n@function test() {\ \n $var: 3;\ \n @return \"dummy\";\ \n}\ \n\ \n.selector {\ \n $var: 4;\ \n @include test;\ \n $dummy: test();\ \n content: $var;\ \n}\ \n\ \n.other-selector {\ \n content: $var;\ \n}\ \n" ) .unwrap(), ".selector {\ \n content: 4;\ \n}\ \n.other-selector {\ \n content: 1;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_615.hrx" #[test] #[ignore] // wrong result fn issue_615() { assert_eq!( rsass( "$foo: \"bar\";\ \n%#{\"foo--#{$foo}\"} {\ \n foo: bar;\ \n}\ \n\ \na {\ \n @extend %foo--bar;\ \n}\ \n" ) .unwrap(), "a {\ \n foo: bar;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_622.hrx" #[test] fn issue_622() { assert_eq!( rsass( "@media screen {\ \n a {\ \n color: red;\ \n }\ \n}\ \n\ \n.link {\ \n @media (foo: bar) {\ \n display: flex;\ \n }\ \n}\ \n" ) .unwrap(), "@media screen {\ \n a {\ \n color: red;\ \n }\ \n}\ \n@media (foo: bar) {\ \n .link {\ \n display: flex;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_623.hrx" #[test] #[ignore] // wrong result fn issue_623() { assert_eq!( rsass( "a {\ \n filter: alpha(opacity=.3); }\ \n\ \ndiv {\ \n filter: alpha(opacity=0.7); }\ \n" ) .unwrap(), "a {\ \n filter: alpha(opacity=0.3);\ \n}\ \ndiv {\ \n filter: alpha(opacity=0.7);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_628.hrx" // Ignoring "issue_628", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_63.hrx" #[test] fn issue_63() { assert_eq!( rsass( "@mixin testComments {\r\ \n\t/* crash */\r\ \n\tp {\r\ \n\t\twidth: 100px;\r\ \n\t}\r\ \n}\r\ \n\r\ \n@media screen and (orientation:landscape) {\r\ \n\t@include testComments;\t\r\ \n}\r\ \n" ) .unwrap(), "@media screen and (orientation: landscape) {\ \n /* crash */\ \n p {\ \n width: 100px;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_639.hrx" #[test] fn issue_639() { assert_eq!( rsass( "$quoted_list: \"foo\", \"bar\", \"baz\";\ \n$unquoted_list: foo, bar, baz;\ \n\ \nfoo {\ \n foo: #{foo, bar, baz};\ \n foo: #{\"foo\", \"bar\", \"baz\"};\ \n foo: #{$quoted_list};\ \n foo: #{$unquoted_list};\ \n}\ \n" ) .unwrap(), "foo {\ \n foo: foo, bar, baz;\ \n foo: foo, bar, baz;\ \n foo: foo, bar, baz;\ \n foo: foo, bar, baz;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_64.hrx" #[test] fn issue_64() { assert_eq!( rsass( "$var: 10px;\r\ \np {\r\ \n\twidth: -$var;\r\ \n}" ) .unwrap(), "p {\ \n width: -10px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_641.hrx" #[test] fn issue_641() { assert_eq!( rsass(".#{\"foo\"}--1 { width:100%; }").unwrap(), ".foo--1 {\ \n width: 100%;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_643.hrx" #[test] fn issue_643() { assert_eq!( rsass( "$map: (foo: bar, bar: baz);\ \n\ \nfoo {\ \n a: nth($map, 2);\ \n}\ \n" ) .unwrap(), "foo {\ \n a: bar baz;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_644.hrx" #[test] fn issue_644() { assert_eq!( rsass( "foo {\ \n background-image: url(foo/#{\"bar\"}/baz.jpg);\ \n}\ \n" ) .unwrap(), "foo {\ \n background-image: url(foo/bar/baz.jpg);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_646.hrx" #[test] fn issue_646() { assert_eq!( rsass( "@function foo() {\ \n /* $bar: 1; */\ \n @return true;\ \n}\ \n\ \nfoo {\ \n foo: foo();\ \n}\ \n" ) .unwrap(), "foo {\ \n foo: true;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_652.hrx" #[test] fn issue_652() { assert_eq!( rsass( "$map: (\ \n purple: foo,\ \n rgba(1,2,3,1): bar,\ \n #ffffff: baz,\ \n);\ \n\ \na {\ \n name: map-get($map, purple) == foo;\ \n func: map-get($map, rgba(1,2,3,1)) == bar;\ \n hex: map-get($map, #ffffff) == baz;\ \n}\ \n" ) .unwrap(), "a {\ \n name: true;\ \n func: true;\ \n hex: true;\ \n}\ \n" ); } mod issue_659; // From "sass-spec/spec/libsass-closed-issues/issue_660.hrx" #[test] fn issue_660() { assert_eq!( rsass( "$foo: true;\ \n\ \ndiv {\ \n blah: $foo;\ \n}\ \n\ \ndiv {\ \n blah: not $foo;\ \n}\ \n\ \ndiv {\ \n blah: not ($foo);\ \n}\ \n\ \ndiv {\ \n blah: not (true);\ \n}\ \n\ \n" ) .unwrap(), "div {\ \n blah: true;\ \n}\ \ndiv {\ \n blah: false;\ \n}\ \ndiv {\ \n blah: false;\ \n}\ \ndiv {\ \n blah: false;\ \n}\ \n" ); } mod issue_666; // From "sass-spec/spec/libsass-closed-issues/issue_67.hrx" #[test] fn issue_67() { assert_eq!( rsass("foo {bar: 70% - 40%}").unwrap(), "foo {\ \n bar: 30%;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_672.hrx" #[test] fn issue_672() { assert_eq!( rsass( "@mixin test($arglist...) {\ \n $map: keywords($arglist);\ \n answer: if($map, \"Yep\", \"Nope\");\ \n}\ \n\ \nwith-keyword-args{\ \n @include test($arg1: one, $arg2: two, $arg3: three);\ \n}\ \nwith-no-args {\ \n @include test();\ \n}\ \nwithout-keyword-args {\ \n @include test(not-a-keyword-arg-1 , not-a-keyword-arg-2);\ \n}\ \n" ) .unwrap(), "with-keyword-args {\ \n answer: \"Yep\";\ \n}\ \nwith-no-args {\ \n answer: \"Yep\";\ \n}\ \nwithout-keyword-args {\ \n answer: \"Yep\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_673.hrx" // Ignoring "issue_673", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_674.hrx" #[test] fn issue_674() { assert_eq!( rsass( "\ \n$base-path:\'../images/\';\ \n$base-attr:\'data-\';\ \n\ \n@function url($src, $path:\'\'){\ \n @return unquote(\'url(\'+$base-path + $path+ $src +\')\');\ \n}\ \n@function url2($src, $path:\'\'){\ \n @return unquote(\'url(\'+ $base-path + $path+ $src +\')\');\ \n}\ \n@function attr($arg1, $arg2:\'\'){\ \n @return unquote(\'attr(\'+$base-attr + $arg1 + $arg2 +\')\');\ \n}\ \n\ \ndiv {\ \n background: url(\'image.png\');\ \n background: url(\'image.png\',\'img/\');\ \n background: url2(\'image.png\',\'img/\');\ \n\ \n &:after {\ \n content: attr(value);\ \n content: attr(value, -extra);\ \n content: url(\'icon.png\');\ \n content: url(\'icon.png\',\'gfx/\');\ \n content: url2(\'icon.png\',\'gfx/\');\ \n }\ \n}\ \n" ) .unwrap(), "div {\ \n background: url(../images/image.png);\ \n background: url(../images/img/image.png);\ \n background: url(../images/img/image.png);\ \n}\ \ndiv:after {\ \n content: attr(data-value);\ \n content: attr(data-value-extra);\ \n content: url(../images/icon.png);\ \n content: url(../images/gfx/icon.png);\ \n content: url(../images/gfx/icon.png);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_683.hrx" #[test] fn issue_683() { assert_eq!( rsass( "foo {\ \n filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\"data:image/png;base64,ABCD\",sizingMethod=crop);\ \n}\ \n" ) .unwrap(), "foo {\ \n filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\"data:image/png;base64,ABCD\",sizingMethod=crop);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_688.hrx" #[test] fn issue_688() { assert_eq!( rsass( "test {\ \n /* Convert to px */\ \n px-to-px: 0px + 1px;\ \n pt-to-px: 0px + 1pt;\ \n pc-to-px: 0px + 1pc;\ \n in-to-px: 0px + 1in;\ \n mm-to-px: 0px + 1mm;\ \n cm-to-px: 0px + 1cm;\ \n /* Convert to pt */\ \n px-to-pt: 0pt + 1px;\ \n pt-to-pt: 0pt + 1pt;\ \n pc-to-pt: 0pt + 1pc;\ \n in-to-pt: 0pt + 1in;\ \n mm-to-pt: 0pt + 1mm;\ \n cm-to-pt: 0pt + 1cm;\ \n /* Convert to pc */\ \n px-to-pc: 0pc + 1px;\ \n pt-to-pc: 0pc + 1pt;\ \n pc-to-pc: 0pc + 1pc;\ \n in-to-pc: 0pc + 1in;\ \n mm-to-pc: 0pc + 1mm;\ \n cm-to-pc: 0pc + 1cm;\ \n /* Convert to in */\ \n px-to-in: 0in + 1px;\ \n pt-to-in: 0in + 1pt;\ \n pc-to-in: 0in + 1pc;\ \n in-to-in: 0in + 1in;\ \n mm-to-in: 0in + 1mm;\ \n cm-to-in: 0in + 1cm;\ \n /* Convert to mm */\ \n px-to-mm: 0mm + 1px;\ \n pt-to-mm: 0mm + 1pt;\ \n pc-to-mm: 0mm + 1pc;\ \n in-to-mm: 0mm + 1in;\ \n mm-to-mm: 0mm + 1mm;\ \n cm-to-mm: 0mm + 1cm; \ \n /* Convert to cm */\ \n px-to-cm: 0cm + 1px;\ \n pt-to-cm: 0cm + 1pt;\ \n pc-to-cm: 0cm + 1pc;\ \n in-to-cm: 0cm + 1in;\ \n mm-to-cm: 0cm + 1mm;\ \n cm-to-cm: 0cm + 1cm; \ \n}\ \n" ) .unwrap(), "test {\ \n /* Convert to px */\ \n px-to-px: 1px;\ \n pt-to-px: 1.3333333333px;\ \n pc-to-px: 16px;\ \n in-to-px: 96px;\ \n mm-to-px: 3.7795275591px;\ \n cm-to-px: 37.7952755906px;\ \n /* Convert to pt */\ \n px-to-pt: 0.75pt;\ \n pt-to-pt: 1pt;\ \n pc-to-pt: 12pt;\ \n in-to-pt: 72pt;\ \n mm-to-pt: 2.8346456693pt;\ \n cm-to-pt: 28.3464566929pt;\ \n /* Convert to pc */\ \n px-to-pc: 0.0625pc;\ \n pt-to-pc: 0.0833333333pc;\ \n pc-to-pc: 1pc;\ \n in-to-pc: 6pc;\ \n mm-to-pc: 0.2362204724pc;\ \n cm-to-pc: 2.3622047244pc;\ \n /* Convert to in */\ \n px-to-in: 0.0104166667in;\ \n pt-to-in: 0.0138888889in;\ \n pc-to-in: 0.1666666667in;\ \n in-to-in: 1in;\ \n mm-to-in: 0.0393700787in;\ \n cm-to-in: 0.3937007874in;\ \n /* Convert to mm */\ \n px-to-mm: 0.2645833333mm;\ \n pt-to-mm: 0.3527777778mm;\ \n pc-to-mm: 4.2333333333mm;\ \n in-to-mm: 25.4mm;\ \n mm-to-mm: 1mm;\ \n cm-to-mm: 10mm;\ \n /* Convert to cm */\ \n px-to-cm: 0.0264583333cm;\ \n pt-to-cm: 0.0352777778cm;\ \n pc-to-cm: 0.4233333333cm;\ \n in-to-cm: 2.54cm;\ \n mm-to-cm: 0.1cm;\ \n cm-to-cm: 1cm;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_690.hrx" #[test] fn issue_690() { assert_eq!( rsass( "test {\ \n left: expression(callSomeFunc());\ \n content: expression(\"Smile :-)\");\ \n}\ \n" ) .unwrap(), "test {\ \n left: expression(callSomeFunc());\ \n content: expression(\"Smile :-)\");\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_694.hrx" #[test] fn issue_694() { assert_eq!( rsass( "// test for libsass 694:\ \n// parser should be smarter about handling quoted quotes\ \n\ \n$str: \'{\' + \'\"foo\": \"bar\"\' + \'}\';\ \n$str2: \'\"hello world\"\';\ \n$str3: \"hello world\";\ \n.interpolation-test {\ \n test: \"#{$str}\";\ \n test: \"#{$str2}\";\ \n test: \"#{$str3}\";\ \n}\ \n" ) .unwrap(), ".interpolation-test {\ \n test: \'{\"foo\": \"bar\"}\';\ \n test: \'\"hello world\"\';\ \n test: \"hello world\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_698.hrx" // Ignoring "issue_698", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_699.hrx" #[test] #[ignore] // wrong result fn issue_699() { assert_eq!( rsass( ".selector {\ \n color: invert(rebeccapurple);\ \n}" ) .unwrap(), ".selector {\ \n color: #99cc66;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_700.hrx" #[test] fn issue_700() { assert_eq!( rsass( ".selector {\ \n color: invert(transparent);\ \n}" ) .unwrap(), ".selector {\ \n color: rgba(255, 255, 255, 0);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_701.hrx" #[test] fn issue_701() { assert_eq!( rsass( ".test-1 {\ \n content: null;\ \n content: inspect(null);\ \n content: inspect(false);\ \n content: inspect(true);\ \n content: inspect(42);\ \n content: inspect(42.3);\ \n content: inspect(42px);\ \n content: inspect(\"string\");\ \n $list: 1, 2, 3;\ \n content: inspect($list);\ \n $map: ( a: 1, b: 2, c: 3 );\ \n content: inspect($map);\ \n}\ \n" ) .unwrap(), ".test-1 {\ \n content: null;\ \n content: false;\ \n content: true;\ \n content: 42;\ \n content: 42.3;\ \n content: 42px;\ \n content: \"string\";\ \n content: 1, 2, 3;\ \n content: (a: 1, b: 2, c: 3);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_702.hrx" #[test] fn issue_702() { assert_eq!( rsass( ".foo {\ \n content: function-exists(\"feature-exists\");\ \n content: feature-exists(\"foo\");\ \n}\ \n" ) .unwrap(), ".foo {\ \n content: true;\ \n content: false;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_703.hrx" #[test] #[ignore] // wrong result fn issue_703() { assert_eq!( rsass( ".test-1 {\ \n @for $i from 1 through 3 {\ \n content: $i;\ \n }\ \n}\ \n\ \n.test-2 {\ \n @for $i from 3 through 1 {\ \n content: $i;\ \n }\ \n}\ \n\ \n.test-3 {\ \n @for $i from 1 to 3 {\ \n content: $i;\ \n }\ \n}\ \n\ \n.test-4 {\ \n @for $i from 3 to 1 {\ \n content: $i;\ \n }\ \n}\ \n" ) .unwrap(), ".test-1 {\ \n content: 1;\ \n content: 2;\ \n content: 3;\ \n}\ \n.test-2 {\ \n content: 3;\ \n content: 2;\ \n content: 1;\ \n}\ \n.test-3 {\ \n content: 1;\ \n content: 2;\ \n}\ \n.test-4 {\ \n content: 3;\ \n content: 2;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_708.hrx" #[test] fn issue_708() { assert_eq!( rsass( "@function foobar($x, $y, $z : 3) {\ \n @return $x + $y * 2 + $z\ \n}\ \n\ \n.foobar {\ \n content: foobar($y:2, $x:4);\ \n content: foobar($y: 2, $x: 4);\ \n content: foobar($y : 2, $x : 4);\ \n content: foobar($y:2px, $x:4);\ \n content: foobar($y: 2px, $x: 4);\ \n content: foobar($y : 2px, $x : 4);\ \n}" ) .unwrap(), ".foobar {\ \n content: 11;\ \n content: 11;\ \n content: 11;\ \n content: 11px;\ \n content: 11px;\ \n content: 11px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_712.hrx" // Ignoring "issue_712", error tests are not supported yet. mod issue_713; // From "sass-spec/spec/libsass-closed-issues/issue_72.hrx" #[test] #[ignore] // wrong result fn issue_72() { assert_eq!( rsass( "test {\r\ \n filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\'#223344\', endColorstr=\'#112233\',GradientType=0 );\r\ \n}\r\ \n\r\ \n@mixin opacity($opacity) {\r\ \n opacity: $opacity / 100;\r\ \n filter: alpha(opacity=$opacity);\r\ \n}" ) .unwrap(), "test {\ \n filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\"#223344\", endColorstr=\"#112233\",GradientType=0 );\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_73.hrx" #[test] fn issue_73() { assert_eq!( rsass( "@mixin box-shadow($shadow...) { \r\ \n -webkit-box-shadow: $shadow;\r\ \n -moz-box-shadow: $shadow;\r\ \n box-shadow: $shadow;\r\ \n}" ) .unwrap(), "" ); } // From "sass-spec/spec/libsass-closed-issues/issue_733.hrx" #[test] fn issue_733() { assert_eq!( rsass( "@function getter() {\ \n @return 42px;\ \n}\ \n\ \ntest {\ \n content: getter()-1;\ \n content: getter()- 1;\ \n content: getter() -1;\ \n}\ \n" ) .unwrap(), "test {\ \n content: 41px;\ \n content: 41px;\ \n content: 42px -1;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_736.hrx" #[test] fn issue_736() { assert_eq!( rsass( "// libsass issue 736: @return does not cause function exit\ \n// https://github.com/sass/libsass/issues/736\ \n\ \n@function contains-true($list) {\ \n @each $bool in $list {\ \n @if $bool {\ \n @return \"found true\";\ \n }\ \n }\ \n @return \"nothing found\";\ \n}\ \n\ \n.test {\ \n out: contains-true(true false false);\ \n out: contains-true(false true false);\ \n out: contains-true(false false true);\ \n}\ \n" ) .unwrap(), ".test {\ \n out: \"found true\";\ \n out: \"found true\";\ \n out: \"found true\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_738.hrx" #[test] fn issue_738() { assert_eq!( rsass( ".foo {\ \n &--bar { color: red; }\ \n &--1bar { color: blue;}\ \n}\ \n" ) .unwrap(), ".foo--bar {\ \n color: red;\ \n}\ \n.foo--1bar {\ \n color: blue;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_740.hrx" #[test] fn issue_740() { assert_eq!( rsass( "$foo: null;\ \n$foo: #fff !default;\ \n$bar: #000;\ \n$bar: #f00 !default;\ \n\ \nfoo {\ \n foo: $foo;\ \n bar: $bar;\ \n}\ \n" ) .unwrap(), "foo {\ \n foo: #fff;\ \n bar: #000;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_748.hrx" #[test] #[ignore] // wrong result fn issue_748() { assert_eq!( rsass( "// problem: not expression is currently returning false on values other than true, false or null\ \n\ \n@function truthyfalsey($bool: null) {\ \n @if not $bool {\ \n @return falsey;\ \n } @else {\ \n @return truthy;\ \n }\ \n}\ \n\ \n.test {\ \n debug: truthyfalsey(true); // expect truthy\ \n debug: truthyfalsey(false); // expect falsey\ \n debug: truthyfalsey(); // expect falsey (default arg is null)\ \n debug: truthyfalsey(5); // expect truthy\ \n debug: truthyfalsey(string); // expect truthy\ \n debug: truthyfalsey((alpha: 1, bravo: 2)); // expect truthy\ \n debug: truthyfalsey(this is a list); // expect truthy\ \n debug: truthyfalsey(\'true\'); // expect truthy\ \n}\ \n" ) .unwrap(), ".test {\ \n debug: truthy;\ \n debug: falsey;\ \n debug: falsey;\ \n debug: truthy;\ \n debug: truthy;\ \n debug: truthy;\ \n debug: truthy;\ \n debug: truthy;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_759.hrx" #[test] fn issue_759() { assert_eq!( rsass( "$a: 10px !global !default;\ \n$b: 20px !default !global;\ \n$c: 30px !default !default !default !global !global !global;\ \n$d: 40px !global !global !global !default !default !default;\ \n$e: 50px !global !default !global !default !global !default;\ \n\ \nfoo {\ \n a: $a;\ \n b: $b;\ \n c: $c;\ \n d: $d;\ \n e: $e;\ \n}\ \n" ) .unwrap(), "foo {\ \n a: 10px;\ \n b: 20px;\ \n c: 30px;\ \n d: 40px;\ \n e: 50px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_760.hrx" #[test] fn issue_760() { assert_eq!( rsass( "foo {\ \n quoted: str-slice(\"abcd\", 1, 0);\ \n unquoted: str-slice(abcd, 1, 0);\ \n}\ \n" ) .unwrap(), "foo {\ \n quoted: \"\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_763.hrx" #[test] fn issue_763() { assert_eq!( rsass( "foo {\ \n a: str-slice(\"abcd\", 1, 1);\ \n b: str-slice(\'abcd\', 1, 1);\ \n c: str-slice(abcd, 1, 1);\ \n\ \n d: str-insert(\"abcd\", \"X\", 1);\ \n e: str-insert(\"abcd\", \'X\', 1);\ \n f: str-insert(\'abcd\', \"X\", 1);\ \n g: str-insert(\'abcd\', \'X\', 1);\ \n}\ \n" ) .unwrap(), "foo {\ \n a: \"a\";\ \n b: \"a\";\ \n c: a;\ \n d: \"Xabcd\";\ \n e: \"Xabcd\";\ \n f: \"Xabcd\";\ \n g: \"Xabcd\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_77.hrx" #[test] fn issue_77() { assert_eq!( rsass( "@mixin m {\r\ \n .m {\r\ \n color: red;\r\ \n @content;\r\ \n }\r\ \n}\r\ \ndiv.a {\r\ \n @include m;\r\ \n}" ) .unwrap(), "div.a .m {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_783" #[test] #[ignore] // wrong result fn issue_783() { assert_eq!( rsass( "// $a: 12px / 1em;\ \n// $b: 6px / 1em;\ \n// $c: 10em;\ \n// $x: -9999em;\ \n// $aa: 1px * 1px;\ \n\ \na {\ \n $foo: 2em;\ \n $bar: 2em;\ \n\ \n foo: $foo; // 2em ✔\ \n bar: $bar; // 2em ✔\ \n // a: $foo * $bar; // 4em*em isn\'t a valid CSS value. ✔\ \n a: $foo / $bar; // 1 ✔\ \n a: $foo + $bar; // 4em ✔\ \n a: $foo - $bar; // 0em ✔\ \n\ \n\ \n $foo: 2px;\ \n $bar: 2em;\ \n\ \n foo: $foo; // 2px ✔\ \n bar: $bar; // 2em ✔\ \n // a: $foo * $bar; // 4em*px isn\'t a valid CSS value. ✔\ \n // a: $foo / $bar; // 1px/em isn\'t a valid CSS value. ✔\ \n // a: $foo + $bar; // Incompatible units: \'em\' and \'px\'. ✔\ \n // a: $foo - $bar; // Incompatible units: \'em\' and \'px\'. ✔\ \n\ \n\ \n $foo: 2em;\ \n $bar: 2px;\ \n\ \n foo: $foo; // 2em ✔\ \n bar: $bar; // 2px ✔\ \n // a: $foo * $bar; // 4em*px isn\'t a valid CSS value. ✔\ \n // a: $foo / $bar; // 1em/px isn\'t a valid CSS value. ✔\ \n // a: $foo + $bar; // Incompatible units: \'px\' and \'em\'. ✔\ \n // a: $foo - $bar; // Incompatible units: \'px\' and \'em\'. ✔\ \n\ \n\ \n $foo: 2px / 2em;\ \n $bar: 2px;\ \n\ \n // foo: $foo; // 1px/em isn\'t a valid CSS value. ✔\ \n bar: $bar; // 2px ✔\ \n // a: $foo * $bar; // 2px*px/em isn\'t a valid CSS value. ✔\ \n // a: $foo / $bar; // 0.5/em isn\'t a valid CSS value. ✔\ \n // a: $foo + $bar; // Incompatible units: \'\' and \'em\'.\ \n // a: $foo - $bar; // Incompatible units: \'\' and \'em\'.\ \n\ \n\ \n $foo: 2em / 2px;\ \n $bar: 2px;\ \n\ \n // foo: $foo; // 1em/px isn\'t a valid CSS value. ✔\ \n bar: $bar; // 2px ✔\ \n a: $foo * $bar; // 2em ✔\ \n // a: $foo / $bar; // 0.5em/px*px isn\'t a valid CSS value. ✔\ \n // a: $foo + $bar; // Incompatible units: \'px\' and \'em\'.\ \n // a: $foo - $bar; // Incompatible units: \'px\' and \'em\'.\ \n\ \n\ \n $foo: 2em / 2px;\ \n $bar: 2em / 2px;\ \n\ \n // foo: $foo; // 1em/px isn\'t a valid CSS value. ✔\ \n // bar: $bar; // 1em/px isn\'t a valid CSS value. ✔\ \n // a: $foo * $bar; // 1em*em/px*px isn\'t a valid CSS value. ✔\ \n a: $foo / $bar; // 1 ✔\ \n // a: $foo + $bar; // 2em/px isn\'t a valid CSS value. ✔\ \n // a: $foo - $bar; // 0em/px isn\'t a valid CSS value. ✔\ \n\ \n\ \n $foo: 2px / 2em;\ \n $bar: 2em / 2px;\ \n\ \n // foo: $foo; // 1px/em isn\'t a valid CSS value. ✔\ \n // bar: $bar; // 1em/px isn\'t a valid CSS value. ✔\ \n a: $foo * $bar; // 1 ✔\ \n // a: $foo / $bar; // 1px*px/em*em isn\'t a valid CSS value. ✔\ \n // a: $foo + $bar; // Incompatible units: \'em\' and \'px\'.\ \n // a: $foo - $bar; // Incompatible units: \'em\' and \'px\'.\ \n\ \n\ \n $foo: 2px;\ \n $bar: 2px / 2em;\ \n\ \n foo: $foo; // 2px ✔\ \n // bar: $bar; // 1px/em isn\'t a valid CSS value. ✔\ \n // a: $foo * $bar; // 2px*px/em isn\'t a valid CSS value. ✔\ \n a: $foo / $bar; // 2em ✔\ \n // a: $foo + $bar; // Incompatible units: \'em\' and \'\'.\ \n // a: $foo - $bar; // Incompatible units: \'em\' and \'\'.\ \n\ \n\ \n $foo: 2px;\ \n $bar: 2em / 2px;\ \n\ \n foo: $foo; // 2px ✔\ \n // bar: $bar; // 1em/px isn\'t a valid CSS value. ✔\ \n a: $foo * $bar; // 2em ✔\ \n // a: $foo / $bar; // 2px*px/em isn\'t a valid CSS value. ✔\ \n // a: $foo + $bar; // Incompatible units: \'em\' and \'px\'.\ \n // a: $foo - $bar; // Incompatible units: \'em\' and \'px\'.\ \n}\ \n" ) .unwrap(), "a {\ \n foo: 2em;\ \n bar: 2em;\ \n a: 1;\ \n a: 4em;\ \n a: 0em;\ \n foo: 2px;\ \n bar: 2em;\ \n foo: 2em;\ \n bar: 2px;\ \n bar: 2px;\ \n bar: 2px;\ \n a: 2em;\ \n a: 1;\ \n a: 1;\ \n foo: 2px;\ \n a: 2em;\ \n foo: 2px;\ \n a: 2em;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_784.hrx" #[test] fn issue_784() { assert_eq!( rsass( ".foo {\ \n @each $item in (a: 1, b: 2, c: 3) {\ \n each: $item;\ \n }\ \n}\ \n" ) .unwrap(), ".foo {\ \n each: a 1;\ \n each: b 2;\ \n each: c 3;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_803.hrx" #[test] #[ignore] // wrong result fn issue_803() { assert_eq!( rsass( "\ \n$query-string: \"(min-width: 0) and (max-width: 599px), (min-width: 600px) and (max-width: 899px)\";\ \n@media #{$query-string} {\ \n .foo {\ \n content: bar;\ \n }\ \n}\ \n" ) .unwrap(), "@media (min-width: 0) and (max-width: 599px), (min-width: 600px) and (max-width: 899px) {\ \n .foo {\ \n content: bar;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_813.hrx" #[test] #[ignore] // wrong result fn issue_813() { assert_eq!( rsass( "@function foo($one, $two) {\ \n @return $one + $two;\ \n}\ \n\ \n$nums: 1px 2px;\ \n\ \n.foo {\ \n left: foo($nums...);\ \n bottom: $nums 3px;\ \n}\ \n" ) .unwrap(), ".foo {\ \n left: 3px;\ \n bottom: 1px 2px 3px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_815.hrx" #[test] fn issue_815() { assert_eq!( rsass( "foo {\ \n foo: str-slice(\"bar\", 1, 2);\ \n bar: str-slice(\"bar\", 3);\ \n}\ \n" ) .unwrap(), "foo {\ \n foo: \"ba\";\ \n bar: \"r\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_817.hrx" #[test] fn issue_817() { assert_eq!( rsass( "foo {\ \n foo: url(\'foo/bar.baz\');\ \n foo: url(\"foo/bar.baz\");\ \n foo: url(foo/bar.baz);\ \n foo: foo(\'foo/bar.baz\', \"bar\", 55);\ \n foo: foo(\"foo/bar.baz\", \'bar\', 55);\ \n foo: foo(\"foo/bar.baz\", bar, 55); }\ \n" ) .unwrap(), "foo {\ \n foo: url(\"foo/bar.baz\");\ \n foo: url(\"foo/bar.baz\");\ \n foo: url(foo/bar.baz);\ \n foo: foo(\"foo/bar.baz\", \"bar\", 55);\ \n foo: foo(\"foo/bar.baz\", \"bar\", 55);\ \n foo: foo(\"foo/bar.baz\", bar, 55);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_820" #[test] fn issue_820() { assert_eq!( rsass( "@charset \"UTF-8\";\ \n/*! Force output of above line by adding a unicode character. ♫ */\ \nhtml, body {\ \n height: 100%; }\ \n" ) .unwrap(), "@charset \"UTF-8\";\ \n/*! Force output of above line by adding a unicode character. ♫ */\ \nhtml, body {\ \n height: 100%;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_823.hrx" #[test] #[ignore] // wrong result fn issue_823() { assert_eq!( rsass( "%test {\ \n > {\ \n .red {\ \n color: #F00;\ \n }\ \n }\ \n}\ \n\ \np {\ \n @extend %test;\ \n\ \n > {\ \n a {\ \n @extend %test;\ \n }\ \n }\ \n}\ \n" ) .unwrap(), "p > a > .red, p > .red {\ \n color: #F00;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_828.hrx" #[test] #[ignore] // wrong result fn issue_828() { assert_eq!( rsass( "foo {\ \n box-shadow: inset -1.5em 0 1.5em -0.75em rgba(0, 0, 0, 0.25);\ \n box-shadow: inset -1.5em 0 1.5em - 0.75em rgba(0, 0, 0, 0.25);\ \n box-shadow: inset -1.5em 0 1.5em- 0.75em rgba(0, 0, 0, 0.25);\ \n box-shadow: inset -1.5em 0 1.5em-0.75em rgba(0, 0, 0, 0.25);\ \n box-shadow: inset -1.5em 0 1.5em -.75em rgba(0, 0, 0, .25);\ \n box-shadow: inset -1.5em 0 1.5em - .75em rgba(0, 0, 0, .25);\ \n box-shadow: inset -1.5em 0 1.5em- .75em rgba(0, 0, 0, .25);\ \n box-shadow: inset -1.5em 0 1.5em-.75em rgba(0, 0, 0, .25);\ \n}\ \n" ) .unwrap(), "foo {\ \n box-shadow: inset -1.5em 0 1.5em -0.75em rgba(0, 0, 0, 0.25);\ \n box-shadow: inset -1.5em 0 0.75em rgba(0, 0, 0, 0.25);\ \n box-shadow: inset -1.5em 0 1.5em- 0.75em rgba(0, 0, 0, 0.25);\ \n box-shadow: inset -1.5em 0 0.75em rgba(0, 0, 0, 0.25);\ \n box-shadow: inset -1.5em 0 1.5em -0.75em rgba(0, 0, 0, 0.25);\ \n box-shadow: inset -1.5em 0 0.75em rgba(0, 0, 0, 0.25);\ \n box-shadow: inset -1.5em 0 1.5em- 0.75em rgba(0, 0, 0, 0.25);\ \n box-shadow: inset -1.5em 0 0.75em rgba(0, 0, 0, 0.25);\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_829.hrx" #[test] #[ignore] // wrong result fn issue_829() { assert_eq!( rsass( ".foo {\ \n @media (foo: bar), (bar: baz) {\ \n foo: bar;\ \n\ \n @media (foo: bar) {\ \n bar: baz;\ \n }\ \n\ \n .bar {\ \n baz: bam;\ \n }\ \n }\ \n }\ \n\ \n" ) .unwrap(), "@media (foo: bar), (bar: baz) {\ \n .foo {\ \n foo: bar;\ \n }\ \n}\ \n@media (foo: bar) and (foo: bar), (bar: baz) and (foo: bar) {\ \n .foo {\ \n bar: baz;\ \n }\ \n}\ \n@media (foo: bar), (bar: baz) {\ \n .foo .bar {\ \n baz: bam;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_83.hrx" // Ignoring "issue_83", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_845.hrx" // From "sass-spec/spec/libsass-closed-issues/issue_857.hrx" #[test] fn issue_857() { assert_eq!( rsass( "$list: \"item-1\" \"item-2\" \"item-3\";\ \n\ \n#hello {\ \n @if length($list) % 2 == 0 {\ \n color: blue;\ \n }\ \n\ \n @else {\ \n color: red;\ \n }\ \n}" ) .unwrap(), "#hello {\ \n color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_859.hrx" #[test] fn issue_859() { assert_eq!( rsass( "@media screen {\ \n .two {\ \n @at-root .one {\ \n background: blue;\ \n .three {\ \n color: red;\ \n }\ \n }\ \n }\ \n}\ \n" ) .unwrap(), "@media screen {\ \n .one {\ \n background: blue;\ \n }\ \n .one .three {\ \n color: red;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_86.hrx" #[test] fn issue_86() { assert_eq!( rsass( ".color-functions {\r\ \n $color: red;\r\ \n hue: hue($color);\r\ \n hue-type: type-of(hue($color));\r\ \n hue-unit: unit(hue($color));\r\ \n hue-comparable: comparable(hue($color), hue($color));\r\ \n\ttest-1: comparable(lightness(red), 1%);\r\ \n\ttest-2: comparable(saturation(red), 1%);\r\ \n}" ) .unwrap(), ".color-functions {\ \n hue: 0deg;\ \n hue-type: number;\ \n hue-unit: \"deg\";\ \n hue-comparable: true;\ \n test-1: true;\ \n test-2: true;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_864.hrx" #[test] fn issue_864() { assert_eq!( rsass("div { color: desaturate(#999, 50%); }").unwrap(), "div {\ \n color: #999999;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_87.hrx" #[test] fn issue_87() { assert_eq!( rsass( "$bar: \"bar\";\r\ \n$foobar: \"foo#{$bar}\";\r\ \n#{$bar} {\r\ \n #{$bar}: #{$bar};\r\ \n #{$bar}: $bar;\r\ \n}\r\ \n#{$foobar} {\r\ \n #{$foobar}: #{$foobar};\r\ \n #{$foobar}: $foobar;\r\ \n}" ) .unwrap(), "bar {\ \n bar: bar;\ \n bar: \"bar\";\ \n}\ \nfoobar {\ \n foobar: foobar;\ \n foobar: \"foobar\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_870.hrx" #[test] fn issue_870() { assert_eq!( rsass( "$quoted-strings-csv: \"alpha\", \"beta\", \'gamma\', \'delta\';\ \n$quoted-strings-ssv: \"alpha\" \"beta\" \'gamma\' \'delta\';\ \n\ \n.csv {\ \n output: $quoted-strings-csv;\ \n output: #{$quoted-strings-csv};\ \n output: \"[#{$quoted-strings-csv}]\";\ \n output: \"#{$quoted-strings-csv}\";\ \n output: \"[\"#{$quoted-strings-csv}\"]\";\ \n output: \'#{$quoted-strings-csv}\';\ \n output: \"[\'#{$quoted-strings-csv}\']\";\ \n}\ \n\ \n.ssv {\ \n output: $quoted-strings-ssv;\ \n output: #{$quoted-strings-ssv};\ \n output: \"[#{$quoted-strings-ssv}]\";\ \n output: \"#{$quoted-strings-ssv}\";\ \n output: \"[\"#{$quoted-strings-ssv}\"]\";\ \n output: \'#{$quoted-strings-ssv}\';\ \n output: \"[\'#{$quoted-strings-ssv}\']\";\ \n}\ \n" ) .unwrap(), ".csv {\ \n output: \"alpha\", \"beta\", \"gamma\", \"delta\";\ \n output: alpha, beta, gamma, delta;\ \n output: \"[alpha, beta, gamma, delta]\";\ \n output: \"alpha, beta, gamma, delta\";\ \n output: \"[\" alpha, beta, gamma, delta \"]\";\ \n output: \"alpha, beta, gamma, delta\";\ \n output: \"[\'alpha, beta, gamma, delta\']\";\ \n}\ \n.ssv {\ \n output: \"alpha\" \"beta\" \"gamma\" \"delta\";\ \n output: alpha beta gamma delta;\ \n output: \"[alpha beta gamma delta]\";\ \n output: \"alpha beta gamma delta\";\ \n output: \"[\" alpha beta gamma delta \"]\";\ \n output: \"alpha beta gamma delta\";\ \n output: \"[\'alpha beta gamma delta\']\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_871.hrx" // Ignoring "issue_871", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_873.hrx" #[test] fn issue_873() { assert_eq!( rsass( "$quoted: \"notification\";\ \n$unquoted: notification;\ \n\ \n@function func($var) {\ \n @return $var;\ \n}\ \n\ \nfoo {\ \n foo: func(notification);\ \n foo: #{notification};\ \n foo: #{$quoted};\ \n foo: $quoted;\ \n foo: #{$unquoted};\ \n foo: $unquoted;\ \n}\ \n" ) .unwrap(), "foo {\ \n foo: notification;\ \n foo: notification;\ \n foo: notification;\ \n foo: \"notification\";\ \n foo: notification;\ \n foo: notification;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_877.hrx" #[test] fn issue_877() { assert_eq!( rsass( "@function _test1() {\ \n @return \'hello\';\ \n}\ \n\ \n@function -test2() {\ \n @return \'hello\';\ \n}\ \n\ \n@function test() {\ \n @return \'world\';\ \n}\ \n\ \n@mixin _test1() {\ \n mixin: true;\ \n}\ \n\ \n@mixin -test2() {\ \n mixin: true;\ \n}\ \n\ \n@mixin test() {\ \n mixin: true;\ \n}\ \n\ \n$-test1: true;\ \n$_test2: true;\ \n$test: true;\ \n\ \n.test {\ \n function: function-exists(\'_test1\');\ \n function: function-exists(\'-test1\');\ \n function: function-exists(\'_test2\');\ \n function: function-exists(\'-test2\');\ \n function: function-exists(\'test1\');\ \n function: function-exists(\'test2\');\ \n function: function-exists(\'test\');\ \n mixin: mixin-exists(\'_test1\');\ \n mixin: mixin-exists(\'-test1\');\ \n mixin: mixin-exists(\'_test2\');\ \n mixin: mixin-exists(\'-test2\');\ \n mixin: mixin-exists(\'test1\');\ \n mixin: mixin-exists(\'test2\');\ \n mixin: mixin-exists(\'test\');\ \n variable: variable-exists(\'_test1\');\ \n variable: variable-exists(\'-test1\');\ \n variable: variable-exists(\'_test2\');\ \n variable: variable-exists(\'-test2\');\ \n variable: variable-exists(\'test1\');\ \n variable: variable-exists(\'test2\');\ \n variable: variable-exists(\'test\');\ \n global-variable: global-variable-exists(\'_test1\');\ \n global-variable: global-variable-exists(\'-test1\');\ \n global-variable: global-variable-exists(\'_test2\');\ \n global-variable: global-variable-exists(\'-test2\');\ \n global-variable: global-variable-exists(\'test1\');\ \n global-variable: global-variable-exists(\'test2\');\ \n global-variable: global-variable-exists(\'test\');\ \n}\ \n" ) .unwrap(), ".test {\ \n function: true;\ \n function: true;\ \n function: true;\ \n function: true;\ \n function: false;\ \n function: false;\ \n function: true;\ \n mixin: true;\ \n mixin: true;\ \n mixin: true;\ \n mixin: true;\ \n mixin: false;\ \n mixin: false;\ \n mixin: true;\ \n variable: true;\ \n variable: true;\ \n variable: true;\ \n variable: true;\ \n variable: false;\ \n variable: false;\ \n variable: true;\ \n global-variable: true;\ \n global-variable: true;\ \n global-variable: true;\ \n global-variable: true;\ \n global-variable: false;\ \n global-variable: false;\ \n global-variable: true;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_883.hrx" #[test] fn issue_883() { assert_eq!( rsass( "div {\ \n @foo {\ \n font: a;\ \n }\ \n @bar {\ \n color: b;\ \n }\ \n}\ \n" ) .unwrap(), "@foo {\ \n div {\ \n font: a;\ \n }\ \n}\ \n@bar {\ \n div {\ \n color: b;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_884.hrx" #[test] fn issue_884() { assert_eq!( rsass( "@function foo() {\ \n @return 2;\ \n}\ \n\ \n$foo: false;\ \n@if foo() % 2 == 0 {\ \n $foo: true;\ \n}\ \n\ \na {\ \n foo: $foo;\ \n}\ \n" ) .unwrap(), "a {\ \n foo: true;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_890.hrx" #[test] fn issue_890() { assert_eq!( rsass( ".foo {\ \n border: {\ \n right: 10px solid /*here is a comment*/;\ \n }\ \n}\ \n" ) .unwrap(), ".foo {\ \n border-right: 10px solid;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_893.hrx" #[test] #[ignore] // wrong result fn issue_893() { assert_eq!( rsass( "$gutter: 20px;\ \n\ \n.row {\ \n margin: 0 -$gutter;\ \n}" ) .unwrap(), ".row {\ \n margin: -20px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_894.hrx" #[test] fn issue_894() { assert_eq!( rsass( "a {/**/}\ \nb {content: \'something so I have a non-empty expected output\'}" ) .unwrap(), "a {\ \n /**/\ \n}\ \nb {\ \n content: \"something so I have a non-empty expected output\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_91.hrx" #[test] fn issue_91() { assert_eq!( rsass( "@mixin simple-media-query($max-width, $min-width) {\r\ \n @media only screen and (max-width: $max-width) and (min-width: $min-width) {\r\ \n @content;\r\ \n }\r\ \n}\r\ \n\r\ \n@mixin test($value) {\r\ \n border-color: $value;\r\ \n}\r\ \n\r\ \nbody \r\ \n{\r\ \n @include test(\"#ccc\");\r\ \n @include simple-media-query(900px, 400px) {\r\ \n border-color: black;\r\ \n }\r\ \n}" ) .unwrap(), "body {\ \n border-color: \"#ccc\";\ \n}\ \n@media only screen and (max-width: 900px) and (min-width: 400px) {\ \n body {\ \n border-color: black;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_930.hrx" #[test] fn issue_930() { assert_eq!( rsass( ".foo {\ \n &.bar {\ \n color: #F00;\ \n }\ \n}\ \n\ \n$class: \'baz\';\ \n.foo {\ \n &.#{$class} {\ \n color: #F00;\ \n }\ \n}\ \n\ \n$n: 1;\ \n.foo {\ \n &:nth-child(#{$n}) {\ \n color: #F00;\ \n }\ \n}\ \n" ) .unwrap(), ".foo.bar {\ \n color: #F00;\ \n}\ \n.foo.baz {\ \n color: #F00;\ \n}\ \n.foo:nth-child(1) {\ \n color: #F00;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_931.hrx" #[test] #[ignore] // wrong result fn issue_931() { assert_eq!( rsass( "@mixin img-opacity($trans) {\ \n filter : alpha(opacity=($trans * 100));\ \n -ms-filter : \"progid:DXImageTransform.Microsoft.Alpha(Opacity=#{$trans * 100})\";\ \n -moz-opacity : $trans;\ \n -khtml-opacity : $trans;\ \n opacity : $trans;\ \n}\ \n\ \nimg {\ \n @include img-opacity(.5);\ \n}" ) .unwrap(), "img {\ \n filter: alpha(opacity=50);\ \n -ms-filter: \"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)\";\ \n -moz-opacity: 0.5;\ \n -khtml-opacity: 0.5;\ \n opacity: 0.5;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_941.hrx" #[test] #[ignore] // wrong result fn issue_941() { assert_eq!( rsass( ".one, /* 1 */\ \n.two /* 2 */ { /* 3 */\ \n\tcolor: #F00; /* 4 */\ \n}\ \n" ) .unwrap(), ".one,\ \n.two {\ \n /* 3 */\ \n color: #F00;\ \n /* 4 */\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_942.hrx" #[test] #[ignore] // wrong result fn issue_942() { assert_eq!( rsass( "$v: \".foo \\\ \n.bar\";\ \n\ \n#{$v} {\ \n\tcolor: #F00;\ \n}\ \n\ \ndiv {\ \n\tcontent: \"foo\\\ \nbar\";\ \n}" ) .unwrap(), ".foo .bar {\ \n color: #F00;\ \n}\ \ndiv {\ \n content: \"foobar\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_943.hrx" #[test] #[ignore] // wrong result fn issue_943() { assert_eq!( rsass( "%dog {\ \n @media (min-width: 10px) {\ \n &:hover {\ \n display: none;\ \n }\ \n }\ \n}\ \n\ \n.puppy {\ \n @extend %dog;\ \n background-color: red;\ \n}" ) .unwrap(), "@media (min-width: 10px) {\ \n .puppy:hover {\ \n display: none;\ \n }\ \n}\ \n.puppy {\ \n background-color: red;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_945.hrx" // Ignoring "issue_945", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_947.hrx" #[test] fn issue_947() { assert_eq!( rsass( "@keyframes test {\ \n $var: 10%;\ \n #{$var} {\ \n color: red;\ \n }\ \n}\ \n" ) .unwrap(), "@keyframes test {\ \n 10% {\ \n color: red;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_948.hrx" #[test] fn issue_948() { assert_eq!( rsass("foo { bar: 10 * 5#{px}; }").unwrap(), "foo {\ \n bar: 50 px;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_950.hrx" #[test] #[ignore] // wrong result fn issue_950() { assert_eq!( rsass( ".selector1{ foo: bar; }\ \n.selector2{ zapf: dings; }\ \n\ \n.selector3{ @extend .selector1, .selector2; }" ) .unwrap(), ".selector1, .selector3 {\ \n foo: bar;\ \n}\ \n.selector2, .selector3 {\ \n zapf: dings;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_976.hrx" #[test] fn issue_976() { assert_eq!( rsass( ".debug {\ \n @debug-this {\ \n foo: bar;\ \n }\ \n}" ) .unwrap(), "@debug-this {\ \n .debug {\ \n foo: bar;\ \n }\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_978.hrx" #[test] fn issue_978() { assert_eq!( rsass( ".foo {\ \n [baz=\"#{&}\"] {\ \n foo: bar;\ \n }\ \n}" ) .unwrap(), ".foo [baz=\".foo\"] {\ \n foo: bar;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_980.hrx" #[test] fn issue_980() { assert_eq!( rsass( "@function foo($value, $default: 13, $args...) {\ \n $res: $value + $default;\ \n @if length($args) != 0 {\ \n $res: $res + nth($args, 1);\ \n }\ \n @return $res;\ \n}\ \n\ \n.test {\ \n value: foo(3); // expected: 16\ \n value: foo(3, 4); // expected: 7\ \n value: foo(3, 4, 5, 6); // expected: 12\ \n}\ \n" ) .unwrap(), ".test {\ \n value: 16;\ \n value: 7;\ \n value: 12;\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_988.hrx" #[test] fn issue_988() { assert_eq!( rsass( "@function str-replace($string, $search, $replace: \'\') {\ \n $index: str-index($string, $search);\ \n @if $index {\ \n @return str-slice($string, 1, $index - 1) + $replace +\ \n str-replace(str-slice($string, $index + str-length($search)), $search, $replace);\ \n }\ \n @return $string;\ \n}\ \n\ \n$string: \'Foo Bar Baz Qux\';\ \n.foo {\ \n content: str-replace($string, \' \', \'-\');\ \n}" ) .unwrap(), ".foo {\ \n content: \"Foo-Bar-Baz-Qux\";\ \n}\ \n" ); } // From "sass-spec/spec/libsass-closed-issues/issue_992.hrx" #[test] fn issue_992() { assert_eq!( rsass( "$color: \'red\';\ \n\ \n.-text-#{$color}- {\ \n color: $color;\ \n}" ) .unwrap(), ".-text-red- {\ \n color: \"red\";\ \n}\ \n" ); }
use std::mem; use linalg::{Layout, Mat, Matrix, Scalar, Square, Vect, Vector}; use typehack::data::*; use typehack::dim::*; pub trait GaussianNullspaceExt<X>: Matrix where X: Vector<Scalar = Self::Scalar, Dims = Self::Cols> { fn ge_null_elem(self) -> X; } #[cfg_attr(rustfmt, rustfmt_skip)] impl<T: Clone + Scalar, M: Size<T> + DimMul<N, Result = P>, N: Size<T>, P: Size<T>, L: Layout> GaussianNullspaceExt<Vect<T, N>> for Mat<T, M, N, L> { fn ge_null_elem(mut self) -> Vect<T, N> { debug!("Calculating arbitrary nullspace element of matrix {:?}...", self); let rows = self.rows().reify(); let cols = self.cols().reify(); debug!("Rows, columns: {}, {}", rows, cols); for i in 0..rows { let mut max = (i, self[[i, i]].abs()); for j in i+1..rows { let abs = self[[j, i]].abs(); if abs > max.1 { max = (j, abs); } } self.row_switch_mut(i, max.0); debug!("Partial pivoting row {} and {}. Matrix: {:?}", i, max.0, self); let mut col = 0; while col < cols && self[[i, col]].eq_zero() { col += 1; } if col >= cols { break; } { let k = mem::replace(&mut self[[i, col]], T::one()); for j in col+1..cols { self[[i, j]] /= k.clone(); } } for j in 0..i { debug!("Canceling row {}'s column {}", j, col); let k = -self[[j, col]].clone(); self.row_add_mut(j, i, &k); debug!("After row cancellation: {:?}", self); } for j in i+1..rows { debug!("Canceling row {}'s column {}", j, i); let k = mem::replace(&mut self[[j, col]], T::zero()); for c in col+1..cols { self[[j, c]] -= k.clone() * self[[i, c]].clone(); } debug!("After row cancellation: {:?}", self); } } // Our matrix should now be in reduced row-echelon form. We now proceed to find the free // variables. // We can proceed by attempting to find the first non-pivot column. If we find none, the // nullspace is the zero vector. debug!("Searching for free variables..."); for i in 0..cols { debug!("Checking column {}...", i); // This direct zero-comparison makes me really nervous. Numerical instability could // seriously kill this. TODO: Find a reasonable epsilon to compare with instead. if (i < rows && self[[i, i]].eq_zero()) || i >= rows { let mut x = Vect::from_elem(self.cols(), &T::zero()); for j in 0..rows { if self[[j, i]].eq_zero() { debug!("First free variable is found, in row {}.", j); x[i] = T::one(); return x; } x[j] = -self[[j, i]].clone(); } debug!("Nullspace element found, with only one free variable."); x[rows] = T::one(); return x; } } unreachable!(); } } pub trait GaussianEliminationExt<V, W>: Square where V: Vector<Scalar = Self::Scalar, Dims = Self::Side>, W: Vector<Scalar = Self::Scalar, Dims = Self::Side> { fn ge_solve(self, V) -> W; } #[cfg_attr(rustfmt, rustfmt_skip)] impl<T: Clone + Scalar, N: Size<T>, M: Size<T>, L: Layout> GaussianEliminationExt<Vect<T, N>, Vect<T, N>> for Mat<T, N, N, L> where N: DimMul<N, Result = M> { fn ge_solve(mut self, mut b: Vect<T, N>) -> Vect<T, N> { let n = self.side().reify(); for i in 0..n { // For every row n, we first find the row i >= n with the maximum absolute value in // column n; then, swap row i with row n. This is called partial pivoting, and it // can vastly increase the numerical stability of the result. let mut max = (i, self[[i, i]].abs()); for j in i+1..n { let abs = self[[j, i]].abs(); if abs > max.1 { max = (j, abs); } } self.row_switch_mut(i, max.0); b.as_mut_slice().swap(i, max.0); // For each row n in the matrix, we perform a row multiply-then-add operation to zero // out the values in column n of every row below row n. // TODO: Optimize: no need to perform the operation when the element in question should // be going to zero (also more numerically accurate.) for j in i+1..n { let k = -(self[[j, i]].clone() / self[[i, i]].clone()); self.row_add_mut(j, i, &k); b[j] += b[i].clone() * k; } } // And now, we use back-substitution to finish the solving process. // TODO: Consume these rows rather than clone their elements; this is the last time we use // the elements of the matrix, and we do not touch any element any more than once. for i in (0..n).rev() { for j in i+1..n { b[i] -= self[[i, j]].clone() * b[j].clone(); } b[i] /= self[[i, i]].clone(); } b } } #[cfg(test)] mod tests { extern crate env_logger; use super::*; use linalg::{Column, Vect, VectorNorm}; #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn ge_nullspace_1x2() { let _ = env_logger::init(); let a = Mat![[1., 0.]]; let c = a.clone().ge_null_elem(); debug!("c: {:?}", c); debug!("a * c: {:?}", Vect::from(a.clone() * c.clone().as_column::<Column>())); assert!(Vect::from(a * c.as_column::<Column>()).norm() < 0.000001); } #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn ge_nullspace_3x4() { let _ = env_logger::init(); let a = Mat![[ 3., 7./2., 9., 6.], [ 6., 2., 2., 5.], [12., 4., 4., 10.]]; let c = a.clone().ge_null_elem(); debug!("c: {:?}", c); debug!("a * c: {:?}", Vect::from(a.clone() * c.clone().as_column::<Column>())); assert!(Vect::from(a * c.as_column::<Column>()).norm() < 0.000001); } #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn ge_nullspace_4x5() { let _ = env_logger::init(); let a = Mat![[ 9., 1., 8., 7./3., 5./2.], [ 3., 5., 1., 8., 9.], [ 5./2., 9., 7., 2., 2.], [ 3./2., 1., 8., 2., 2.]]; let c = a.clone().ge_null_elem(); debug!("c: {:?}", c); debug!("a * c: {:?}", Vect::from(a.clone() * c.clone().as_column::<Column>())); assert!(Vect::from(a * c.as_column::<Column>()).norm() < 0.000001); } #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn ge_solve_3x3_row_major() { let a = Mat![#row [ 2., 1., -1.], [-3., -1., 2.], [-2., 1., 2.]]; let b = Vect![8., -11., -3.]; let c = a.ge_solve(b); assert!((c - Vect![2., 3., -1.]).norm() < 0.000001); } #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn ge_solve_3x3_column_major() { let a = Mat![#column [ 2., 1., -1.], [-3., -1., 2.], [-2., 1., 2.]]; let b = Vect![8., -11., -3.]; let c = a.ge_solve(b); assert!((c - Vect![2., 3., -1.]).norm() < 0.000001); } }
#![no_std] use zoon::*; blocks!{ #[s_var] fn watching_enabled() -> bool { false } #[update] fn toggle_watching() { watching_enabled().update(not); } // -- mouse -- #[s_var] fn mouse_position() -> Point { Point::new(0, 0) } #[update] fn update_mouse_position(event: OnMouseMove) { mouse_position().set(event.position); } // -- keyboard -- #[s_var] fn last_key() -> String { String::new() } #[update] fn update_last_key(event: OnKeyDown) { last_key().set(event.key.to_string()); } // -- el -- #[el] fn root() -> View { let enabled = watching_enabled().inner(); view![ enabled.then(|| vec![ on_mouse_move(update_mouse_position), on_key_down(update_last_key), ]), control_panel(), ] } #[el] fn control_panel() -> Column { let position = mouse_position().inner(); let key = last_key(); let enabled = watching_enabled().inner(); column![ format!("X: {}, Y: {}", position.x, position.y), key.map(|key| format!("Key: {}", key)), button![ button::on_press(toggle_watching), format!("{} watching", if enabled { "Stop" } else { "Start"}), ], ] } } #[wasm_bindgen(start)] pub fn start() { start!() }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. mod authenticator; mod supplicant; use self::authenticator::Authenticator; use self::supplicant::Supplicant; use Error; use akm::Akm; use bytes::BytesMut; use cipher::{Cipher, GROUP_CIPHER_SUITE, TKIP}; use eapol; use failure; use key::exchange::Key; use key::gtk::Gtk; use key::ptk::Ptk; use rsna::{Role, SecAssocResult, SecAssocStatus, SecAssocUpdate}; use rsne::Rsne; use std::rc::Rc; enum RoleHandler { Authenticator(Authenticator), Supplicant(Supplicant), } #[derive(Debug)] pub enum MessageNumber { Message1 = 1, Message2 = 2, Message3 = 3, Message4 = 4, } #[derive(Debug)] pub struct Config { pub role: Role, pub s_addr: [u8; 6], pub s_rsne: Rsne, pub a_addr: [u8; 6], pub a_rsne: Rsne, } impl Config { pub fn new( role: Role, s_addr: [u8; 6], s_rsne: Rsne, a_addr: [u8; 6], a_rsne: Rsne, ) -> Result<Config, failure::Error> { // TODO(hahnr): Validate configuration for: // (1) Correct RSNE subset // (2) Correct AKM and Cipher Suite configuration Ok(Config { role, s_addr, s_rsne, a_addr, a_rsne, }) } } pub struct Fourway { cfg: Rc<Config>, handler: RoleHandler, ptk: Option<Ptk>, gtk: Option<Gtk>, } impl Fourway { pub fn new(cfg: Config, pmk: Vec<u8>) -> Result<Fourway, failure::Error> { let shared_cfg = Rc::new(cfg); let handler = match &shared_cfg.role { &Role::Supplicant => RoleHandler::Supplicant(Supplicant::new(shared_cfg.clone(), pmk)?), &Role::Authenticator => RoleHandler::Authenticator(Authenticator::new()?), }; Ok(Fourway { cfg: shared_cfg, handler: handler, ptk: None, gtk: None, }) } fn on_key_confirmed(&mut self, key: Key) { match key { Key::Ptk(ptk) => self.ptk = Some(ptk), Key::Gtk(gtk) => self.gtk = Some(gtk), _ => (), } } pub fn on_eapol_key_frame(&mut self, frame: &eapol::KeyFrame) -> SecAssocResult { // (1) Validate frame. let () = self.validate_eapol_key_frame(frame)?; // (2) Decrypt key data. let mut plaintext = None; if frame.key_info.encrypted_key_data() { let rsne = &self.cfg.s_rsne; let akm = &rsne.akm_suites[0]; let unwrap_result = match self.ptk.as_ref() { // Return error if key data is encrypted but the PTK was not yet derived. None => Err(Error::UnexpectedEncryptedKeyData.into()), // Else attempt to decrypt key data. Some(ptk) => akm.keywrap_algorithm() .ok_or(Error::UnsupportedAkmSuite)? .unwrap(ptk.kek(), &frame.key_data[..]) .map(|p| Some(p)), }; plaintext = match unwrap_result { Ok(plaintext) => plaintext, Err(Error::WrongAesKeywrapKey) => { return Ok(vec![SecAssocUpdate::Status(SecAssocStatus::WrongPassword)]) }, Err(e) => return Err(e.into()) } } let key_data = match plaintext.as_ref() { Some(data) => &data[..], // Key data was never encrypted. None => &frame.key_data[..], }; // (3) Process frame by handler. let result = match &mut self.handler { &mut RoleHandler::Authenticator(ref a) => a.on_eapol_key_frame(frame, key_data), &mut RoleHandler::Supplicant(ref mut s) => s.on_eapol_key_frame(frame, key_data), }?; // (4) Process results from handler. self.process_updates(result) } fn validate_eapol_key_frame(&self, frame: &eapol::KeyFrame) -> Result<(), failure::Error> { // IEEE Std 802.1X-2010, 11.9 let key_descriptor = match eapol::KeyDescriptor::from_u8(frame.descriptor_type) { Some(eapol::KeyDescriptor::Ieee802dot11) => Ok(eapol::KeyDescriptor::Ieee802dot11), // Use of RC4 is deprecated. Some(_) => Err(Error::InvalidKeyDescriptor( frame.descriptor_type, eapol::KeyDescriptor::Ieee802dot11, )), // Invalid value. None => Err(Error::UnsupportedKeyDescriptor(frame.descriptor_type)), }.map_err(|e| failure::Error::from(e))?; // IEEE Std 802.11-2016, 12.7.2 b.1) let rsne = &self.cfg.s_rsne; let expected_version = derive_key_descriptor_version(rsne, key_descriptor); if frame.key_info.key_descriptor_version() != expected_version { return Err(Error::UnsupportedKeyDescriptorVersion( frame.key_info.key_descriptor_version(), ).into()); } // IEEE Std 802.11-2016, 12.7.2 b.2) // Only PTK derivation is supported as of now. if frame.key_info.key_type() != eapol::KEY_TYPE_PAIRWISE { return Err(Error::UnsupportedKeyDerivation.into()); } // Drop messages which were not expected by the configured role. let msg_no = message_number(frame); match self.cfg.role { // Authenticator should only receive message 2 and 4. Role::Authenticator => match msg_no { MessageNumber::Message2 | MessageNumber::Message4 => Ok(()), _ => Err(Error::Unexpected4WayHandshakeMessage(msg_no)), }, Role::Supplicant => match msg_no { MessageNumber::Message1 | MessageNumber::Message3 => Ok(()), _ => Err(Error::Unexpected4WayHandshakeMessage(msg_no)), }, }.map_err(|e| failure::Error::from(e))?; // Explicit validation based on the frame's message number. let msg_no = message_number(frame); match msg_no { MessageNumber::Message1 => validate_message_1(frame), MessageNumber::Message2 => validate_message_2(frame), MessageNumber::Message3 => validate_message_3(frame), MessageNumber::Message4 => validate_message_4(frame), }?; // IEEE Std 802.11-2016, 12.7.2 c) match msg_no { MessageNumber::Message1 | MessageNumber::Message3 => { let rsne = &self.cfg.s_rsne; let pairwise = &rsne.pairwise_cipher_suites[0]; let tk_bits = pairwise .tk_bits() .ok_or(Error::UnsupportedCipherSuite) .map_err(|e| failure::Error::from(e))?; if frame.key_len != tk_bits / 8 { Err(Error::InvalidPairwiseKeyLength(frame.key_len, tk_bits / 8)) } else { Ok(()) } } _ => Ok(()), }.map_err(|e| failure::Error::from(e))?; // IEEE Std 802.11-2016, 12.7.2, d) let min_key_replay_counter = match &self.handler { &RoleHandler::Authenticator(ref a) => a.key_replay_counter, &RoleHandler::Supplicant(ref s) => s.key_replay_counter(), }; if frame.key_replay_counter <= min_key_replay_counter { return Err(Error::InvalidKeyReplayCounter.into()); } // IEEE Std 802.11-2016, 12.7.2, e) // Nonce is validated based on the frame's message number. // Must not be zero in 1st, 2nd and 3rd message. // Nonce in 3rd message must be same as the one from the 1st message. if let MessageNumber::Message3 = msg_no { let nonce_match = match &self.handler { &RoleHandler::Supplicant(ref s) => &frame.key_nonce[..] == s.anonce(), _ => false, }; if !nonce_match { return Err(Error::ErrorNonceDoesntMatch.into()); } } // IEEE Std 802.11-2016, 12.7.2, g) // Key RSC validated based on the frame's message number. // Optional in the 3rd message. Must be zero in others. // IEEE Std 802.11-2016, 12.7.2 h) let rsne = &self.cfg.s_rsne; let akm = &rsne.akm_suites[0]; let mic_bytes = akm.mic_bytes() .ok_or(Error::UnsupportedAkmSuite) .map_err(|e| failure::Error::from(e))?; if frame.key_mic.len() != mic_bytes as usize { return Err(Error::InvalidMicSize.into()); } // If a MIC is set but the PTK was not yet derived, the MIC cannot be verified. if frame.key_info.key_mic() { match self.ptk.as_ref() { None => Err(Error::UnexpectedMic.into()), Some(ptk) => { let mut buf = Vec::with_capacity(frame.len()); frame.as_bytes(true, &mut buf); let written = buf.len(); let valid_mic = akm.integrity_algorithm() .ok_or(Error::UnsupportedAkmSuite)? .verify(ptk.kck(), &buf[..], &frame.key_mic[..]); if !valid_mic { Err(Error::InvalidMic) } else { Ok(()) } } }.map_err(|e: Error| failure::Error::from(e))?; } // IEEE Std 802.11-2016, 12.7.2 i) & j) if frame.key_data_len as usize != frame.key_data.len() { return Err(Error::InvalidKeyDataLength.into()); } Ok(()) } fn process_updates(&mut self, mut updates: Vec<SecAssocUpdate>) -> SecAssocResult { // Filter key updates and process ourselves to prevent reporting keys before the Handshake // completed successfully. Report all other updates. updates .drain_filter(|update| match update { SecAssocUpdate::Key(_) => true, _ => false, }) .for_each(|update| { if let SecAssocUpdate::Key(key) = update { self.on_key_confirmed(key); } }); // If both PTK and GTK are known the Handshake completed successfully and keys can be // reported. if let (Some(ptk), Some(gtk)) = (self.ptk.as_ref(), self.gtk.as_ref()) { updates.push(SecAssocUpdate::Key(Key::Ptk(ptk.clone()))); updates.push(SecAssocUpdate::Key(Key::Gtk(gtk.clone()))); } Ok(updates) } } // Verbose and explicit validation of Message 1 to 4. fn validate_message_1(frame: &eapol::KeyFrame) -> Result<(), failure::Error> { // IEEE Std 802.11-2016, 12.7.2 b.4) if frame.key_info.install() { Err(Error::InvalidInstallBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.5) } else if !frame.key_info.key_ack() { Err(Error::InvalidKeyAckBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.6) } else if frame.key_info.key_mic() { Err(Error::InvalidKeyAckBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.7) } else if frame.key_info.secure() { Err(Error::InvalidSecureBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.8) } else if frame.key_info.error() { Err(Error::InvalidErrorBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.9) } else if frame.key_info.request() { Err(Error::InvalidRequestBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.10) } else if frame.key_info.encrypted_key_data() { Err(Error::InvalidEncryptedKeyDataBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 e) } else if is_zero(&frame.key_nonce[..]) { Err(Error::InvalidNonce.into()) // IEEE Std 802.11-2016, 12.7.6.2 } else if !is_zero(&frame.key_iv[..]) { Err(Error::InvalidIv.into()) // IEEE Std 802.11-2016, 12.7.2 g) } else if frame.key_rsc != 0 { Err(Error::InvalidRsc.into()) } else { Ok(()) } // The first message of the Handshake is also required to carry a zeroed MIC. // Some routers however send messages without zeroing out the MIC beforehand. // To ensure compatibility with such routers, the MIC of the first message is // allowed to be set. // This assumption faces no security risk because the message's MIC is only // validated in the Handshake and not in the Supplicant or Authenticator // implementation. } fn validate_message_2(frame: &eapol::KeyFrame) -> Result<(), failure::Error> { // IEEE Std 802.11-2016, 12.7.2 b.4) if frame.key_info.install() { Err(Error::InvalidInstallBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.5) } else if frame.key_info.key_ack() { Err(Error::InvalidKeyAckBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.6) } else if !frame.key_info.key_mic() { Err(Error::InvalidKeyAckBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.7) } else if frame.key_info.secure() { Err(Error::InvalidSecureBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.8) // Error bit only set by Supplicant in MIC failures in SMK derivation. // SMK derivation not yet supported. } else if frame.key_info.error() { Err(Error::InvalidErrorBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.9) } else if frame.key_info.request() { Err(Error::InvalidRequestBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.10) } else if frame.key_info.encrypted_key_data() { Err(Error::InvalidEncryptedKeyDataBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 e) } else if is_zero(&frame.key_nonce[..]) { Err(Error::InvalidNonce.into()) // IEEE Std 802.11-2016, 12.7.6.3 } else if !is_zero(&frame.key_iv[..]) { Err(Error::InvalidIv.into()) // IEEE Std 802.11-2016, 12.7.2 g) } else if frame.key_rsc != 0 { Err(Error::InvalidRsc.into()) } else { Ok(()) } } fn validate_message_3(frame: &eapol::KeyFrame) -> Result<(), failure::Error> { // IEEE Std 802.11-2016, 12.7.2 b.4) // Install = 0 is only used in key mapping with TKIP and WEP, neither is supported by Fuchsia. if !frame.key_info.install() { Err(Error::InvalidInstallBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.5) } else if !frame.key_info.key_ack() { Err(Error::InvalidKeyAckBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.6) } else if !frame.key_info.key_mic() { Err(Error::InvalidKeyAckBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.7) } else if !frame.key_info.secure() { Err(Error::InvalidSecureBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.8) } else if frame.key_info.error() { Err(Error::InvalidErrorBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.9) } else if frame.key_info.request() { Err(Error::InvalidRequestBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.10) } else if !frame.key_info.encrypted_key_data() { Err(Error::InvalidEncryptedKeyDataBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 e) } else if is_zero(&frame.key_nonce[..]) { Err(Error::InvalidNonce.into()) // IEEE Std 802.11-2016, 12.7.6.4 } else if frame.version >= eapol::ProtocolVersion::Ieee802dot1x2004 as u8 && !is_zero(&frame.key_iv[..]) { Err(Error::InvalidIv.into()) // IEEE Std 802.11-2016, 12.7.2 i) & j) // Key Data must not be empty. } else if frame.key_data_len == 0 { Err(Error::EmptyKeyData.into()) } else { Ok(()) } } fn validate_message_4(frame: &eapol::KeyFrame) -> Result<(), failure::Error> { // IEEE Std 802.11-2016, 12.7.2 b.4) if frame.key_info.install() { Err(Error::InvalidInstallBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.5) } else if frame.key_info.key_ack() { Err(Error::InvalidKeyAckBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.6) } else if !frame.key_info.key_mic() { Err(Error::InvalidKeyAckBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.7) } else if !frame.key_info.secure() { Err(Error::InvalidSecureBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.8) // Error bit only set by Supplicant in MIC failures in SMK derivation. // SMK derivation not yet supported. } else if frame.key_info.error() { Err(Error::InvalidErrorBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.9) } else if frame.key_info.request() { Err(Error::InvalidRequestBitValue.into()) // IEEE Std 802.11-2016, 12.7.2 b.10) } else if frame.key_info.encrypted_key_data() { Err(Error::InvalidEncryptedKeyDataBitValue.into()) // IEEE Std 802.11-2016, 12.7.6.5 } else if !is_zero(&frame.key_iv[..]) { Err(Error::InvalidIv.into()) // IEEE Std 802.11-2016, 12.7.2 g) } else if frame.key_rsc != 0 { Err(Error::InvalidRsc.into()) } else { Ok(()) } } fn message_number(rx_frame: &eapol::KeyFrame) -> MessageNumber { // IEEE does not specify how to determine a frame's message number in the 4-Way Handshake // sequence. However, it's important to know a frame's message number to do further // validations. To derive the message number the key info field is used. // 4-Way Handshake specific EAPOL Key frame requirements: // IEEE Std 802.11-2016, 12.7.6.1 // IEEE Std 802.11-2016, 12.7.6.2 & 12.7.6.4 // Authenticator requires acknowledgement of all its sent frames. if rx_frame.key_info.key_ack() { // Authenticator only sends 1st and 3rd message of the handshake. // IEEE Std 802.11-2016, 12.7.2 b.4) // The third requires key installation while the first one doesn't. if rx_frame.key_info.install() { MessageNumber::Message3 } else { MessageNumber::Message1 } } else { // Supplicant only sends 2nd and 4th message of the handshake. // IEEE Std 802.11-2016, 12.7.2 b.7) // The fourth message is secured while the second one is not. if rx_frame.key_info.secure() { MessageNumber::Message4 } else { MessageNumber::Message2 } } } // IEEE Std 802.11-2016, 12.7.2 b.1) // Key Descriptor Version is based on the negotiated AKM, Pairwise- and Group Cipher suite. fn derive_key_descriptor_version(rsne: &Rsne, key_descriptor_type: eapol::KeyDescriptor) -> u16 { let akm = &rsne.akm_suites[0]; let pairwise = &rsne.pairwise_cipher_suites[0]; if !akm.has_known_algorithm() || !pairwise.has_known_usage() { return 0; } match akm.suite_type { 1 | 2 => match key_descriptor_type { eapol::KeyDescriptor::Rc4 => match pairwise.suite_type { TKIP | GROUP_CIPHER_SUITE => 1, _ => 0, }, eapol::KeyDescriptor::Ieee802dot11 => { if pairwise.is_enhanced() { 2 } else { match rsne.group_data_cipher_suite.as_ref() { Some(group) if group.is_enhanced() => 2, _ => 0, } } } _ => 0, }, // Interestingly, IEEE 802.11 does not specify any pairwise- or group cipher // requirements for these AKMs. 3...6 => 3, _ => 0, } } fn is_zero(slice: &[u8]) -> bool { slice.iter().all(|&x| x == 0) } #[cfg(test)] mod tests { use super::*; use rsna::test_util::{self, MessageOverride}; use bytes::Bytes; fn make_handshake() -> Fourway { // Create a new instance of the 4-Way Handshake in Supplicant role. let pmk = test_util::get_pmk(); let cfg = Config{ s_rsne: test_util::get_s_rsne(), a_rsne: test_util::get_a_rsne(), s_addr: test_util::S_ADDR, a_addr: test_util::A_ADDR, role: Role::Supplicant }; Fourway::new(cfg, pmk).expect("error while creating 4-Way Handshake") } fn compute_ptk(a_nonce: &[u8], supplicant_result: SecAssocResult) -> Option<Ptk> { match supplicant_result.expect("expected successful processing of first message") .get(0) .expect("expected at least one response from Supplicant") { SecAssocUpdate::TxEapolKeyFrame(msg2) => { let snonce = msg2.key_nonce; let derived_ptk = test_util::get_ptk(a_nonce, &snonce[..]); Some(derived_ptk) } _ => None, } } #[test] fn test_nonzero_mic_in_first_msg() { let mut handshake = make_handshake(); // Send first message of Handshake to Supplicant and verify result. let a_nonce = test_util::get_nonce(); let mut msg1 = test_util::get_4whs_msg1(&a_nonce[..], 1); msg1.key_mic = Bytes::from(vec![0xAA; 16]); let result = handshake.on_eapol_key_frame(&msg1); assert!(result.is_ok(), "error, expected success for processing first msg but result is: {:?}", result); } // First messages of 4-Way Handshake must carry a zeroed IV in all protocol versions. #[test] fn test_random_iv_msg1_v1() { let mut handshake = make_handshake(); // Send first message of Handshake to Supplicant and verify result. let a_nonce = test_util::get_nonce(); let mut msg1 = test_util::get_4whs_msg1(&a_nonce[..], 1); msg1.version = 1; msg1.key_iv[0] = 0xFF; let result = handshake.on_eapol_key_frame(&msg1); assert!(result.is_err(), "error, expected failure for first msg but result is: {:?}", result); } #[test] fn test_random_iv_msg1_v2() { let mut handshake = make_handshake(); // Send first message of Handshake to Supplicant and verify result. let a_nonce = test_util::get_nonce(); let mut msg1 = test_util::get_4whs_msg1(&a_nonce[..], 1); msg1.version = 2; msg1.key_iv[0] = 0xFF; let result = handshake.on_eapol_key_frame(&msg1); assert!(result.is_err(), "error, expected failure for first msg but result is: {:?}", result); } // EAPOL Key frames can carry a random IV in the third message of the 4-Way Handshake if // protocol version 1, 802.1X-2001, is used. All other protocol versions require a zeroed IV // for the third message of the handshake. #[test] fn test_random_iv_msg3_v1() { let mut handshake = make_handshake(); // Send first message of Handshake to Supplicant and derive PTK. let a_nonce = test_util::get_nonce(); let msg1 = test_util::get_4whs_msg1(&a_nonce[..], 1); let result = handshake.on_eapol_key_frame(&msg1); let ptk = compute_ptk(&a_nonce[..], result).expect("could not derive PTK"); // Send third message of 4-Way Handshake to Supplicant. let gtk = vec![42u8; 16]; let mut msg3 = test_util::get_4whs_msg3(&ptk, &a_nonce[..], &gtk[..], Some(MessageOverride{ version: 1, replay_counter: 2, iv: [0xFFu8; 16], })); let result = handshake.on_eapol_key_frame(&msg3); assert!(result.is_ok(), "error, expected success for processing third msg but result is: {:?}", result); } #[test] fn test_random_iv_msg3_v2() { let mut handshake = make_handshake(); // Send first message of Handshake to Supplicant and derive PTK. let a_nonce = test_util::get_nonce(); let msg1 = test_util::get_4whs_msg1(&a_nonce[..], 1); let result = handshake.on_eapol_key_frame(&msg1); let ptk = compute_ptk(&a_nonce[..], result).expect("could not derive PTK"); // Send third message of 4-Way Handshake to Supplicant. let gtk = vec![42u8; 16]; let mut msg3 = test_util::get_4whs_msg3(&ptk, &a_nonce[..], &gtk[..], Some(MessageOverride{ version: 2, replay_counter: 2, iv: [0xFFu8; 16], })); let result = handshake.on_eapol_key_frame(&msg3); assert!(result.is_err(), "error, expected failure for third msg but result is: {:?}", result); } #[test] fn test_zeroed_iv_msg3_v2() { let mut handshake = make_handshake(); // Send first message of Handshake to Supplicant and derive PTK. let a_nonce = test_util::get_nonce(); let msg1 = test_util::get_4whs_msg1(&a_nonce[..], 1); let result = handshake.on_eapol_key_frame(&msg1); let ptk = compute_ptk(&a_nonce[..], result).expect("could not derive PTK"); // Send third message of 4-Way Handshake to Supplicant. let gtk = vec![42u8; 16]; let mut msg3 = test_util::get_4whs_msg3(&ptk, &a_nonce[..], &gtk[..], Some(MessageOverride{ version: 2, replay_counter: 2, iv: [0u8; 16], })); let result = handshake.on_eapol_key_frame(&msg3); assert!(result.is_ok(), "error, expected success for processing third msg but result is: {:?}", result); } // TODO(hahnr): Add additional tests. }
use super::*; pub(crate) fn buffer_command(ctx: &Context) -> CommandResult { assume_args(&ctx, "try: /buffer N")?; // TODO get rid of this string let buf = ctx.parts[0] .parse::<usize>() .map_err(|_e| Error::InvalidArgument("try: /buffer N (a number this time)".into()))?; ctx.request(Request::SwitchBuffer(buf)); Ok(Response::Nothing) }
extern crate bytes; extern crate hex; extern crate rsocket_rust; use bytes::{Bytes, BytesMut}; use rsocket_rust::frame::*; use rsocket_rust::utils::Writeable; #[test] fn test_setup() { let f = Setup::builder(1234, 0) .set_mime_data("application/binary") .set_mime_metadata("text/plain") .set_token(Bytes::from("this_is_a_token")) .set_data(Bytes::from(String::from("Hello World!"))) .set_metadata(Bytes::from(String::from("foobar"))) .build(); try_codec(f); } #[test] fn test_keepalive() { let f = Keepalive::builder(1234, Frame::FLAG_RESPOND) .set_last_received_position(123) .set_data(Bytes::from("foobar")) .build(); try_codec(f); } #[test] fn test_request_response() { let f = RequestResponse::builder(1234, 0) .set_data(Bytes::from("Hello World")) .set_metadata(Bytes::from("Foobar")) .build(); try_codec(f); } #[test] fn test_payload() { let f = Payload::builder(1234, Frame::FLAG_NEXT | Frame::FLAG_COMPLETE) .set_data(Bytes::from("Hello World!")) .set_metadata(Bytes::from("foobar")) .build(); try_codec(f); } #[test] fn test_request_channel() { let f = RequestChannel::builder(1234, 0) .set_initial_request_n(1) .set_data(Bytes::from("Hello World!")) .set_metadata(Bytes::from("foobar")) .build(); try_codec(f); } #[test] fn test_cancel() { let f = Cancel::builder(1234, 0).build(); try_codec(f); } #[test] fn test_request_fnf() { let f = RequestFNF::builder(1234, 0) .set_data(Bytes::from("Hello")) .set_metadata(Bytes::from("World")) .build(); try_codec(f); } #[test] fn test_metadata_push() { let f = MetadataPush::builder(1234, 0) .set_metadata(Bytes::from("Hello Rust!")) .build(); try_codec(f); } #[test] fn test_request_n() { let f = RequestN::builder(1234, 0).set_n(77778888).build(); try_codec(f); } #[test] fn test_lease() { let f = Lease::builder(1234, 0) .set_metadata(Bytes::from("Hello Rust!")) .set_number_of_requests(333) .set_ttl(1000) .build(); try_codec(f); } #[test] fn test_error() { let f = Error::builder(1234, 0) .set_data(Bytes::from("Hello World!")) .set_code(4444) .build(); try_codec(f); } #[test] fn resume_ok() { let f = ResumeOK::builder(1234, 0).set_position(2333).build(); try_codec(f); } #[test] fn test_resume() { let f = Resume::builder(0, Frame::FLAG_RESUME) .set_last_received_server_position(123) .set_first_available_client_position(22) .set_token(Bytes::from("this is a token")) .build(); try_codec(f); } fn try_codec(f: Frame) { println!("******* codec: {:?}", f); let mut bf = BytesMut::with_capacity(f.len() as usize); f.write_to(&mut bf); println!("####### encode: {}", hex::encode(bf.to_vec())); let f2 = Frame::decode(&mut bf).unwrap(); println!("####### decode: {:?}", f2); assert_eq!( f, f2, "frames doesn't match: expect={:?}, actual={:?}", f, f2 ); }
pub const BUFFER_HEIGHT: usize = 25; pub const BUFFER_WIDTH: usize = 80; pub fn halt_cpu() -> ! { unsafe { asm!("hlt"); } loop {} // Never reach here } pub fn out_byte(dst: u16, value: u8) { unsafe { asm!( "mov $0, %dx mov $1, %al out %al, %dx" : // no output : "r"(dst), "r"(value) : "al", "dx" ); } } pub fn out_word(dst: u16, value: u16) { unsafe { asm!( "mov $0, %dx mov $1, %ax out %ax, %dx" : // no output : "r"(dst), "r"(value) : "ax", "dx" ); } } pub fn out_dword(dst: u16, value: u32) { unsafe { asm!( "mov $0, %dx mov $1, %eax out %eax, %dx" : // no output : "r"(dst), "r"(value) : "eax", "dx" ); } } pub fn disable_cursor() { out_byte(0x3D4, 0x0A); out_byte(0x3D5, 0x20); } pub fn move_cursor(x: usize, y: usize) { let position = y * BUFFER_WIDTH + x; out_byte(0x3D4, 0x0F); out_byte(0x3D5, (position & 0xFF) as _); out_byte(0x3D4, 0x0E); out_byte(0x3D5, ((position >> 8) & 0xFF) as _); }
/// A basic trie, used to associate patterns to their hyphenation scores. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Patterns { pub tally: Option<Vec<(u8, u8)>>, pub descendants: HashMap<u8, Patterns, BuildHasherDefault<FnvHasher>> } /// A specialized hash map of pattern-score pairs. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Exceptions(pub HashMap<String, Vec<usize>>);
#[doc = "Register `ADC2_OR` reader"] pub type R = crate::R<ADC2_OR_SPEC>; #[doc = "Register `ADC2_OR` writer"] pub type W = crate::W<ADC2_OR_SPEC>; #[doc = "Field `VDDCOREEN` reader - VDDCOREEN"] pub type VDDCOREEN_R = crate::BitReader; #[doc = "Field `VDDCOREEN` writer - VDDCOREEN"] pub type VDDCOREEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - VDDCOREEN"] #[inline(always)] pub fn vddcoreen(&self) -> VDDCOREEN_R { VDDCOREEN_R::new((self.bits & 1) != 0) } } impl W { #[doc = "Bit 0 - VDDCOREEN"] #[inline(always)] #[must_use] pub fn vddcoreen(&mut self) -> VDDCOREEN_W<ADC2_OR_SPEC, 0> { VDDCOREEN_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "ADC2 option register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`adc2_or::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`adc2_or::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ADC2_OR_SPEC; impl crate::RegisterSpec for ADC2_OR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`adc2_or::R`](R) reader structure"] impl crate::Readable for ADC2_OR_SPEC {} #[doc = "`write(|w| ..)` method takes [`adc2_or::W`](W) writer structure"] impl crate::Writable for ADC2_OR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets ADC2_OR to value 0"] impl crate::Resettable for ADC2_OR_SPEC { const RESET_VALUE: Self::Ux = 0; }
fn main() { println!("Hello, World!"); another_function(5,6); } fn another_function(x: i32,y: i32) { println!("The value of x and y are: {} and {}",x,y); }
// Here it goes all the stuff related with "Settings" and "My Mod" windows. extern crate gtk; extern crate pango; extern crate url; use std::cell::RefCell; use std::rc::Rc; use std::path::{ Path, PathBuf }; use url::Url; use gtk::prelude::*; use gtk::{ Entry, Button, Frame, ComboBoxText, ApplicationWindow, WindowPosition, Orientation, Label, ButtonBox, ButtonBoxStyle, Application, FileChooserNative, ResponseType, FileChooserAction, ReliefStyle, StyleContext, CheckButton, Grid, FontButton }; use pango::{ AttrList, Attribute }; use packfile::packfile::PackFile; use settings::Settings; use settings::GameInfo; use settings::GameSelected; use AppUI; use super::*; use packfile; /// `SettingsWindow`: This struct holds all the relevant stuff for the Settings Window. #[derive(Clone, Debug)] pub struct SettingsWindow { pub settings_window: ApplicationWindow, pub settings_path_my_mod_entry: Entry, pub settings_path_my_mod_button: Button, pub settings_path_entries: Vec<Entry>, pub settings_path_buttons: Vec<Button>, pub settings_game_list_combo: ComboBoxText, pub settings_extra_allow_edition_of_ca_packfiles: CheckButton, pub settings_extra_check_updates_on_start: CheckButton, pub settings_extra_check_schema_updates_on_start: CheckButton, pub settings_theme_prefer_dark_theme: CheckButton, pub settings_theme_font_button: FontButton, pub settings_cancel: Button, pub settings_accept: Button, } /// `MyModNewWindow`: This struct holds all the relevant stuff for "My Mod"'s New Mod Window. #[derive(Clone, Debug)] pub struct MyModNewWindow { pub my_mod_new_window: ApplicationWindow, pub my_mod_new_game_list_combo: ComboBoxText, pub my_mod_new_name_entry: Entry, pub my_mod_new_cancel: Button, pub my_mod_new_accept: Button, } /// `NewPrefabWindow`: This struct holds all the relevant stuff for the "New Prefab" window to work. #[derive(Clone, Debug)] pub struct NewPrefabWindow { pub window: ApplicationWindow, pub entries: Vec<Entry>, pub accept_button: Button, pub cancel_button: Button, } /// Implementation of `SettingsWindow`. impl SettingsWindow { /// This function creates the entire settings window. It requires the application object to pass /// the window to. pub fn create_settings_window(application: &Application, parent: &ApplicationWindow, rpfm_path: &PathBuf, supported_games: &[GameInfo]) -> SettingsWindow { let settings_window = ApplicationWindow::new(application); settings_window.set_size_request(700, 0); settings_window.set_transient_for(parent); settings_window.set_position(WindowPosition::CenterOnParent); settings_window.set_title("Settings"); // Config the icon for the Settings Window. If this fails, something went wrong when setting the paths, // so crash the program, as we don't know what more is broken. settings_window.set_icon_from_file(&Path::new(&format!("{}/img/rpfm.png", rpfm_path.to_string_lossy()))).unwrap(); // Disable the menubar in this window. settings_window.set_show_menubar(false); // Get the current GTK settings. This unwrap is not expected to fail anytime, so we unwrap it. let gtk_settings = &settings_window.get_settings().unwrap(); // Stuff of the Settings window. let big_grid = Grid::new(); big_grid.set_border_width(6); big_grid.set_row_spacing(3); big_grid.set_column_spacing(3); let paths_frame = Frame::new(Some("Paths")); let paths_grid = Grid::new(); paths_frame.set_label_align(0.04, 0.5); paths_grid.set_border_width(6); paths_grid.set_row_spacing(3); paths_grid.set_column_spacing(3); // The "MyMod" entry is created here. let my_mod_label = Label::new(Some("My mod's folder")); let my_mod_entry = Entry::new(); let my_mod_button = Button::new_with_label("..."); my_mod_label.set_size_request(170, 0); my_mod_label.set_xalign(0.0); my_mod_label.set_yalign(0.5); my_mod_entry.set_has_frame(false); my_mod_entry.set_hexpand(true); my_mod_entry.set_placeholder_text("This is the folder where you want to store all \"MyMod\" related files."); // All the "Game" entries are created dinamically here, depending on the supported games. let mut game_entries: Vec<Entry> = vec![]; let mut game_buttons: Vec<Button> = vec![]; for (index, game) in supported_games.iter().enumerate() { let label = Label::new(Some(&*format!("TW: {} folder", game.display_name))); let entry = Entry::new(); let button = Button::new_with_label("..."); label.set_size_request(170, 0); label.set_xalign(0.0); label.set_yalign(0.5); entry.set_has_frame(false); entry.set_hexpand(true); entry.set_placeholder_text(&*format!("This is the folder where you have {} installed.", game.display_name)); paths_grid.attach(&label, 0, (index + 1) as i32, 1, 1); paths_grid.attach(&entry, 1, (index + 1) as i32, 1, 1); paths_grid.attach(&button, 2, (index + 1) as i32, 1, 1); game_entries.push(entry); game_buttons.push(button); } let theme_frame = Frame::new(Some("Theme Settings")); let theme_grid = Grid::new(); theme_frame.set_label_align(0.04, 0.5); theme_grid.set_border_width(6); theme_grid.set_row_spacing(3); theme_grid.set_column_spacing(3); let prefer_dark_theme_label = Label::new(Some("Use Dark Theme:")); let prefer_dark_theme_checkbox = CheckButton::new(); let font_settings_label = Label::new(Some("Font Settings:")); let font_settings_button = FontButton::new(); prefer_dark_theme_label.set_size_request(170, 0); prefer_dark_theme_label.set_xalign(0.0); prefer_dark_theme_label.set_yalign(0.5); prefer_dark_theme_checkbox.set_hexpand(true); font_settings_label.set_size_request(170, 0); font_settings_label.set_xalign(0.0); font_settings_label.set_yalign(0.5); font_settings_button.set_hexpand(true); let extra_settings_frame = Frame::new(Some("Extra Settings")); let extra_settings_grid = Grid::new(); extra_settings_frame.set_label_align(0.04, 0.5); extra_settings_grid.set_border_width(6); extra_settings_grid.set_row_spacing(3); extra_settings_grid.set_column_spacing(3); let default_game_label = Label::new(Some("Default Game Selected:")); let game_list_combo = ComboBoxText::new(); default_game_label.set_size_request(170, 0); default_game_label.set_xalign(0.0); default_game_label.set_yalign(0.5); for game in supported_games.iter() { game_list_combo.append(Some(&*game.folder_name), &game.display_name); } game_list_combo.set_active(0); game_list_combo.set_hexpand(true); let allow_edition_of_ca_packfiles_label = Label::new(Some("Allow edition of CA PackFiles:")); let allow_edition_of_ca_packfiles_checkbox = CheckButton::new(); allow_edition_of_ca_packfiles_label.set_size_request(170, 0); allow_edition_of_ca_packfiles_label.set_xalign(0.0); allow_edition_of_ca_packfiles_label.set_yalign(0.5); allow_edition_of_ca_packfiles_checkbox.set_hexpand(true); let check_updates_on_start_label = Label::new(Some("Check Updates on Start:")); let check_updates_on_start_checkbox = CheckButton::new(); check_updates_on_start_label.set_size_request(170, 0); check_updates_on_start_label.set_xalign(0.0); check_updates_on_start_label.set_yalign(0.5); check_updates_on_start_checkbox.set_hexpand(true); let check_schema_updates_on_start_label = Label::new(Some("Check Schema Updates on Start:")); let check_schema_updates_on_start_checkbox = CheckButton::new(); check_schema_updates_on_start_label.set_size_request(170, 0); check_schema_updates_on_start_label.set_xalign(0.0); check_schema_updates_on_start_label.set_yalign(0.5); check_schema_updates_on_start_checkbox.set_hexpand(true); let button_box = ButtonBox::new(Orientation::Horizontal); button_box.set_layout(ButtonBoxStyle::End); button_box.set_spacing(10); let restore_default_button = Button::new_with_label("Restore Default"); let cancel_button = Button::new_with_label("Cancel"); let accept_button = Button::new_with_label("Accept"); // Frame packing stuff... paths_grid.attach(&my_mod_label, 0, 0, 1, 1); paths_grid.attach(&my_mod_entry, 1, 0, 1, 1); paths_grid.attach(&my_mod_button, 2, 0, 1, 1); paths_frame.add(&paths_grid); // Theme Settings packing stuff... theme_grid.attach(&prefer_dark_theme_label, 0, 0, 1, 1); theme_grid.attach(&prefer_dark_theme_checkbox, 1, 0, 1, 1); theme_grid.attach(&font_settings_label, 0, 1, 1, 1); theme_grid.attach(&font_settings_button, 1, 1, 1, 1); theme_frame.add(&theme_grid); // Extra Settings packing stuff extra_settings_grid.attach(&default_game_label, 0, 0, 1, 1); extra_settings_grid.attach(&game_list_combo, 1, 0, 1, 1); extra_settings_grid.attach(&allow_edition_of_ca_packfiles_label, 0, 1, 1, 1); extra_settings_grid.attach(&allow_edition_of_ca_packfiles_checkbox, 1, 1, 1, 1); extra_settings_grid.attach(&check_updates_on_start_label, 0, 2, 1, 1); extra_settings_grid.attach(&check_updates_on_start_checkbox, 1, 2, 1, 1); extra_settings_grid.attach(&check_schema_updates_on_start_label, 0, 3, 1, 1); extra_settings_grid.attach(&check_schema_updates_on_start_checkbox, 1, 3, 1, 1); extra_settings_frame.add(&extra_settings_grid); // ButtonBox packing stuff... button_box.pack_start(&restore_default_button, false, false, 0); button_box.pack_start(&cancel_button, false, false, 0); button_box.pack_start(&accept_button, false, false, 0); // General packing stuff... big_grid.attach(&paths_frame, 0, 0, 2, 1); big_grid.attach(&theme_frame, 0, 1, 1, 1); big_grid.attach(&extra_settings_frame, 1, 1, 1, 1); big_grid.attach(&button_box, 0, 2, 2, 1); settings_window.add(&big_grid); settings_window.show_all(); // Event to change between "Light/Dark" theme variations. prefer_dark_theme_checkbox.connect_toggled(clone!( gtk_settings => move |checkbox| { gtk_settings.set_property_gtk_application_prefer_dark_theme(checkbox.get_active()); } )); // Event to change the Font used. font_settings_button.connect_font_set(clone!( gtk_settings => move |font_settings_button| { let new_font = font_settings_button.get_font_name().unwrap_or_else(|| String::from("Segoe UI 9")); gtk_settings.set_property_gtk_font_name(Some(&new_font)); } )); // Events for the `Entries`. // Check all the entries. If all are valid, enable the "Accept" button. // FIXME: Fix this shit. accept_button.connect_property_relief_notify(clone!( game_entries, my_mod_entry => move |accept_button| { let mut invalid_path = false; for game in &game_entries { if Path::new(&game.get_buffer().get_text()).is_dir() || game.get_buffer().get_text().is_empty() { invalid_path = false; } else { invalid_path = true; break; } } if (Path::new(&my_mod_entry.get_buffer().get_text()).is_dir() || my_mod_entry.get_buffer().get_text().is_empty()) && !invalid_path { accept_button.set_sensitive(true); } else { accept_button.set_sensitive(false); } } )); // Set their background red while writing in them if their path is not valid. my_mod_entry.connect_changed(clone!( accept_button, my_mod_button => move |text_entry| { paint_entry(text_entry, &my_mod_button, &accept_button); } )); // When we press the "..." buttons. my_mod_button.connect_button_release_event(clone!( my_mod_entry, my_mod_button, accept_button, settings_window => move |_,_| { update_entry_path( &my_mod_entry, &my_mod_button, &accept_button, "Select MyMod's Folder", &settings_window, ); Inhibit(false) } )); // Create an iterator chaining every entry with his button. let game_entries_cloned = game_entries.clone(); let game_buttons_cloned = game_buttons.clone(); let entries = game_entries_cloned.iter().cloned().zip(game_buttons_cloned.iter().cloned()); for (index, game) in entries.enumerate() { // When we change the path in the game's entry. game.0.connect_changed(clone!( accept_button, game => move |text_entry| { paint_entry(text_entry, &game.1, &accept_button); } )); // When we press the "..." buttons. let supported_games = supported_games.to_vec(); game.1.connect_button_release_event(clone!( game, accept_button, supported_games, settings_window => move |_,_| { update_entry_path( &game.0, &game.1, &accept_button, &format!("Select {} Folder", &supported_games[index].display_name), &settings_window, ); Inhibit(false) } )); } // Create the SettingsWindow object and store it (We need it for the "Restore Default" button). let window = SettingsWindow { settings_window, settings_path_my_mod_entry: my_mod_entry, settings_path_my_mod_button: my_mod_button, settings_path_entries: game_entries, settings_path_buttons: game_buttons, settings_game_list_combo: game_list_combo, settings_extra_allow_edition_of_ca_packfiles: allow_edition_of_ca_packfiles_checkbox, settings_extra_check_updates_on_start: check_updates_on_start_checkbox, settings_extra_check_schema_updates_on_start: check_schema_updates_on_start_checkbox, settings_theme_prefer_dark_theme: prefer_dark_theme_checkbox, settings_theme_font_button: font_settings_button, settings_cancel: cancel_button, settings_accept: accept_button, }; // When we press the "Restore Default" button, we restore the settings to their "Default" values. let supported_games = supported_games.to_vec(); restore_default_button.connect_button_release_event(clone!( window => move |_,_| { let default_settings = Settings::new(&supported_games); window.load_to_settings_window(&default_settings); load_gtk_settings(&window.settings_window, &default_settings); Inhibit(false) } )); // Now, return the window. window } /// This function loads the data from the settings object to the settings window. pub fn load_to_settings_window(&self, settings: &Settings) { // Load the "Default Game". self.settings_game_list_combo.set_active_id(Some(&*settings.default_game)); // Load the "Allow Edition of CA PackFiles" setting. self.settings_extra_allow_edition_of_ca_packfiles.set_active(settings.allow_edition_of_ca_packfiles); // Load the "Check Updates on Start" settings. self.settings_extra_check_updates_on_start.set_active(settings.check_updates_on_start); self.settings_extra_check_schema_updates_on_start.set_active(settings.check_schema_updates_on_start); // Load the current Theme prefs. self.settings_theme_prefer_dark_theme.set_active(settings.prefer_dark_theme); self.settings_theme_font_button.set_font_name(&settings.font); // Load the data to the entries. self.settings_path_my_mod_entry.get_buffer().set_text(&settings.paths.my_mods_base_path.clone().unwrap_or_else(||PathBuf::new()).to_string_lossy()); // Load the data to the game entries. let entries = self.settings_path_entries.iter().zip(self.settings_path_buttons.iter()); for (index, game) in entries.clone().enumerate() { game.0.get_buffer().set_text(&settings.paths.game_paths[index].path.clone().unwrap_or_else(||PathBuf::new()).to_string_lossy()); } // Paint the entries and buttons. paint_entry(&self.settings_path_my_mod_entry, &self.settings_path_my_mod_button, &self.settings_accept); for game in entries { paint_entry(game.0, game.1, &self.settings_accept); } } /// This function gets the data from the settings window and returns a Settings object with that /// data in it. pub fn save_from_settings_window(&self, supported_games: &[GameInfo]) -> Settings { let mut settings = Settings::new(supported_games); // We get his game's folder, depending on the selected game. settings.default_game = self.settings_game_list_combo.get_active_id().unwrap(); // Get the "Allow Edition of CA PackFiles" setting. settings.allow_edition_of_ca_packfiles = self.settings_extra_allow_edition_of_ca_packfiles.get_active(); // Get the "Check Updates on Start" settings. settings.check_updates_on_start = self.settings_extra_check_updates_on_start.get_active(); settings.check_schema_updates_on_start = self.settings_extra_check_schema_updates_on_start.get_active(); // Get the Theme and Font settings. settings.prefer_dark_theme = self.settings_theme_prefer_dark_theme.get_active(); settings.font = self.settings_theme_font_button.get_font_name().unwrap_or_else(|| String::from("Segoe UI 9")); // Only if we have valid directories, we save them. Otherwise we wipe them out. settings.paths.my_mods_base_path = match Path::new(&self.settings_path_my_mod_entry.get_buffer().get_text()).is_dir() { true => Some(PathBuf::from(&self.settings_path_my_mod_entry.get_buffer().get_text())), false => None, }; // For each entry, we get check if it's a valid directory and save it into `settings`. let entries = self.settings_path_entries.iter().zip(self.settings_path_buttons.iter()); for (index, game) in entries.enumerate() { settings.paths.game_paths[index].path = match Path::new(&game.0.get_buffer().get_text()).is_dir() { true => Some(PathBuf::from(&game.0.get_buffer().get_text())), false => None, } } settings } } /// Implementation of `MyModNewWindow`. impl MyModNewWindow { /// This function creates the entire "New Mod" window. It requires the application object to pass /// the window to. pub fn create_my_mod_new_window( application: &Application, parent: &ApplicationWindow, supported_games: &[GameInfo], game_selected: &GameSelected, settings: &Settings, rpfm_path: &PathBuf ) -> MyModNewWindow { let my_mod_new_window = ApplicationWindow::new(application); my_mod_new_window.set_size_request(500, 0); my_mod_new_window.set_transient_for(parent); my_mod_new_window.set_position(WindowPosition::CenterOnParent); my_mod_new_window.set_title("New MyMod"); // Config the icon for the New "MyMod" Window. If this fails, something went wrong when setting the paths, // so crash the program, as we don't know what more is broken. my_mod_new_window.set_icon_from_file(&Path::new(&format!("{}/img/rpfm.png", rpfm_path.to_string_lossy()))).unwrap(); // Disable the menubar in this window. my_mod_new_window.set_show_menubar(false); // Stuff of the "New Mod" window. let big_grid = Grid::new(); big_grid.set_border_width(6); big_grid.set_row_spacing(6); big_grid.set_column_spacing(3); let advices_frame = Frame::new(Some("Advices")); advices_frame.set_label_align(0.04, 0.5); let advices_label = Label::new(Some("Things to take into account before creating a new mod: - Select the game you'll make the mod for. - Pick an simple name (it shouldn't end in *.pack). - If you want to use multiple words, use \"_\" instead of \" \". - You can't create a mod for a game that has no path set in the settings.")); advices_label.set_size_request(-1, 0); advices_label.set_xalign(0.5); advices_label.set_yalign(0.5); let mod_name_label = Label::new(Some("Name of the Mod:")); mod_name_label.set_size_request(120, 0); mod_name_label.set_xalign(0.0); mod_name_label.set_yalign(0.5); let mod_name_entry = Entry::new(); mod_name_entry.set_placeholder_text("For example: one_ring_for_me"); mod_name_entry.set_hexpand(true); mod_name_entry.set_has_frame(false); let selected_game_label = Label::new(Some("Game of the Mod:")); selected_game_label.set_size_request(120, 0); selected_game_label.set_xalign(0.0); selected_game_label.set_yalign(0.5); let selected_game_list_combo = ComboBoxText::new(); for game in supported_games.iter() { selected_game_list_combo.append(Some(&*game.folder_name), &game.display_name); } selected_game_list_combo.set_active_id(Some(&*game_selected.game)); selected_game_list_combo.set_hexpand(true); let button_box = ButtonBox::new(Orientation::Horizontal); button_box.set_layout(ButtonBoxStyle::End); button_box.set_spacing(6); let cancel_button = Button::new_with_label("Cancel"); let accept_button = Button::new_with_label("Accept"); // Frame packing stuff... advices_frame.add(&advices_label); // ButtonBox packing stuff... button_box.pack_start(&cancel_button, false, false, 0); button_box.pack_start(&accept_button, false, false, 0); // General packing stuff... big_grid.attach(&advices_frame, 0, 0, 2, 1); big_grid.attach(&mod_name_label, 0, 1, 1, 1); big_grid.attach(&mod_name_entry, 1, 1, 1, 1); big_grid.attach(&selected_game_label, 0, 2, 1, 1); big_grid.attach(&selected_game_list_combo, 1, 2, 1, 1); big_grid.attach(&button_box, 0, 3, 2, 1); my_mod_new_window.add(&big_grid); my_mod_new_window.show_all(); // By default, the `mod_name_entry` will be empty, so let the ´Accept´ button disabled. accept_button.set_sensitive(false); // Events to check the Mod's Name is valid and available. This should be done while writing // in `mod_name_entry` and when changing the selected game. mod_name_entry.connect_changed(clone!( settings, selected_game_list_combo, accept_button => move |text_entry| { let selected_game = selected_game_list_combo.get_active_id().unwrap(); check_my_mod_validity(text_entry, selected_game, &settings, &accept_button); } )); selected_game_list_combo.connect_changed(clone!( mod_name_entry, settings, accept_button => move |selected_game_list_combo| { let selected_game = selected_game_list_combo.get_active_id().unwrap(); check_my_mod_validity(&mod_name_entry, selected_game, &settings, &accept_button); } )); MyModNewWindow { my_mod_new_window, my_mod_new_game_list_combo: selected_game_list_combo, my_mod_new_name_entry: mod_name_entry, my_mod_new_cancel: cancel_button, my_mod_new_accept: accept_button, } } } /// Implementation of `NewPrefabWindow`. impl NewPrefabWindow { /// This function creates the window and sets the events needed for everything to work. pub fn create_new_prefab_window( app_ui: &AppUI, application: &Application, game_selected: &Rc<RefCell<GameSelected>>, pack_file_decoded: &Rc<RefCell<PackFile>>, catchment_indexes: &[usize] ) { // Create the "New Name" window... let window = ApplicationWindow::new(application); window.set_size_request(500, 0); window.set_transient_for(&app_ui.window); window.set_position(WindowPosition::CenterOnParent); window.set_title("New Prefab"); // Disable the menubar in this window. window.set_show_menubar(false); // Create the main `Grid`. let grid = Grid::new(); grid.set_border_width(6); grid.set_row_spacing(6); grid.set_column_spacing(3); // Create the `Frame` for the list of catchments. let prefab_frame = Frame::new(Some("Possible Prefabs")); prefab_frame.set_label_align(0.04, 0.5); // Create the entries `Grid`. let entries_grid = Grid::new(); entries_grid.set_border_width(6); entries_grid.set_row_spacing(6); entries_grid.set_column_spacing(3); prefab_frame.add(&entries_grid); // Create the list of entries. let mut entries = vec![]; // For each catchment... for (index, catchment_index) in catchment_indexes.iter().enumerate() { // Create the label and the entry. let label = Label::new(Some(&*format!("Prefab's name for \"{}\\{}\":", pack_file_decoded.borrow().data.packed_files[*catchment_index].path[4], pack_file_decoded.borrow().data.packed_files[*catchment_index].path[5]))); let entry = Entry::new(); label.set_xalign(0.0); label.set_yalign(0.5); entry.set_placeholder_text("For example: one_ring_for_me"); entry.set_hexpand(true); entry.set_has_frame(false); entry.set_size_request(200, 0); entries_grid.attach(&label, 0, index as i32, 1, 1); entries_grid.attach(&entry, 1, index as i32, 1, 1); // And push his entry to the list. entries.push(entry); } // Create the buttons. let button_box = ButtonBox::new(Orientation::Horizontal); button_box.set_layout(ButtonBoxStyle::End); button_box.set_spacing(6); let accept_button = Button::new_with_label("Accept"); let cancel_button = Button::new_with_label("Cancel"); // ButtonBox packing stuff... button_box.pack_start(&cancel_button, false, false, 0); button_box.pack_start(&accept_button, false, false, 0); // Grid packing stuff... grid.attach(&prefab_frame, 0, 0, 1, 1); grid.attach(&button_box, 0, 1, 1, 1); window.add(&grid); window.show_all(); // Disable the accept button by default. accept_button.set_sensitive(false); // Get all the stuff inside one struct, so it's easier to pass it to the closures. let new_prefab_stuff = Self { window, entries, accept_button, cancel_button, }; // Events for this to work. // Every time we change a character in the entry, check if the name is valid, and disable the "Accept" // button if it's invalid. for entry in &new_prefab_stuff.entries { entry.connect_changed(clone!( game_selected, new_prefab_stuff => move |entry| { // If it's stupid but it works,... new_prefab_stuff.accept_button.set_relief(ReliefStyle::None); new_prefab_stuff.accept_button.set_relief(ReliefStyle::Normal); // If our Game Selected have a path in settings... if let Some(ref game_path) = game_selected.borrow().game_path { // Get the "final" path for that prefab. let prefab_name = entry.get_text().unwrap(); let prefab_path = game_path.to_path_buf().join(PathBuf::from(format!("assembly_kit/raw_data/art/prefabs/battle/custom_prefabs/{}.terry", prefab_name))); // Create an attribute list for the entry. let attribute_list = AttrList::new(); let invalid_color = Attribute::new_background((214 * 256) - 1, (75 * 256) - 1, (139 * 256) - 1).unwrap(); // If it already exist, allow it but mark it, so prefabs don't get overwritten by error. if prefab_path.is_file() { attribute_list.insert(invalid_color); } // Paint it like one of your french girls. entry.set_attributes(&attribute_list); } } )); } // If any of the entries has changed, check if we can enable it. new_prefab_stuff.accept_button.connect_property_relief_notify(clone!( new_prefab_stuff => move |accept_button| { // Create the var to check if the name is valid, and the vector to store the names. let mut invalid_name = false; let mut name_list = vec![]; // For each entry... for entry in &new_prefab_stuff.entries { // Get his text. let name = entry.get_text().unwrap(); // If it has spaces, it's empty or it's repeated, it's automatically invalid. if name.contains(' ') || name.is_empty() || name_list.contains(&name) { invalid_name = true; break; } // Otherwise, we add it to the list. else { name_list.push(name); } } // We enable or disable the button, depending if the name is valid. if invalid_name { accept_button.set_sensitive(false); } else { accept_button.set_sensitive(true); } } )); // When we press the "Cancel" button, we close the window and re-enable the main window. new_prefab_stuff.cancel_button.connect_button_release_event(clone!( new_prefab_stuff, app_ui => move |_,_| { // Destroy the "New Prefab" window, new_prefab_stuff.window.destroy(); // Restore the main window. app_ui.window.set_sensitive(true); Inhibit(false) } )); // We catch the destroy event of the window. new_prefab_stuff.window.connect_delete_event(clone!( new_prefab_stuff, app_ui => move |_, _| { // Destroy the "New Prefab" window, new_prefab_stuff.window.destroy(); // Restore the main window. app_ui.window.set_sensitive(true); Inhibit(false) } )); // For some reason, the clone! macro is unable to clone this, so we clone it here. let catchment_indexes = catchment_indexes.to_vec(); // If we hit the "Accept" button.... new_prefab_stuff.accept_button.connect_button_release_event(clone!( app_ui, pack_file_decoded, game_selected, new_prefab_stuff => move |_,_| { // Get the base path of the game, to put the prefabs in his Assembly Kit directory. match game_selected.borrow().game_path { Some(ref game_path) => { // Get the list of all the names in the entries. let name_list = new_prefab_stuff.entries.iter().filter_map(|entry| entry.get_text()).collect::<Vec<String>>(); // Try to create the prefabs with the provided names. match packfile::create_prefab_from_catchment( &name_list, &game_path, &catchment_indexes, &pack_file_decoded, ) { Ok(result) => show_dialog(&app_ui.window, true, result), Err(error) => show_dialog(&app_ui.window, false, error), }; } // If there is no game_path, stop and report error. None => show_dialog(&app_ui.window, false, "The selected Game Selected doesn't have a path specified in the Settings."), } // Destroy the "New Prefab" window, new_prefab_stuff.window.destroy(); // Re-enable the main window. app_ui.window.set_sensitive(true); Inhibit(false) } )); } } /// This function paints the provided `Entry` depending if the text inside the `Entry` is a valid /// `Path` or not. It also set the button as "destructive-action" if there is no path set or it's /// invalid. And, If any of the paths is invalid, it disables the "Accept" button. fn paint_entry(text_entry: &Entry, text_button: &Button, accept_button: &Button) { let text = text_entry.get_buffer().get_text(); let attribute_list = AttrList::new(); let style_context = text_button.get_style_context().unwrap(); // Set `text_button` as "Normal" by default. text_button.set_relief(ReliefStyle::None); StyleContext::remove_class(&style_context, "suggested-action"); StyleContext::remove_class(&style_context, "destructive-action"); // If there is text and it's an invalid path, we paint in red. We clear the background otherwise. if !text.is_empty() { if !Path::new(&text).is_dir() { let red = Attribute::new_background(65535, 35000, 35000).unwrap(); attribute_list.insert(red); text_button.set_relief(ReliefStyle::Normal); StyleContext::add_class(&style_context, "destructive-action"); } } // If the `Entry` is empty, we mark his button red. else { text_button.set_relief(ReliefStyle::Normal); StyleContext::add_class(&style_context, "suggested-action"); } text_entry.set_attributes(&attribute_list); // Trigger the "check all the paths" signal. This is extremely wonky, but until I find a better // way to do it.... It works. // FIXME: Fix this shit. accept_button.set_relief(ReliefStyle::None); accept_button.set_relief(ReliefStyle::Normal); } /// Modification of `paint_entry`. In this one, the button painted red is the `Accept` button. fn check_my_mod_validity( text_entry: &Entry, selected_game: String, settings: &Settings, accept_button: &Button ) { let text = text_entry.get_buffer().get_text(); let attribute_list = AttrList::new(); let red = Attribute::new_background(65535, 35000, 35000).unwrap(); // If there is text and it doesn't have whitespaces... if !text.is_empty() && !text.contains(' ') { // If we have "MyMod" path configured (we SHOULD have it to access this window, but just in case...). if let Some(ref mod_path) = settings.paths.my_mods_base_path { let mut mod_path = mod_path.clone(); mod_path.push(selected_game); mod_path.push(format!("{}.pack", text)); // If a mod with that name for that game already exists, disable the "Accept" button. if mod_path.is_file() { attribute_list.insert(red); accept_button.set_sensitive(false); } // If the name is available, enable the `Accept` button. else { accept_button.set_sensitive(true); } } // If there is no "MyMod" path configured, disable the button. else { attribute_list.insert(red); accept_button.set_sensitive(false); } } // If name is empty, disable the button but don't make the text red. else { accept_button.set_sensitive(false); } text_entry.set_attributes(&attribute_list); } /// This function gets a Folder from a Native FileChooser and put his path into the provided `Entry`. fn update_entry_path( text_entry: &Entry, text_button: &Button, accept_button: &Button, file_chooser_title: &str, file_chooser_parent: &ApplicationWindow) { let file_chooser_select_folder = FileChooserNative::new( file_chooser_title, file_chooser_parent, FileChooserAction::SelectFolder, "Accept", "Cancel" ); // If we already have a Path inside the `text_entry` (and it's not empty or an invalid folder), // we set it as "starting" path for the FileChooser. if let Some(current_path) = text_entry.get_text() { if !current_path.is_empty() && PathBuf::from(&current_path).is_dir() { file_chooser_select_folder.set_current_folder(PathBuf::from(&current_path)); } } // Then run the created FileChooser and update the `text_entry` only if we received `Accept`. // We get his `URI`, translate it into `PathBuf`, and then to `&str` to put it into `text_entry`. if file_chooser_select_folder.run() == Into::<i32>::into(ResponseType::Accept) { if let Some(new_folder) = file_chooser_select_folder.get_uri() { let path = Url::parse(&new_folder).unwrap().to_file_path().unwrap(); text_entry.set_text(&path.to_string_lossy()); paint_entry(text_entry, text_button, accept_button); } } } /// This function loads the Theme and Font settings we have in our `Setting` object to GTK. pub fn load_gtk_settings(window: &ApplicationWindow, settings: &Settings) { // Depending on our settings, load the GTK Theme we want to use. let gtk_settings = window.get_settings().unwrap(); gtk_settings.set_property_gtk_application_prefer_dark_theme(settings.prefer_dark_theme); gtk_settings.set_property_gtk_font_name(Some(&settings.font)); }
#[macro_use] extern crate criterion; extern crate hamming; use criterion::{Criterion, Bencher, ParameterizedBenchmark, PlotConfiguration, AxisScale}; const SIZES: [usize; 7] = [1, 10, 100, 1000, 10_000, 100_000, 1_000_000]; macro_rules! create_benchmarks { ($( fn $group_id: ident($input: expr) { $first_name: expr => $first_func: expr, $($rest_name: expr => $rest_func: expr,)* } )*) => { $( fn $group_id(c: &mut Criterion) { let input = $input; let plot_config = PlotConfiguration::default() .summary_scale(AxisScale::Logarithmic); let bench = ParameterizedBenchmark::new( $first_name, $first_func, input.into_iter().cloned()) $( .with_function($rest_name, $rest_func) )* .plot_config(plot_config); c.bench(stringify!($group_id), bench); } )* } } fn naive_weight(x: &[u8]) -> u64 { x.iter().fold(0, |a, b| a + b.count_ones() as u64) } fn weight_bench<F: 'static + FnMut(&[u8]) -> u64>(mut f: F) -> impl FnMut(&mut Bencher, &usize) { move |b, n| { let data = vec![0xFF; *n]; b.iter(|| f(criterion::black_box(&data))) } } fn naive_distance(x: &[u8], y: &[u8]) -> u64 { assert_eq!(x.len(), y.len()); x.iter().zip(y).fold(0, |a, (b, c)| a + (*b ^ *c).count_ones() as u64) } fn distance_bench<F: 'static + FnMut(&[u8], &[u8]) -> u64>(mut f: F) -> impl FnMut(&mut Bencher, &usize) { move |b, n| { let data = vec![0xFF; *n]; b.iter(|| { let d1 = criterion::black_box(&data); let d2 = criterion::black_box(&data); f(d1, d2) }) } } create_benchmarks! { fn weight(SIZES) { "naive" => weight_bench(naive_weight), "weight" => weight_bench(hamming::weight), } fn distance(SIZES) { "naive" => distance_bench(naive_distance), "distance" => distance_bench(hamming::distance), } } criterion_group!(benches, weight, distance); criterion_main!(benches);
use crate::coord::CoordTranslate; use crate::drawing::DrawingArea; use crate::drawing::DrawingBackend; /// The trait indicates that the type has a dimension info pub trait HasDimension { fn dim(&self) -> (u32, u32); } impl<T: DrawingBackend> HasDimension for T { fn dim(&self) -> (u32, u32) { self.get_size() } } impl<D: DrawingBackend, C: CoordTranslate> HasDimension for DrawingArea<D, C> { fn dim(&self) -> (u32, u32) { self.dim_in_pixel() } } impl HasDimension for (u32, u32) { fn dim(&self) -> (u32, u32) { *self } } /// The trait that describes a size pub trait SizeDesc { fn in_pixels<T: HasDimension>(&self, parent: &T) -> i32; } /*impl<T: Into<i32> + Clone> SizeDesc for T { fn in_pixels<D: HasDimension>(&self, _parent: &D) -> i32 { self.clone().into() } }*/ impl SizeDesc for i32 { fn in_pixels<D: HasDimension>(&self, _parent: &D) -> i32 { *self } } impl SizeDesc for u32 { fn in_pixels<D: HasDimension>(&self, _parent: &D) -> i32 { *self as i32 } } pub enum RelativeSize { Height(f64), Width(f64), Smaller(f64), } impl RelativeSize { pub fn min(self, min_sz: i32) -> RelativeSizeWithBound { RelativeSizeWithBound { size: self, min: Some(min_sz), max: None, } } pub fn max(self, max_sz: i32) -> RelativeSizeWithBound { RelativeSizeWithBound { size: self, max: Some(max_sz), min: None, } } } impl SizeDesc for RelativeSize { fn in_pixels<D: HasDimension>(&self, parent: &D) -> i32 { let (w, h) = parent.dim(); match self { RelativeSize::Width(p) => *p * f64::from(w), RelativeSize::Height(p) => *p * f64::from(h), RelativeSize::Smaller(p) => *p * f64::from(w.min(h)), } .round() as i32 } } pub trait AsRelative: Into<f64> { fn percent_width(self) -> RelativeSize { RelativeSize::Width(self.into() / 100.0) } fn percent_height(self) -> RelativeSize { RelativeSize::Height(self.into() / 100.0) } fn percent(self) -> RelativeSize { RelativeSize::Smaller(self.into() / 100.0) } } impl<T: Into<f64>> AsRelative for T {} pub struct RelativeSizeWithBound { size: RelativeSize, min: Option<i32>, max: Option<i32>, } impl RelativeSizeWithBound { pub fn min(mut self, min_sz: i32) -> RelativeSizeWithBound { self.min = Some(min_sz); self } pub fn max(mut self, max_sz: i32) -> RelativeSizeWithBound { self.max = Some(max_sz); self } } impl SizeDesc for RelativeSizeWithBound { fn in_pixels<D: HasDimension>(&self, parent: &D) -> i32 { let size = self.size.in_pixels(parent); let size_lower_capped = self.min.map_or(size, |x| x.max(size)); self.max.map_or(size_lower_capped, |x| x.min(size)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_relative_size() { let size = (10).percent_height(); assert_eq!(size.in_pixels(&(100, 200)), 20); let size = (10).percent_width(); assert_eq!(size.in_pixels(&(100, 200)), 10); let size = (-10).percent_width(); assert_eq!(size.in_pixels(&(100, 200)), -10); let size = (10).percent_width().min(30); assert_eq!(size.in_pixels(&(100, 200)), 30); assert_eq!(size.in_pixels(&(400, 200)), 40); let size = (10).percent(); assert_eq!(size.in_pixels(&(100, 200)), 10); assert_eq!(size.in_pixels(&(400, 200)), 20); } }
type Result<T> = std::result::Result<T, String>; fn main() { let result = iter_result(); println!("{}", result.unwrap()); } fn iter_result() -> Result<i32> { (0..5).map(|x| if x > 2 { Err("greater than 2") } else { Ok(1) }); Ok(1) }
use super::{ChatServer, ClientPacket}; use crate::chat::{InternalId, SuccessReason}; use crate::error::*; use log::*; use uuid::Uuid; impl ChatServer { pub(super) fn ban_user(&mut self, user_id: InternalId, to_ban: &Uuid) { self.handle_user(user_id, to_ban, true); } pub(super) fn unban_user(&mut self, user_id: InternalId, to_unban: &Uuid) { self.handle_user(user_id, to_unban, false); } fn handle_user(&mut self, user_id: InternalId, receiver: &Uuid, ban: bool) { let session = self .connections .get(&user_id) .expect("could not find connection"); if let Some(info) = &session.user { if !self.moderation.is_moderator(&info.uuid) { info!("`{}` tried to (un-)ban user without permission", user_id); session .addr .do_send(ClientPacket::Error { message: ClientError::NotPermitted, }) .ok(); return; } let res = if ban { self.moderation.ban(receiver) } else { self.moderation.unban(receiver) }; match res { Ok(()) => { let reason = if ban { info!("User `{}` banned.", receiver); SuccessReason::Ban } else { info!("User `{}` unbanned.", receiver); SuccessReason::Unban }; let _ = session.addr.do_send(ClientPacket::Success { reason }); } Err(Error::AxoChat { source }) => { info!("Could not (un-)ban user `{}`: {}", receiver, source); session .addr .do_send(ClientPacket::Error { message: source }) .ok(); } Err(err) => { info!("Could not (un-)ban user `{}`: {}", receiver, err); session .addr .do_send(ClientPacket::Error { message: ClientError::Internal, }) .ok(); } } } else { info!("`{}` is not logged in.", user_id); session .addr .do_send(ClientPacket::Error { message: ClientError::NotLoggedIn, }) .ok(); return; } } }
use std::os::raw::c_char; use bioenpro4to_channel_manager::channels::ChannelInfo as ChInfo; use std::ffi::{CString, CStr}; use anyhow::Result; use bioenpro4to_channel_manager::utils::{create_encryption_key, create_encryption_nonce}; #[repr(C)] pub struct ChannelInfo{ pub channel_id: *const c_char, pub announce_id: *const c_char } impl ChannelInfo{ pub fn from_ch_info(ch_info: ChInfo) -> *const ChannelInfo{ let channel_id = CString::new(ch_info.channel_id()).unwrap().into_raw(); let announce_id = CString::new(ch_info.announce_id()).unwrap().into_raw(); new_channel_info(channel_id, announce_id) } pub unsafe fn to_ch_info(&self) -> Result<ChInfo>{ let channel_id = CStr::from_ptr(self.channel_id).to_str()?; let announce_id = CStr::from_ptr(self.announce_id).to_str()?; Ok(ChInfo::new(channel_id.to_string(), announce_id.to_string())) } } #[no_mangle] pub extern "C" fn new_channel_info(channel_id: *const c_char, announce_id: *const c_char) -> *const ChannelInfo{ let ch_info = ChannelInfo{channel_id, announce_id}; Box::into_raw(Box::new(ch_info)) } #[no_mangle] pub unsafe extern "C" fn drop_channel_info(info: *mut ChannelInfo){ Box::from_raw(info); } #[repr(C)] pub struct KeyNonce{ pub key: [u8; 32], pub nonce: [u8; 24], } #[no_mangle] pub extern "C" fn new_encryption_key_nonce(key: *const c_char, nonce: *const c_char) -> *const KeyNonce{ unsafe { let k = CStr::from_ptr(key).to_str().unwrap(); let n = CStr::from_ptr(nonce).to_str().unwrap(); let k = create_encryption_key(k); let n = create_encryption_nonce(n); Box::into_raw(Box::new(KeyNonce{key: k, nonce: n})) } } #[no_mangle] pub unsafe extern "C" fn drop_key_nonce(kn: *const KeyNonce) { Box::from_raw(kn as *mut KeyNonce); } #[repr(C)] pub struct RawPacket{ pub public: *const u8, pub p_len: usize, pub masked: *const u8, pub m_len: usize } impl RawPacket{ pub unsafe fn public(&self) -> Vec<u8>{ let p = std::slice::from_raw_parts(self.public, self.p_len); p.to_vec() } pub unsafe fn masked(&self) -> Vec<u8>{ let m = std::slice::from_raw_parts(self.masked, self.m_len); m.to_vec() } } #[no_mangle] pub extern "C" fn new_raw_packet(public: *mut u8, p_len: u64, masked: *mut u8, m_len: u64) -> *const RawPacket{ let p_len = p_len as usize; let m_len = m_len as usize; let packet = RawPacket{public, p_len, masked, m_len}; Box::into_raw(Box::new(packet)) } #[no_mangle] pub unsafe extern "C" fn drop_raw_packet(packet: *mut RawPacket){ Box::from_raw(packet); } #[no_mangle] pub unsafe extern "C" fn drop_str(s: *const c_char) { CString::from_raw(s as *mut c_char); }
mod info; mod validate; use crate::info::Info; use crate::validate::Validate; use crossterm::style::Stylize; use solp::Consume; extern crate humantime; extern crate solp; #[macro_use] extern crate prettytable; extern crate crossterm; pub trait ConsumeDisplay: Consume + std::fmt::Display { fn as_consume(&mut self) -> &mut dyn Consume; } // Trait casting code begin impl ConsumeDisplay for Info { fn as_consume(&mut self) -> &mut dyn Consume { self } } impl ConsumeDisplay for Validate { fn as_consume(&mut self) -> &mut dyn Consume { self } } // Trait casting code end // Factory method #[must_use] pub fn new_consumer(only_validate: bool, only_problems: bool) -> Box<dyn ConsumeDisplay> { if only_validate { Validate::new_box(only_problems) } else { Info::new_box() } } fn err(path: &str) { eprintln!("Error parsing {} solution", path.red()); }
// This file is part of Substrate. // Copyright (C) 2019-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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. //! # Running //! Running this fuzzer can be done with `cargo hfuzz run per_thing_rational`. `honggfuzz` CLI //! options can be used by setting `HFUZZ_RUN_ARGS`, such as `-n 4` to use 4 threads. //! //! # Debugging a panic //! Once a panic is found, it can be debugged with //! `cargo hfuzz run-debug per_thing_rational hfuzz_workspace/per_thing_rational/*.fuzz`. use honggfuzz::fuzz; use sp_arithmetic::{traits::SaturatedConversion, PerThing, PerU16, Perbill, Percent, Perquintill}; fn main() { loop { fuzz!(|data: ((u16, u16), (u32, u32), (u64, u64))| { let (u16_pair, u32_pair, u64_pair) = data; // peru16 let (smaller, bigger) = (u16_pair.0.min(u16_pair.1), u16_pair.0.max(u16_pair.1)); let ratio = PerU16::from_rational_approximation(smaller, bigger); assert_per_thing_equal_error( ratio, PerU16::from_fraction(smaller as f64 / bigger.max(1) as f64), 1, ); let (smaller, bigger) = (u32_pair.0.min(u32_pair.1), u32_pair.0.max(u32_pair.1)); let ratio = PerU16::from_rational_approximation(smaller, bigger); assert_per_thing_equal_error( ratio, PerU16::from_fraction(smaller as f64 / bigger.max(1) as f64), 1, ); let (smaller, bigger) = (u64_pair.0.min(u64_pair.1), u64_pair.0.max(u64_pair.1)); let ratio = PerU16::from_rational_approximation(smaller, bigger); assert_per_thing_equal_error( ratio, PerU16::from_fraction(smaller as f64 / bigger.max(1) as f64), 1, ); // percent let (smaller, bigger) = (u16_pair.0.min(u16_pair.1), u16_pair.0.max(u16_pair.1)); let ratio = Percent::from_rational_approximation(smaller, bigger); assert_per_thing_equal_error( ratio, Percent::from_fraction(smaller as f64 / bigger.max(1) as f64), 1, ); let (smaller, bigger) = (u32_pair.0.min(u32_pair.1), u32_pair.0.max(u32_pair.1)); let ratio = Percent::from_rational_approximation(smaller, bigger); assert_per_thing_equal_error( ratio, Percent::from_fraction(smaller as f64 / bigger.max(1) as f64), 1, ); let (smaller, bigger) = (u64_pair.0.min(u64_pair.1), u64_pair.0.max(u64_pair.1)); let ratio = Percent::from_rational_approximation(smaller, bigger); assert_per_thing_equal_error( ratio, Percent::from_fraction(smaller as f64 / bigger.max(1) as f64), 1, ); // perbill let (smaller, bigger) = (u32_pair.0.min(u32_pair.1), u32_pair.0.max(u32_pair.1)); let ratio = Perbill::from_rational_approximation(smaller, bigger); assert_per_thing_equal_error( ratio, Perbill::from_fraction(smaller as f64 / bigger.max(1) as f64), 100, ); let (smaller, bigger) = (u64_pair.0.min(u64_pair.1), u64_pair.0.max(u64_pair.1)); let ratio = Perbill::from_rational_approximation(smaller, bigger); assert_per_thing_equal_error( ratio, Perbill::from_fraction(smaller as f64 / bigger.max(1) as f64), 100, ); // perquintillion let (smaller, bigger) = (u64_pair.0.min(u64_pair.1), u64_pair.0.max(u64_pair.1)); let ratio = Perquintill::from_rational_approximation(smaller, bigger); assert_per_thing_equal_error( ratio, Perquintill::from_fraction(smaller as f64 / bigger.max(1) as f64), 1000, ); }) } } fn assert_per_thing_equal_error<P: PerThing>(a: P, b: P, err: u128) { let a_abs = a.deconstruct().saturated_into::<u128>(); let b_abs = b.deconstruct().saturated_into::<u128>(); let diff = a_abs.max(b_abs) - a_abs.min(b_abs); assert!(diff <= err, "{:?} !~ {:?}", a, b); }
//! Implements `StdSearchNode`. use std::cmp::min; use std::cell::UnsafeCell; use std::hash::Hasher; use std::collections::hash_map::DefaultHasher; use uci::{SetOption, OptionDescription}; use board::{Board, IllegalBoard}; use value::*; use depth::*; use qsearch::{Qsearch, QsearchParams, QsearchResult}; use moves::{Move, MoveDigest, AddMove}; use move_generator::MoveGenerator; use search_node::SearchNode; use utils::{ZobristArrays, parse_fen}; /// Contains information about a position. #[derive(Clone, Copy)] struct PositionInfo { /// The number of half-moves since the last piece capture or pawn /// advance. (We do not allow `halfmove_clock` to become greater /// than 99.) halfmove_clock: u8, /// The last played move. last_move: Move, } /// Implements the `SearchNode` trait. pub struct StdSearchNode<T: Qsearch> { zobrist: &'static ZobristArrays, position: UnsafeCell<T::MoveGenerator>, /// Information needed so as to be able to undo the played moves. state_stack: Vec<PositionInfo>, /// The count of half-moves since the beginning of the game. halfmove_count: u16, /// `true` if the position is deemed as a draw by repetition or /// because 50 moves have been played without capturing a piece or /// advancing a pawn. repeated_or_rule50: bool, /// The hash value for the underlying `Board` instance. board_hash: u64, /// A list of hash values for the `Board` instances that had /// occurred during the game. This is needed so as to be able to /// detect repeated positions. encountered_boards: Vec<u64>, /// A collective hash value for the set of boards that had /// occurred at least twice before the root position (the earliest /// position in `state_stack`), and can still be reached by /// playing moves from the root position. An empty set has a hash /// of `0`. We use this value when we generate position's hash. repeated_boards_hash: u64, } impl<T: Qsearch> SearchNode for StdSearchNode<T> { type Evaluator = <<T as Qsearch>::MoveGenerator as MoveGenerator>::Evaluator; type QsearchResult = T::QsearchResult; fn from_history(fen: &str, moves: &mut Iterator<Item = &str>) -> Result<Self, IllegalBoard> { let mut p: StdSearchNode<T> = try!(StdSearchNode::from_fen(fen)); let mut move_list = Vec::new(); 'played_moves: for played_move in moves { move_list.clear(); p.position().generate_all(&mut move_list); for m in move_list.iter() { if played_move == m.notation() { if p.do_move(*m) { continue 'played_moves; } break; } } return Err(IllegalBoard); } p.declare_as_root(); Ok(p) } #[inline] fn hash(&self) -> u64 { // Notes: // // 1. Two positions that differ in their sets of previously // repeated, still reachable boards will have different // hashes. // // 2. Two positions that differ only in their number of played // moves without capturing piece or advancing a pawn will // have equal hashes, as long as they both are far from the // rule-50 limit. if self.repeated_or_rule50 { // All repeated and rule-50 positions are a draw, so for // practical purposes they can be considered to be the // exact same position, and therefore we can generate the // same hash value for all of them. This has the important // practical advantage that we get two separate records in // the transposition table for the first and the second // occurrence of the same position. (The second occurrence // being deemed as a draw.) 1 } else { let hash = if self.root_is_reachable() { // If the repeated positions that occured before the // root postition are still reachable, we blend their // collective hash into current position's hash. self.board_hash ^ self.repeated_boards_hash } else { self.board_hash }; let halfmove_clock = self.state().halfmove_clock; if halfmove_clock >= 70 { // If `halfmove_clock` is close to rule-50, we blend // it into the returned hash. hash ^ self.zobrist.halfmove_clock[halfmove_clock as usize] } else { hash } } } #[inline] fn board(&self) -> &Board { self.position().board() } #[inline] fn halfmove_clock(&self) -> u8 { self.state().halfmove_clock } #[inline] fn fullmove_number(&self) -> u16 { 1 + (self.halfmove_count >> 1) } #[inline] fn is_check(&self) -> bool { self.position().is_check() } #[inline] fn evaluator(&self) -> &Self::Evaluator { self.position().evaluator() } #[inline] fn evaluate_final(&self) -> Value { if self.repeated_or_rule50 || !self.is_check() { 0 } else { VALUE_MIN } } #[inline] fn evaluate_move(&self, m: Move) -> Value { self.position().evaluate_move(m) } #[inline] fn qsearch(&self, depth: Depth, lower_bound: Value, upper_bound: Value, static_eval: Value) -> Self::QsearchResult { debug_assert!(DEPTH_MIN <= depth && depth <= 0); debug_assert!(lower_bound >= VALUE_MIN); debug_assert!(upper_bound <= VALUE_MAX); debug_assert!(lower_bound < upper_bound); if self.repeated_or_rule50 { Self::QsearchResult::new(0, 0) } else { T::qsearch(QsearchParams { position: unsafe { self.position_mut() }, depth: depth, lower_bound: lower_bound, upper_bound: upper_bound, static_eval: static_eval, }) } } #[inline] fn generate_moves<U: AddMove>(&self, moves: &mut U) { if !self.repeated_or_rule50 { self.position().generate_all(moves); } } #[inline] fn try_move_digest(&self, move_digest: MoveDigest) -> Option<Move> { if self.repeated_or_rule50 { None } else { self.position().try_move_digest(move_digest) } } #[inline] fn null_move(&self) -> Move { self.position().null_move() } #[inline] fn last_move(&self) -> Move { self.state().last_move } fn do_move(&mut self, m: Move) -> bool { if self.repeated_or_rule50 && m.is_null() { // This is a final position -- null moves are not // allowed. We must still allow other moves though, // because `from_history` should be able to call `do_move` // even in final positions. return false; } if let Some(h) = unsafe { self.position_mut().do_move(m) } { let halfmove_clock = if m.is_pawn_advance_or_capure() { 0 } else { match self.state().halfmove_clock { x if x < 99 => x + 1, _ => { if !self.is_checkmate() { self.repeated_or_rule50 = true; } 99 } } }; self.halfmove_count += 1; self.encountered_boards.push(self.board_hash); self.board_hash ^= h; debug_assert!(halfmove_clock <= 99); debug_assert!(self.encountered_boards.len() >= halfmove_clock as usize); // Figure out if the new position is repeated (a draw). if halfmove_clock >= 4 { let boards = &self.encountered_boards; let last_irrev = (boards.len() - (halfmove_clock as usize)) as isize; unsafe { let mut i = (boards.len() - 4) as isize; while i >= last_irrev { if self.board_hash == *boards.get_unchecked(i as usize) { self.repeated_or_rule50 = true; break; } i -= 2; } } } self.state_stack .push(PositionInfo { halfmove_clock: halfmove_clock, last_move: m, }); return true; } false } #[inline] fn undo_last_move(&mut self) { debug_assert!(self.state_stack.len() > 1); unsafe { self.position_mut().undo_move(self.state().last_move); } self.halfmove_count -= 1; self.board_hash = self.encountered_boards.pop().unwrap(); self.repeated_or_rule50 = false; self.state_stack.pop(); } } impl<T: Qsearch> Clone for StdSearchNode<T> { fn clone(&self) -> Self { StdSearchNode { position: UnsafeCell::new(self.position().clone()), encountered_boards: self.encountered_boards.clone(), state_stack: self.state_stack.clone(), ..*self } } } impl<T: Qsearch> SetOption for StdSearchNode<T> { fn options() -> Vec<(&'static str, OptionDescription)> { T::options() } fn set_option(name: &str, value: &str) { T::set_option(name, value) } } impl<T: Qsearch> StdSearchNode<T> { /// Creates a new instance from Forsyth–Edwards Notation (FEN). pub fn from_fen(fen: &str) -> Result<StdSearchNode<T>, IllegalBoard> { let (board, halfmove_clock, fullmove_number) = try!(parse_fen(fen)); let gen = try!(T::MoveGenerator::from_board(board)); Ok(StdSearchNode { zobrist: ZobristArrays::get(), halfmove_count: ((fullmove_number - 1) << 1) + gen.board().to_move as u16, board_hash: gen.hash(), position: UnsafeCell::new(gen), repeated_or_rule50: false, repeated_boards_hash: 0, encountered_boards: vec![0; halfmove_clock as usize], state_stack: vec![PositionInfo { halfmove_clock: min(halfmove_clock, 99), last_move: Move::invalid(), }], }) } /// Forgets the previous playing history, preserves only the set /// of previously repeated, still reachable boards. fn declare_as_root(&mut self) { let state = *self.state(); // The root position is never deemed as a draw due to // repetition or rule-50. self.repeated_or_rule50 = false; // Calculate the set of previously repeated, still reachable boards. let repeated_boards = { // Forget all encountered boards before the last irreversible move. let last_irrev = self.encountered_boards.len() - state.halfmove_clock as usize; self.encountered_boards = self.encountered_boards.split_off(last_irrev); self.encountered_boards.reserve(32); // Forget all encountered boards that occurred only once. set_non_repeated_values(&mut self.encountered_boards, 0) }; // Calculate a collective hash value representing the set of // previously repeated, still reachable boards. (We will use // this value when calculating position's hash.) self.repeated_boards_hash = if repeated_boards.is_empty() { 0 } else { let mut hasher = DefaultHasher::new(); for x in repeated_boards { hasher.write_u64(x); } hasher.finish() }; // Forget all played moves. self.state_stack = vec![state]; self.state_stack.reserve(32); } /// Returns if the root position (the earliest in `state_stack`) /// can be reached by playing moves from the current position. #[inline] fn root_is_reachable(&self) -> bool { self.encountered_boards.len() <= self.state().halfmove_clock as usize } /// Returns if the side to move is checkmated. fn is_checkmate(&self) -> bool { thread_local!( static MOVE_LIST: UnsafeCell<Vec<Move>> = UnsafeCell::new(Vec::new()) ); self.is_check() && MOVE_LIST.with(|s| unsafe { // Check if there are no legal moves. let position = self.position_mut(); let move_list = &mut *s.get(); let mut no_legal_moves = true; position.generate_all(move_list); for m in move_list.iter() { if position.do_move(*m).is_some() { position.undo_move(*m); no_legal_moves = false; break; } } move_list.clear(); no_legal_moves }) } #[inline] fn state(&self) -> &PositionInfo { self.state_stack.last().unwrap() } #[inline] fn position(&self) -> &T::MoveGenerator { unsafe { &*self.position.get() } } #[inline] unsafe fn position_mut(&self) -> &mut T::MoveGenerator { &mut *self.position.get() } } /// A helper function. It sets all unique (non-repeated) values in /// `slice` to `value`, and returns a sorted vector containing a /// single value for each duplicated value in `slice`. fn set_non_repeated_values<T>(slice: &mut [T], value: T) -> Vec<T> where T: Copy + Ord { let mut repeated = vec![]; let mut v = slice.to_vec(); v.sort(); let mut prev = value; for curr in v { if curr != value && curr == prev { repeated.push(curr); } prev = curr; } repeated.dedup(); for x in slice.iter_mut() { if repeated.binary_search(x).is_err() { *x = value; } } repeated } #[cfg(test)] mod tests { use utils::MoveStack; use value::*; use search_node::*; use evaluator::*; use qsearch::*; use moves::Move; use stock::{StdSearchNode, StdQsearch, StdMoveGenerator, SimpleEvaluator}; type P = StdSearchNode<StdQsearch<StdMoveGenerator<SimpleEvaluator>>>; #[test] fn is_legal() { assert!(P::from_fen("8/8/8/8/8/8/8/8 w - - 0 1").is_err()); assert!(P::from_fen("8/8/8/8/8/8/8/7K w - - 0 1").is_err()); assert!(P::from_fen("k7/8/8/8/8/8/8/7K w - - 0 1").is_ok()); assert!(P::from_fen("k7/8/8/8/8/8/8/6KK w - - 0 1").is_err()); assert!(P::from_fen("k7/pppppppp/p7/8/8/8/8/7K w - - 0 1").is_err()); assert!(P::from_fen("k7/8/8/8/8/7P/PPPPPPPP/7K w - - 0 1").is_err()); assert!(P::from_fen("k7/pppppppp/8/8/8/8/PPPPPPPP/7K w - - 0 1").is_ok()); assert!(P::from_fen("k7/1P6/8/8/8/8/8/7K w - - 0 1").is_err()); assert!(P::from_fen("k7/1B6/8/8/8/8/8/7K w - - 0 1").is_err()); assert!(P::from_fen("k7/1N6/8/8/8/8/8/7K w - - 0 1").is_ok()); assert!(P::from_fen("k3P3/8/8/8/8/8/8/7K w - - 0 1").is_err()); assert!(P::from_fen("k3p3/8/8/8/8/8/8/7K w - - 0 1").is_err()); assert!(P::from_fen("k7/8/8/8/8/8/8/pP5K w - - 0 1").is_err()); assert!(P::from_fen("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1").is_ok()); assert!(P::from_fen("r3k2r/8/8/8/8/8/8/R3K2B w KQkq - 0 1").is_err()); assert!(P::from_fen("r3k2r/8/8/8/8/8/8/R3K3 w KQkq - 0 1").is_err()); assert!(P::from_fen("r3k2r/8/8/8/8/8/8/R3K3 w KQkq - 0 1").is_err()); assert!(P::from_fen("r3k2r/8/8/8/8/8/8/R3K3 w Qkq - 0 1").is_ok()); assert!(P::from_fen("r2k3r/8/8/8/8/8/8/R3K3 w Qkq - 0 1").is_err()); assert!(P::from_fen("r2k3r/8/8/8/8/8/8/R3K3 w Qk - 0 1").is_err()); assert!(P::from_fen("r2k3r/8/8/8/8/8/8/R3K3 w Q - 0 1").is_ok()); assert!(P::from_fen("k7/8/8/8/7P/8/8/7K w - h3 0 1").is_err()); assert!(P::from_fen("k7/8/8/8/7P/8/8/7K b - h3 0 1").is_ok()); assert!(P::from_fen("k7/8/8/7P/8/8/8/7K b - h4 0 1").is_err()); assert!(P::from_fen("k7/8/8/8/7P/7P/8/7K b - h3 0 1").is_err()); assert!(P::from_fen("k7/8/8/8/7P/8/7P/7K b - h3 0 1").is_err()); assert!(P::from_fen("k7/8/8/8/6P1/7P/8/7K b - h3 0 1").is_err()); assert!(P::from_fen("8/8/8/6k1/7P/8/8/7K b - h3 0 1").is_ok()); assert!(P::from_fen("8/8/8/6k1/7P/8/8/6RK b - h3 0 1").is_err()); assert!(P::from_fen("8/8/8/6k1/3P4/8/8/2B4K b - d3 0 1").is_ok()); assert!(P::from_fen("8/8/8/6k1/7P/4B3/8/7K b - h3 0 1").is_err()); assert!(P::from_fen("8/8/8/6k1/7P/8/8/7K b - h3 0 0").is_err()); } #[test] fn evaluate_fullmove_number() { let mut p = P::from_fen("krq5/p7/8/8/8/8/8/KRQ5 w - - 6 31") .ok() .unwrap(); assert_eq!(p.last_move(), Move::invalid()); assert_eq!(p.fullmove_number(), 31); let m = p.legal_moves()[0]; p.do_move(m); assert_eq!(p.last_move(), m); assert_eq!(p.fullmove_number(), 31); p.undo_last_move(); assert_eq!(p.fullmove_number(), 31); let mut p = P::from_fen("krq5/p7/8/8/8/8/8/KRQ5 b - - 6 31") .ok() .unwrap(); assert_eq!(p.fullmove_number(), 31); let m = p.legal_moves()[0]; p.do_move(m); assert_eq!(p.fullmove_number(), 32); p.undo_last_move(); assert_eq!(p.fullmove_number(), 31); } #[test] fn evaluate_static() { let p = P::from_fen("krq5/p7/8/8/8/8/8/KRQ5 w - - 0 1") .ok() .unwrap(); assert!(p.evaluator().evaluate(p.board()) < -20); } #[test] fn evaluate_move() { let mut s = MoveStack::new(); let p = P::from_fen("8/4P1kP/8/8/8/7p/8/7K w - - 0 1") .ok() .unwrap(); p.generate_moves(&mut s); while let Some(m) = s.pop() { if m.notation() == "e7e8q" { assert!(p.evaluate_move(m) > 0); } if m.notation() == "e7e8r" { assert!(p.evaluate_move(m) > 0); } if m.notation() == "h7h8r" { assert!(p.evaluate_move(m) < 0); } if m.notation() == "h1h2" { assert_eq!(p.evaluate_move(m), 0); } if m.notation() == "h1g2" { assert!(p.evaluate_move(m) < -5000); } } let p = P::from_fen("6k1/1P6/8/4b3/8/8/8/1R3K2 w - - 0 1") .ok() .unwrap(); p.generate_moves(&mut s); while let Some(m) = s.pop() { if m.notation() == "b7b8q" { assert!(p.evaluate_move(m) > 0); } if m.notation() == "b7b8k" { assert!(p.evaluate_move(m) > 0); } } let p = P::from_fen("5r2/8/8/4q1p1/3P4/k3P1P1/P2b1R1B/K4R2 w - - 0 1") .ok() .unwrap(); p.generate_moves(&mut s); while let Some(m) = s.pop() { if m.notation() == "f2f4" { assert!(p.evaluate_move(m) <= -400); } if m.notation() == "e3e4" { assert_eq!(p.evaluate_move(m), -100); } if m.notation() == "g3g4" { assert_eq!(p.evaluate_move(m), 0); } if m.notation() == "f1e1" { assert_eq!(p.evaluate_move(m), -500); } if m.notation() == "f1d1" { assert_eq!(p.evaluate_move(m), 0); } } let p = P::from_fen("5r2/8/8/4q1p1/3P4/k3P1P1/P2b1R1B/K4R2 b - - 0 1") .ok() .unwrap(); p.generate_moves(&mut s); while let Some(m) = s.pop() { if m.notation() == "e5e3" { assert_eq!(p.evaluate_move(m), 100); } if m.notation() == "e5d4" { assert_eq!(p.evaluate_move(m), -875); } if m.notation() == "a3a2" { assert_eq!(p.evaluate_move(m), -9900); } } let p = P::from_fen("8/8/8/8/8/8/2pkpKp1/8 b - - 0 1") .ok() .unwrap(); p.generate_moves(&mut s); while let Some(m) = s.pop() { if m.notation() == "c2c1r" { assert_eq!(p.evaluate_move(m), 400); } if m.notation() == "c2c1n" { assert_eq!(p.evaluate_move(m), 225); } if m.notation() == "e2e1q" { assert_eq!(p.evaluate_move(m), 875); } if m.notation() == "e2e1n" { assert_eq!(p.evaluate_move(m), 225); } if m.notation() == "g2g1q" { assert_eq!(p.evaluate_move(m), -100); } if m.notation() == "g2g1r" { assert_eq!(p.evaluate_move(m), -100); } } assert_eq!(p.evaluate_move(p.null_move()), 0); } #[test] fn repeated_root_position() { let moves: Vec<&str> = vec!["g4f3", "g1f1", "f3g4", "f1g1", "g4f3", "g1f1", "f3g4", "f1g1"]; let p = P::from_history("8/8/8/8/6k1/6P1/8/6K1 b - - 0 1", &mut moves.into_iter()) .ok() .unwrap(); let mut v = MoveStack::new(); p.generate_moves(&mut v); assert!(v.list().len() != 0); } #[test] fn set_non_repeated_values() { use super::set_non_repeated_values; let mut v = vec![0, 1, 2, 7, 9, 0, 0, 1, 2]; let dups = set_non_repeated_values(&mut v, 0); assert_eq!(v, vec![0, 1, 2, 0, 0, 0, 0, 1, 2]); assert_eq!(dups, vec![1, 2]); } #[test] fn qsearch() { let p = P::from_fen("8/8/8/8/8/6qk/7P/7K b - - 0 1") .ok() .unwrap(); assert_eq!(p.qsearch(0, -10000, 10000, VALUE_UNKNOWN) .searched_nodes(), 1); } #[test] fn is_repeated() { let mut p = P::from_fen("8/5p1b/5Pp1/6P1/6p1/3p1pPk/3PpP2/4B2K w - - 0 1") .ok() .unwrap(); let mut v = MoveStack::new(); let mut count = 0; for _ in 0..100 { p.generate_moves(&mut v); while let Some(m) = v.pop() { if p.do_move(m) { count += 1; v.clear_all(); break; } } } assert_eq!(count, 4); } #[test] fn is_checkmate() { let p = P::from_fen("8/8/8/8/8/7K/8/5R1k b - - 0 1") .ok() .unwrap(); assert!(p.is_checkmate()); let p = P::from_fen("8/8/8/8/8/7K/6p1/5R1k b - - 0 1") .ok() .unwrap(); assert!(!p.is_checkmate()); let p = P::from_fen("8/8/8/8/8/7K/8/5N1k b - - 0 1") .ok() .unwrap(); assert!(!p.is_checkmate()); } #[test] fn repeated_boards_hash() { let p1 = P::from_fen("8/8/8/8/8/7k/8/7K w - - 0 1").ok().unwrap(); let moves: Vec<&str> = vec![]; let p2 = P::from_history("8/8/8/8/8/7k/8/7K w - - 0 1", &mut moves.into_iter()) .ok() .unwrap(); assert_eq!(p1.board_hash, p2.board_hash); assert_eq!(p1.hash(), p2.hash()); let moves: Vec<&str> = vec!["f1g1", "f3g3", "g1h1", "g3h3"]; let p2 = P::from_history("8/8/8/8/8/5k2/8/5K2 w - - 0 1", &mut moves.into_iter()) .ok() .unwrap(); assert_eq!(p1.board_hash, p2.board_hash); assert_eq!(p1.hash(), p2.hash()); let moves: Vec<&str> = vec!["f1g1", "f3g3", "g1f1", "g3f3", "f1g1", "f3g3", "g1h1", "g3h3"]; let p3 = P::from_history("8/8/8/8/8/5k2/8/5K2 w - - 0 1", &mut moves.into_iter()) .ok() .unwrap(); assert_eq!(p1.board_hash, p2.board_hash); assert!(p1.hash() != p3.hash()); } }
use franklin_crypto::plonk::circuit::allocated_num::Num; use franklin_crypto::bellman::pairing::Engine; use franklin_crypto::bellman::plonk::better_better_cs::cs::ConstraintSystem; use super::cipher_tools::{ CipherParams, mds::{MdsMatrix, construct_mds_matrix, construct_inverse_matrix, dot_product, add_vectors, sub_vectors}, sboxes::{QuinticSBox, QuinticInverseSBox} }; use std::marker::PhantomData; pub struct ReadyCipherParams< E: Engine, const SIZE: usize, const RNUMBER: usize> { pub matrix: MdsMatrix<E, SIZE>, pub inv_matrix: MdsMatrix<E, SIZE>, pub sbox1: QuinticSBox<E, SIZE>, pub sbox2: QuinticInverseSBox<E, SIZE>, pub round_constants: [[Num<E>; SIZE]; RNUMBER] } pub fn construct_ready_params< E: Engine, CS: ConstraintSystem<E>, const SIZE: usize, const RNUMBER: usize>( cs: &mut CS, params: &mut CipherParams<E, SIZE, RNUMBER> )-> ReadyCipherParams<E, SIZE, RNUMBER>{ let matrix = construct_mds_matrix::<E, CS, SIZE>(cs, &mut params.vect_for_matrix); let inv_matrix = construct_inverse_matrix::<E, CS, SIZE>(cs, &matrix).unwrap(); let sbox1 = QuinticSBox::<E, SIZE>{ _marker: PhantomData::<E>::default() }; let sbox2 = QuinticInverseSBox::<E, SIZE>{ _marker: PhantomData::<E>::default() }; let mut round_constants = [[Num::<E>::zero(); SIZE]; RNUMBER]; for i in 0..RNUMBER { for j in 0..SIZE { round_constants[i][j] = Num::alloc(cs, Some(params.round_constants[i][j])).unwrap(); } } ReadyCipherParams { matrix, inv_matrix, sbox1, sbox2, round_constants } } pub fn rescue_encryption< E: Engine, CS: ConstraintSystem<E>, const SIZE: usize, const RNUMBER: usize>( cs: &mut CS, params: &ReadyCipherParams<E, SIZE, RNUMBER>, key: &[Num<E>; SIZE], plaintext: &[Num<E>; SIZE])->[Num<E>; SIZE]{ let subkeys = construct_subkeys(cs, &params, *key); let mut ciphertext = add_vectors(cs, &plaintext, &subkeys[0]); let mut helptext = ciphertext; let matrix = &params.matrix; for i in 1..RNUMBER { for j in 0..SIZE { helptext[j] = dot_product(cs, &ciphertext, &matrix.get_row(j)); } ciphertext = helptext; if i%2 == 1 { params.sbox1.apply(cs, &mut ciphertext); } else { params.sbox2.apply(cs, &mut ciphertext); } ciphertext = add_vectors(cs, &ciphertext, &subkeys[i]); } ciphertext } pub fn rescue_decryption< E: Engine, CS: ConstraintSystem<E>, const SIZE: usize, const RNUMBER: usize>( cs: &mut CS, params: &ReadyCipherParams<E, SIZE, RNUMBER>, key: &[Num<E>; SIZE], ciphertext: &[Num<E>; SIZE])->[Num<E>; SIZE]{ let subkeys = construct_subkeys(cs, &params, *key); let mut plaintext = sub_vectors(cs, &ciphertext, &subkeys[RNUMBER-1]); let mut helptext = plaintext; let matrix = &params.inv_matrix; for i in 1..RNUMBER { if i%2 == 1 { params.sbox1.apply(cs, &mut plaintext); } else { params.sbox2.apply(cs, &mut plaintext); } for j in 0..SIZE { helptext[j] = dot_product(cs, &plaintext, &matrix.get_row(j)); } plaintext = helptext; plaintext = sub_vectors(cs, &plaintext, &subkeys[RNUMBER-i-1]); } plaintext } fn construct_subkeys< E: Engine, CS: ConstraintSystem<E>, const SIZE: usize, const RNUMBER: usize>( cs: &mut CS, params: &ReadyCipherParams<E, SIZE, RNUMBER>, key: [Num<E>; SIZE] )->[[Num<E>; SIZE]; RNUMBER]{ let mut subkeys = [[Num::<E>::zero(); SIZE]; RNUMBER]; let raconsts = params.round_constants; let matrix = &params.matrix; subkeys[0] = add_vectors(cs, &key, &raconsts[0]); for i in 1..RNUMBER { for j in 0..SIZE { subkeys[i][j] = dot_product(cs, &subkeys[i-1], &matrix.get_row(j)); } if i%2 == 1 { params.sbox1.apply(cs, &mut subkeys[i]); } else { params.sbox2.apply(cs, &mut subkeys[i]); } subkeys[i] = add_vectors(cs, &subkeys[i], &raconsts[i]); } subkeys }
#[test] fn test_hello_world() {}
use std::fs::read_to_string; type Program<'a> = Vec<(&'a str, i32)>; fn parse(input: &str) -> Program { input.lines() .map(|line| line.split_whitespace().collect::<Vec<_>>()) .map(|line| (line[0], line[1].parse().unwrap())) .collect() } pub fn run(program: &Program) -> (bool, i32) { let (mut acc, mut ptr) = (0, 0); let mut visited_pointers = vec![false; program.len()]; loop { if ptr > program.len() - 1 { return (true, acc); } if visited_pointers[ptr] { return (false, acc); } visited_pointers[ptr] = true; match program[ptr] { ("acc", arg) => { acc += arg; ptr += 1 } ("jmp", arg) => { ptr = (ptr as i32 + arg) as usize } ("nop", _) => { ptr += 1 } _ => { panic!("Unknown operation") } } } } pub fn solve() { let input = read_to_string("../inputs/8.txt").unwrap(); let bags = parse(&input); print!("Day 8 part 1: {}\n", part_1(&bags)); print!("Day 8 part 2: {}\n", part_2(&bags)); } fn part_1(program: &Program) -> i32 { let (_, acc) = run(program); acc } fn part_2(program: &Program) -> i32 { for p in program.iter() .enumerate() .filter(|(_, (arg, _))| *arg == "jmp") .map(|(i, _)| { let mut possibility = program.clone(); possibility[i].0 = "nop"; possibility }) { let result = run(&p); if result.0 { return result.1; } } 0 } #[cfg(test)] mod tests { use super::*; #[test] fn test_parser() { let data = "nop +0\nacc +1\njmp +4\nacc +3\njmp -3\nacc -99\nacc +1\njmp -4\nacc +6"; let code = parse(&data); assert_eq!(code[0], ("nop", 0)); assert_eq!(code[4], ("jmp", -3)); } #[test] fn test_parser_real() { let data = read_to_string("../inputs/8.txt").unwrap(); let code = parse(&data); assert_eq!(code[0], ("acc", 22)); assert_eq!(code.len(), 611); } #[test] fn test_part1_with_example() { let data = "nop +0\nacc +1\njmp +4\nacc +3\njmp -3\nacc -99\nacc +1\njmp -4\nacc +6"; let code = parse(&data); let result = part_1(&code); assert_eq!(result, 5); } #[test] fn test_part1_with_real() { let data = read_to_string("../inputs/8.txt").unwrap(); let code = parse(&data); let result = part_1(&code); assert_eq!(result, 1782); } #[test] fn test_part2_with_example() { let data = "nop +0\nacc +1\njmp +4\nacc +3\njmp -3\nacc -99\nacc +1\njmp -4\nacc +6"; let code = parse(&data); let result = part_2(&code); assert_eq!(result, 8); } #[test] fn test_part2_with_real() { let data = read_to_string("../inputs/8.txt").unwrap(); let code = parse(&data); let result = part_2(&code); assert_eq!(result, 797); } }
fn print_one<'a>(x: &'a i32) { println!("`print_one`: x is {}", x); } fn add_one<'a>(x: &'a mut i32) { *x += 1; } fn print_multi<'a, 'b>(x: &'a i32, y: &'b i32) { println!("`print_multi`: x is {}, y is {}", x, y); } fn pass_x<'a, 'b>(x: &'a i32, _: &'b i32) -> &'a i32 { x } // fn invalid_output<'a>() -> &'a i32 { &7 } fn main() { let x = 7; let y = 9; print_one(&x); print_multi(&x, &y); let z = pass_x(&x, &y); print_one(z); let mut t = 3; add_one(&mut t); print_one(&t); }
#![no_std] #![feature(once_cell)] #![feature(map_try_insert)] pub mod inode; pub mod ramdisk; pub mod file_table;
use super::types; use crate::common::types as common; use crate::common::types::ParsingContext; use crate::execution; use crate::logical::types::Named; use crate::syntax::ast; use crate::syntax::ast::{PathExpr, PathSegment, TableReference}; use hashbrown::HashSet; #[derive(Fail, Debug, Clone, PartialEq, Eq)] pub enum ParseError { #[fail(display = "Type Mismatch")] TypeMismatch, #[fail(display = "Not Aggregate Function")] NotAggregateFunction, #[fail(display = "Group By statement but no aggregate function provided")] GroupByWithoutAggregateFunction, #[fail(display = "Group By statement mismatch with the non-aggregate fields")] GroupByFieldsMismatch, #[fail(display = "Invalid Arguments: {}", _0)] InvalidArguments(String), #[fail(display = "Invalid Arguments: {}", _0)] UnknownFunction(String), #[fail(display = "Having clause but no Group By clause provided")] HavingClauseWithoutGroupBy, #[fail(display = "Invalid table reference in From Clause")] FromClausePathInvalidTableReference, #[fail(display = "Using 'as' to define an alias is required in From Clause for nested path expr")] FromClauseMissingAsForPathExpr, } pub type ParseResult<T> = Result<T, ParseError>; fn parse_prefix_operator( ctx: &common::ParsingContext, op: types::LogicPrefixOp, child: &ast::Expression, ) -> ParseResult<Box<types::Formula>> { let child_parsed = parse_logic(ctx, child)?; let prefix_op = types::Formula::PrefixOperator(op, child_parsed); Ok(Box::new(prefix_op)) } fn parse_infix_operator( ctx: &common::ParsingContext, op: types::LogicInfixOp, left: &ast::Expression, right: &ast::Expression, ) -> ParseResult<Box<types::Formula>> { let left_parsed = parse_logic(ctx, left)?; let right_parsed = parse_logic(ctx, right)?; let infix_op = types::Formula::InfixOperator(op, left_parsed, right_parsed); Ok(Box::new(infix_op)) } fn parse_logic(ctx: &common::ParsingContext, expr: &ast::Expression) -> ParseResult<Box<types::Formula>> { match expr { ast::Expression::BinaryOperator(op, l, r) => { if op == &ast::BinaryOperator::And { let formula = parse_infix_operator(ctx, types::LogicInfixOp::And, l, r)?; Ok(formula) } else if op == &ast::BinaryOperator::Or { let formula = parse_infix_operator(ctx, types::LogicInfixOp::Or, l, r)?; Ok(formula) } else { parse_condition(ctx, expr) } } ast::Expression::UnaryOperator(op, c) => { if op == &ast::UnaryOperator::Not { let formula = parse_prefix_operator(ctx, types::LogicPrefixOp::Not, c)?; Ok(formula) } else { unreachable!() } } ast::Expression::Value(value_expr) => match value_expr { ast::Value::Boolean(b) => Ok(Box::new(types::Formula::Constant(*b))), _ => Err(ParseError::TypeMismatch), }, _ => unreachable!(), } } fn parse_logic_expression(ctx: &common::ParsingContext, expr: &ast::Expression) -> ParseResult<Box<types::Expression>> { let formula = parse_logic(ctx, expr)?; Ok(Box::new(types::Expression::Logic(formula))) } fn parse_value(value: &ast::Value) -> ParseResult<Box<types::Expression>> { match value { ast::Value::Boolean(b) => Ok(Box::new(types::Expression::Constant(common::Value::Boolean(*b)))), ast::Value::Float(f) => Ok(Box::new(types::Expression::Constant(common::Value::Float(*f)))), ast::Value::Integral(i) => Ok(Box::new(types::Expression::Constant(common::Value::Int(*i)))), ast::Value::StringLiteral(s) => Ok(Box::new(types::Expression::Constant(common::Value::String(s.clone())))), } } fn parse_case_when_expression( ctx: &common::ParsingContext, value_expr: &ast::Expression, ) -> ParseResult<Box<types::Expression>> { match value_expr { ast::Expression::CaseWhenExpression(case_when_expr) => { let branch = parse_logic(ctx, &case_when_expr.condition)?; let then_expr = parse_value_expression(ctx, &case_when_expr.then_expr)?; let else_expr = if let Some(e) = &case_when_expr.else_expr { Some(parse_value_expression(ctx, &e)?) } else { None }; Ok(Box::new(types::Expression::Branch(branch, then_expr, else_expr))) } _ => { unreachable!(); } } } fn parse_binary_operator( ctx: &common::ParsingContext, value_expr: &ast::Expression, ) -> ParseResult<Box<types::Expression>> { match value_expr { ast::Expression::BinaryOperator(op, left_expr, right_expr) => { if op == &ast::BinaryOperator::And || op == &ast::BinaryOperator::Or { parse_logic_expression(ctx, value_expr) } else if op == &ast::BinaryOperator::Equal || op == &ast::BinaryOperator::NotEqual || op == &ast::BinaryOperator::MoreThan || op == &ast::BinaryOperator::LessThan || op == &ast::BinaryOperator::GreaterEqual || op == &ast::BinaryOperator::LessEqual { let formula = parse_condition(ctx, value_expr)?; Ok(Box::new(types::Expression::Logic(formula))) } else { let func_name = (*op).to_string(); let left = parse_value_expression(ctx, left_expr)?; let right = parse_value_expression(ctx, right_expr)?; let args = vec![ types::Named::Expression(*left, None), types::Named::Expression(*right, None), ]; Ok(Box::new(types::Expression::Function(func_name, args))) } } _ => { unreachable!(); } } } fn parse_unary_operator(ctx: &ParsingContext, value_expr: &ast::Expression) -> ParseResult<Box<types::Expression>> { match value_expr { ast::Expression::UnaryOperator(op, expr) => { if op == &ast::UnaryOperator::Not { let formula = parse_prefix_operator(ctx, types::LogicPrefixOp::Not, expr)?; Ok(Box::new(types::Expression::Logic(formula))) } else { unreachable!(); } } _ => { unreachable!(); } } } fn parse_value_expression( ctx: &common::ParsingContext, value_expr: &ast::Expression, ) -> ParseResult<Box<types::Expression>> { match value_expr { ast::Expression::Value(v) => { let expr = parse_value(v)?; Ok(expr) } ast::Expression::Column(path_expr) => Ok(Box::new(types::Expression::Variable(path_expr.clone()))), ast::Expression::BinaryOperator(_, _, _) => parse_binary_operator(ctx, value_expr), ast::Expression::UnaryOperator(_, _) => parse_unary_operator(ctx, value_expr), ast::Expression::FuncCall(func_name, select_exprs, _) => { let mut args = Vec::new(); for select_expr in select_exprs.iter() { let arg = parse_expression(ctx, select_expr)?; args.push(*arg); } Ok(Box::new(types::Expression::Function(func_name.clone(), args))) } ast::Expression::CaseWhenExpression(_) => parse_case_when_expression(ctx, value_expr), } } fn parse_relation(op: &ast::BinaryOperator) -> ParseResult<types::Relation> { match op { ast::BinaryOperator::Equal => Ok(types::Relation::Equal), ast::BinaryOperator::NotEqual => Ok(types::Relation::NotEqual), ast::BinaryOperator::GreaterEqual => Ok(types::Relation::GreaterEqual), ast::BinaryOperator::LessEqual => Ok(types::Relation::LessEqual), ast::BinaryOperator::LessThan => Ok(types::Relation::LessThan), ast::BinaryOperator::MoreThan => Ok(types::Relation::MoreThan), _ => unreachable!(), } } fn parse_condition(ctx: &common::ParsingContext, condition: &ast::Expression) -> ParseResult<Box<types::Formula>> { match condition { ast::Expression::BinaryOperator(op, left_expr, right_expr) => { let left = parse_value_expression(ctx, left_expr)?; let right = parse_value_expression(ctx, right_expr)?; let rel_op = parse_relation(op)?; Ok(Box::new(types::Formula::Predicate(rel_op, left, right))) } _ => unreachable!(), } } fn parse_expression(ctx: &ParsingContext, select_expr: &ast::SelectExpression) -> ParseResult<Box<types::Named>> { match select_expr { ast::SelectExpression::Star => Ok(Box::new(types::Named::Star)), ast::SelectExpression::Expression(expr, name_opt) => { let e = parse_value_expression(ctx, expr)?; match &*e { types::Expression::Variable(path_expr) => { let name = match path_expr.path_segments.last().unwrap() { PathSegment::ArrayIndex(_s, _) => None, PathSegment::AttrName(s) => Some(s.clone()), }; Ok(Box::new(types::Named::Expression(*e.clone(), name))) } _ => Ok(Box::new(types::Named::Expression(*e, name_opt.clone()))), } } } } fn from_str(value: &str, named: types::Named) -> ParseResult<types::Aggregate> { match value { "avg" => Ok(types::Aggregate::Avg(named)), "count" => Ok(types::Aggregate::Count(named)), "first" => Ok(types::Aggregate::First(named)), "last" => Ok(types::Aggregate::Last(named)), "max" => Ok(types::Aggregate::Max(named)), "min" => Ok(types::Aggregate::Min(named)), "sum" => Ok(types::Aggregate::Sum(named)), "approx_count_distinct" => Ok(types::Aggregate::ApproxCountDistinct(named)), _ => Err(ParseError::NotAggregateFunction), } } fn parse_ordering(ordering: ast::Ordering) -> ParseResult<types::Ordering> { match ordering { ast::Ordering::Desc => Ok(types::Ordering::Desc), ast::Ordering::Asc => Ok(types::Ordering::Asc), } } fn parse_aggregate(ctx: &ParsingContext, select_expr: &ast::SelectExpression) -> ParseResult<types::NamedAggregate> { match select_expr { ast::SelectExpression::Expression(expr, name_opt) => match &**expr { ast::Expression::FuncCall(func_name, args, within_group_opt) => { let named = *parse_expression(ctx, &args[0])?; let aggregate = if let Some(within_group_clause) = within_group_opt { match named { types::Named::Expression(expr, _) => match expr { types::Expression::Constant(val) => match val { common::Value::Float(f) => { let o = parse_ordering(within_group_clause.ordering_term.ordering.clone())?; if func_name == "percentile_disc" { types::Aggregate::PercentileDisc( f, within_group_clause.ordering_term.column_name.clone(), o, ) } else if func_name == "approx_percentile" { types::Aggregate::ApproxPercentile( f, within_group_clause.ordering_term.column_name.clone(), o, ) } else { return Err(ParseError::UnknownFunction(func_name.to_string())); } } _ => { return Err(ParseError::InvalidArguments("percentile_disc".to_string())); } }, _ => { //FIXME: should be ok for a function returning Float as well return Err(ParseError::InvalidArguments("percentile_disc".to_string())); } }, _ => { //Star should be disallowed. return Err(ParseError::InvalidArguments("percentile_disc".to_string())); } } } else { from_str(&**func_name, named)? }; let named_aggregate = types::NamedAggregate::new(aggregate, name_opt.clone()); Ok(named_aggregate) } _ => Err(ParseError::TypeMismatch), }, _ => Err(ParseError::TypeMismatch), } } fn check_contains_group_as_var(named_list: &[types::Named], group_as_var: &String) -> bool { for named in named_list.iter() { match named { types::Named::Expression(expr, var_name_opt) => { if let Some(var_name) = var_name_opt { if var_name.eq(group_as_var) { return true; } } else if let types::Expression::Variable(var_name) = expr { let path_expr = &PathExpr::new(vec![PathSegment::AttrName(group_as_var.clone())]); if path_expr.eq(var_name) { return true; } } } types::Named::Star => {} } } false } fn check_env(table_name: &String, table_references: &Vec<TableReference>) -> ParseResult<()> { for (i, table_reference) in table_references.iter().enumerate() { if i == 0 { match &table_reference.path_expr.path_segments[0] { PathSegment::AttrName(s) => { if !s.eq(table_name) { return Err(ParseError::FromClausePathInvalidTableReference); } } _ => return Err(ParseError::FromClausePathInvalidTableReference), } } let path_expr = &table_reference.path_expr; if path_expr.path_segments.is_empty() { return Err(ParseError::FromClausePathInvalidTableReference); } if path_expr.path_segments.len() > 1 && table_reference.as_clause.is_none() { return Err(ParseError::FromClauseMissingAsForPathExpr); } } Ok(()) } fn to_bindings(table_name: &String, table_references: &Vec<TableReference>) -> Vec<common::Binding> { table_references .iter() .map(|table_reference| { let path_expr = match &table_reference.path_expr.path_segments[0] { PathSegment::AttrName(s) => { if s.eq(table_name) { PathExpr::new( table_reference .path_expr .path_segments .iter() .skip(1) .cloned() .collect(), ) } else { table_reference.path_expr.clone() } } _ => table_reference.path_expr.clone(), }; if let Some(name) = table_reference.as_clause.clone() { Some(common::Binding { path_expr, name, idx_name: table_reference.at_clause.clone(), }) } else { None } }) .filter_map(|x| x) .collect() } fn check_group_by_vars(named: &Named, group_by_vars: &HashSet<String>) -> bool { match named { Named::Expression(expr, alias) => { match expr { types::Expression::Variable(path_expr) => match path_expr.path_segments.last().unwrap() { PathSegment::AttrName(s) => { return group_by_vars.contains(s); } PathSegment::ArrayIndex(_, _) => { return false; } }, types::Expression::Function(_, _) => { if let Some(a) = alias { return group_by_vars.contains(a); } else { return false; } } _ => { //TODO: branch furhter return false; } } } _ => { return false; } } } pub(crate) fn parse_query(query: ast::SelectStatement, data_source: common::DataSource) -> ParseResult<types::Node> { let table_references = &query.table_references; let (file_format, table_name) = match &data_source { common::DataSource::File(_, file_format, table_name) => (file_format.clone(), table_name.clone()), common::DataSource::Stdin(file_format, table_name) => (file_format.clone(), table_name.clone()), }; check_env(&table_name, table_references)?; let parsing_context = ParsingContext { table_name: table_name.clone(), }; let bindings = to_bindings(&table_name, table_references); let mut root = types::Node::DataSource(data_source, bindings); let mut named_aggregates = Vec::new(); let mut named_list: Vec<types::Named> = Vec::new(); let mut non_aggregates: Vec<types::Named> = Vec::new(); let mut group_by_vars: HashSet<String> = HashSet::default(); if let Some(group_by) = &query.group_by_exprs_opt { for (position, r) in group_by.exprs.iter().enumerate() { let e = parse_value_expression(&parsing_context, &r.column_expr)?; let named = match &*e { types::Expression::Variable(path_expr) => { if let Some(alias) = &r.as_clause { group_by_vars.insert(alias.clone()); types::Named::Expression(*e.clone(), Some(alias.clone())) } else { let l = path_expr.path_segments.last().unwrap(); match l { PathSegment::AttrName(s) => { group_by_vars.insert(s.clone()); types::Named::Expression(*e.clone(), Some(s.clone())) } PathSegment::ArrayIndex(_s, _idx) => { group_by_vars.insert(format!("_{}", position + 1)); types::Named::Expression(*e.clone(), Some(format!("_{}", position + 1))) } } } } _ => { if let Some(alias) = &r.as_clause { group_by_vars.insert(alias.clone()); types::Named::Expression(*e.clone(), Some(alias.clone())) } else { group_by_vars.insert(format!("_{}", position + 1)); types::Named::Expression(*e.clone(), Some(format!("_{}", position + 1))) } } }; non_aggregates.push(named.clone()); named_list.push(named); } } match query.select_clause { ast::SelectClause::SelectExpressions(select_exprs) => { if !select_exprs.is_empty() { for (offset, select_expr) in select_exprs.iter().enumerate() { if let Ok(mut named_aggregate) = parse_aggregate(&parsing_context, select_expr) { match &named_aggregate.aggregate { types::Aggregate::GroupAsAggregate(_) => { unreachable!(); } types::Aggregate::Avg(named) => { if let types::Named::Star = named { return Err(ParseError::InvalidArguments("avg".to_string())); } named_aggregates.push(named_aggregate.clone()); named_list.push(named.clone()); } types::Aggregate::Count(named) => { named_aggregates.push(named_aggregate.clone()); named_list.push(named.clone()); } types::Aggregate::First(named) => { if let types::Named::Star = named { return Err(ParseError::InvalidArguments("first".to_string())); } named_aggregates.push(named_aggregate.clone()); named_list.push(named.clone()); } types::Aggregate::Last(named) => { if let types::Named::Star = named { return Err(ParseError::InvalidArguments("last".to_string())); } named_aggregates.push(named_aggregate.clone()); named_list.push(named.clone()); } types::Aggregate::Sum(named) => { let nnn = named.clone(); match &named { types::Named::Star => { return Err(ParseError::InvalidArguments("sum".to_string())); } types::Named::Expression(expr, opt_name) => match expr { types::Expression::Variable(path_expr) => { let l = path_expr.path_segments.last().unwrap(); match l { PathSegment::AttrName(_s) => { let p = PathExpr::new(vec![l.clone()]); let n = types::Named::Expression( types::Expression::Variable(p), opt_name.clone(), ); named_aggregate.aggregate = types::Aggregate::Sum(n); named_aggregates.push(named_aggregate); named_list.push(nnn); } PathSegment::ArrayIndex(_s, _idx) => { let s = format! {"_{}", offset}; let p = PathExpr::new(vec![PathSegment::AttrName(s)]); let n = types::Named::Expression( types::Expression::Variable(p), opt_name.clone(), ); named_aggregate.aggregate = types::Aggregate::Sum(n); named_aggregates.push(named_aggregate); named_list.push(nnn); } } } _ => { named_aggregates.push(named_aggregate.clone()); named_list.push(named.clone()); } }, } } types::Aggregate::Max(named) => { if let types::Named::Star = named { return Err(ParseError::InvalidArguments("max".to_string())); } named_aggregates.push(named_aggregate.clone()); named_list.push(named.clone()); } types::Aggregate::Min(named) => { if let types::Named::Star = named { return Err(ParseError::InvalidArguments("min".to_string())); } named_aggregates.push(named_aggregate.clone()); named_list.push(named.clone()); } types::Aggregate::ApproxCountDistinct(named) => { if let types::Named::Star = named { return Err(ParseError::InvalidArguments("approx_count_distinct".to_string())); } named_aggregates.push(named_aggregate.clone()); named_list.push(named.clone()); } types::Aggregate::PercentileDisc(_, column_name, _) => { named_aggregates.push(named_aggregate.clone()); named_list.push(types::Named::Expression( types::Expression::Variable(column_name.clone()), Some(column_name.unwrap_last()), )) } types::Aggregate::ApproxPercentile(_, column_name, _) => { named_aggregates.push(named_aggregate.clone()); named_list.push(types::Named::Expression( types::Expression::Variable(column_name.clone()), Some(column_name.unwrap_last()), )) } } } else { let named = *parse_expression(&parsing_context, select_expr)?; if query.group_by_exprs_opt.is_some() { if !check_group_by_vars(&named, &group_by_vars) { return Err(ParseError::GroupByFieldsMismatch); } } else if let Some(group_as_clause) = query .group_by_exprs_opt .as_ref() .and_then(|x| x.group_as_clause.as_ref()) { if check_contains_group_as_var(&[named.clone()], group_as_clause) { named_list.push(named.clone()); named_aggregates.push(types::NamedAggregate::new( types::Aggregate::GroupAsAggregate(named), Some(group_as_clause.clone()), )); } } else { non_aggregates.push(named.clone()); named_list.push(named.clone()); } } } root = types::Node::Map(named_list.clone(), Box::new(root)); } } ast::SelectClause::ValueConstructor(_vc) => { unimplemented!() } } if let Some(where_expr) = query.where_expr_opt { let filter_formula = parse_logic(&parsing_context, &where_expr.expr)?; root = types::Node::Filter(filter_formula, Box::new(root)); } if !named_aggregates.is_empty() { if let Some(group_by) = query.group_by_exprs_opt { let fields: Vec<PathExpr> = group_by .exprs .iter() .enumerate() .map(|(position, r)| { let e = parse_value_expression(&parsing_context, &r.column_expr).unwrap(); match &*e { types::Expression::Variable(path_expr) => { if let Some(alias) = &r.as_clause { PathExpr::new(vec![PathSegment::AttrName(alias.clone())]) } else { let l = path_expr.path_segments.last().unwrap(); match l { PathSegment::AttrName(s) => PathExpr::new(vec![PathSegment::AttrName(s.clone())]), PathSegment::ArrayIndex(_s, _idx) => { let s = format!("_{}", position + 1); PathExpr::new(vec![PathSegment::AttrName(s.clone())]) } } } } _ => { if let Some(alias) = &r.as_clause { PathExpr::new(vec![PathSegment::AttrName(alias.clone())]) } else { let s = format!("_{}", position + 1); PathExpr::new(vec![PathSegment::AttrName(s.clone())]) } } } }) .collect(); if !is_match_group_by_fields(&fields, &non_aggregates, &file_format) { return Err(ParseError::GroupByFieldsMismatch); } root = types::Node::GroupBy(fields, named_aggregates, Box::new(root)); } else { let fields = Vec::new(); root = types::Node::GroupBy(fields, named_aggregates, Box::new(root)); } if let Some(having_expr) = query.having_expr_opt { let filter_formula = parse_logic(&parsing_context, &having_expr.expr)?; root = types::Node::Filter(filter_formula, Box::new(root)); } } else { //sanity check if there is a group by statement if let Some(group_by_exprs) = query.group_by_exprs_opt { if let Some(group_as_clause) = group_by_exprs.group_as_clause { if !check_contains_group_as_var(&named_list, &group_as_clause) { return Err(ParseError::GroupByWithoutAggregateFunction); } } else { return Err(ParseError::GroupByWithoutAggregateFunction); } } if query.having_expr_opt.is_some() { return Err(ParseError::HavingClauseWithoutGroupBy); } } if let Some(order_by_expr) = query.order_by_expr_opt { let mut column_names = Vec::new(); let mut orderings = Vec::new(); for ordering_term in order_by_expr.ordering_terms { column_names.push(ordering_term.column_name.clone()); let ordering = parse_ordering(ordering_term.ordering)?; orderings.push(ordering); } root = types::Node::OrderBy(column_names, orderings, Box::new(root)); } if let Some(limit_expr) = query.limit_expr_opt { root = types::Node::Limit(limit_expr.row_count, Box::new(root)); } Ok(root) } fn is_match_group_by_fields(variables: &[ast::PathExpr], named_list: &[types::Named], file_format: &str) -> bool { let a: HashSet<PathExpr> = variables.iter().map(|s| s.clone()).collect(); let mut b: HashSet<PathExpr> = HashSet::new(); for named in named_list.iter() { match named { types::Named::Expression(expr, name_opt) => { if let Some(name) = name_opt { b.insert(PathExpr::new(vec![PathSegment::AttrName(name.clone())])); } else { match expr { types::Expression::Variable(path_expr) => { b.insert(path_expr.clone()); } _ => { return false; } } } } types::Named::Star => { if file_format == "elb" { for field_name in execution::datasource::ClassicLoadBalancerLogField::field_names().into_iter() { b.insert(PathExpr::new(vec![PathSegment::AttrName(field_name.clone())])); } } else if file_format == "alb" { for field_name in execution::datasource::ApplicationLoadBalancerLogField::field_names().into_iter() { b.insert(PathExpr::new(vec![PathSegment::AttrName(field_name.clone())])); } } else if file_format == "squid" { for field_name in execution::datasource::SquidLogField::field_names().into_iter() { b.insert(PathExpr::new(vec![PathSegment::AttrName(field_name.clone())])); } } else if file_format == "s3" { for field_name in execution::datasource::S3Field::field_names().into_iter() { b.insert(PathExpr::new(vec![PathSegment::AttrName(field_name.clone())])); } } else { unreachable!(); } } } } if a.len() != b.len() { false } else { let mut a_iter = a.iter(); let mut b_iter = b.iter(); while let (Some(aa), Some(bb)) = (a_iter.next(), b_iter.next()) { if aa != bb { return false; } } true } } #[cfg(test)] mod test { use super::*; use crate::syntax::ast::{PathSegment, SelectClause}; #[test] fn test_parse_logic_expression() { let before = ast::Expression::BinaryOperator( ast::BinaryOperator::And, Box::new(ast::Expression::Value(ast::Value::Boolean(true))), Box::new(ast::Expression::Value(ast::Value::Boolean(false))), ); let parsing_context = ParsingContext { table_name: "a".to_string(), }; let expected = Box::new(types::Expression::Logic(Box::new(types::Formula::InfixOperator( types::LogicInfixOp::And, Box::new(types::Formula::Constant(true)), Box::new(types::Formula::Constant(false)), )))); let ans = parse_logic_expression(&parsing_context, &before).unwrap(); assert_eq!(expected, ans); let before = ast::Expression::UnaryOperator( ast::UnaryOperator::Not, Box::new(ast::Expression::Value(ast::Value::Boolean(false))), ); let expected = Box::new(types::Expression::Logic(Box::new(types::Formula::PrefixOperator( types::LogicPrefixOp::Not, Box::new(types::Formula::Constant(false)), )))); let parsing_context = ParsingContext { table_name: "a".to_string(), }; let ans = parse_logic_expression(&parsing_context, &before).unwrap(); assert_eq!(expected, ans); } #[test] fn test_parse_value_expression() { let before = ast::Expression::BinaryOperator( ast::BinaryOperator::Plus, Box::new(ast::Expression::BinaryOperator( ast::BinaryOperator::Plus, Box::new(ast::Expression::Value(ast::Value::Integral(1))), Box::new(ast::Expression::Value(ast::Value::Integral(2))), )), Box::new(ast::Expression::Value(ast::Value::Integral(3))), ); let expected = Box::new(types::Expression::Function( "Plus".to_string(), vec![ types::Named::Expression( types::Expression::Function( "Plus".to_string(), vec![ types::Named::Expression(types::Expression::Constant(common::Value::Int(1)), None), types::Named::Expression(types::Expression::Constant(common::Value::Int(2)), None), ], ), None, ), types::Named::Expression(types::Expression::Constant(common::Value::Int(3)), None), ], )); let parsing_context = ParsingContext { table_name: "a".to_string(), }; let ans = parse_value_expression(&parsing_context, &before).unwrap(); assert_eq!(expected, ans); } #[test] fn test_parse_aggregate() { let path_expr_a = PathExpr::new(vec![PathSegment::AttrName("a".to_string())]); let before = ast::SelectExpression::Expression( Box::new(ast::Expression::FuncCall( "avg".to_string(), vec![ast::SelectExpression::Expression( Box::new(ast::Expression::Column(path_expr_a.clone())), None, )], None, )), None, ); let named = types::Named::Expression(types::Expression::Variable(path_expr_a.clone()), Some("a".to_string())); let expected = types::NamedAggregate::new(types::Aggregate::Avg(named), None); let parsing_context = ParsingContext { table_name: "a".to_string(), }; let ans = parse_aggregate(&parsing_context, &before).unwrap(); assert_eq!(expected, ans); } #[test] fn test_parse_condition() { let path_expr = PathExpr::new(vec![PathSegment::AttrName("a".to_string())]); let before = ast::Expression::BinaryOperator( ast::BinaryOperator::Equal, Box::new(ast::Expression::Column(path_expr.clone())), Box::new(ast::Expression::Value(ast::Value::Integral(1))), ); let expected = Box::new(types::Formula::Predicate( types::Relation::Equal, Box::new(types::Expression::Variable(path_expr.clone())), Box::new(types::Expression::Constant(common::Value::Int(1))), )); let parsing_context = ParsingContext { table_name: "a".to_string(), }; let ans = parse_condition(&parsing_context, &before).unwrap(); assert_eq!(expected, ans); } #[test] fn test_parse_query_with_simple_select_where_with_bindings() { let path_expr_a = PathExpr::new(vec![PathSegment::AttrName("a".to_string())]); let path_expr_b = PathExpr::new(vec![PathSegment::AttrName("b".to_string())]); let select_exprs = vec![ ast::SelectExpression::Expression(Box::new(ast::Expression::Column(path_expr_a.clone())), None), ast::SelectExpression::Expression(Box::new(ast::Expression::Column(path_expr_b.clone())), None), ]; let where_expr = ast::WhereExpression::new(ast::Expression::BinaryOperator( ast::BinaryOperator::Equal, Box::new(ast::Expression::Column(path_expr_a.clone())), Box::new(ast::Expression::Value(ast::Value::Integral(1))), )); let path_expr = PathExpr::new(vec![ PathSegment::AttrName("it".to_string()), PathSegment::AttrName("a".to_string()), ]); let table_reference = ast::TableReference::new(path_expr, Some("e".to_string()), None); let before = ast::SelectStatement::new( SelectClause::SelectExpressions(select_exprs), vec![table_reference], Some(where_expr), None, None, None, None, ); let data_source = common::DataSource::Stdin("jsonl".to_string(), "it".to_string()); let filtered_formula = Box::new(types::Formula::Predicate( types::Relation::Equal, Box::new(types::Expression::Variable(path_expr_a.clone())), Box::new(types::Expression::Constant(common::Value::Int(1))), )); let path_expr = PathExpr::new(vec![PathSegment::AttrName("a".to_string())]); let bindings = vec![common::Binding { path_expr, name: "e".to_string(), idx_name: None, }]; let expected = types::Node::Filter( filtered_formula, Box::new(types::Node::Map( vec![ types::Named::Expression(types::Expression::Variable(path_expr_a.clone()), Some("a".to_string())), types::Named::Expression(types::Expression::Variable(path_expr_b.clone()), Some("b".to_string())), ], Box::new(types::Node::DataSource( common::DataSource::Stdin("jsonl".to_string(), "it".to_string()), bindings, )), )), ); let ans = parse_query(before, data_source).unwrap(); assert_eq!(expected, ans); } #[test] fn test_parse_query_with_simple_select_where_no_from_clause_bindings() { let path_expr_a = PathExpr::new(vec![PathSegment::AttrName("a".to_string())]); let path_expr_b = PathExpr::new(vec![PathSegment::AttrName("b".to_string())]); let select_exprs = vec![ ast::SelectExpression::Expression(Box::new(ast::Expression::Column(path_expr_a.clone())), None), ast::SelectExpression::Expression(Box::new(ast::Expression::Column(path_expr_b.clone())), None), ]; let where_expr = ast::WhereExpression::new(ast::Expression::BinaryOperator( ast::BinaryOperator::Equal, Box::new(ast::Expression::Column(path_expr_a.clone())), Box::new(ast::Expression::Value(ast::Value::Integral(1))), )); let path_expr = PathExpr::new(vec![PathSegment::AttrName("it".to_string())]); let table_reference = ast::TableReference::new(path_expr, None, None); let before = ast::SelectStatement::new( SelectClause::SelectExpressions(select_exprs), vec![table_reference], Some(where_expr), None, None, None, None, ); let data_source = common::DataSource::Stdin("jsonl".to_string(), "it".to_string()); let filtered_formula = Box::new(types::Formula::Predicate( types::Relation::Equal, Box::new(types::Expression::Variable(path_expr_a.clone())), Box::new(types::Expression::Constant(common::Value::Int(1))), )); let expected = types::Node::Filter( filtered_formula, Box::new(types::Node::Map( vec![ types::Named::Expression(types::Expression::Variable(path_expr_a.clone()), Some("a".to_string())), types::Named::Expression(types::Expression::Variable(path_expr_b.clone()), Some("b".to_string())), ], Box::new(types::Node::DataSource( common::DataSource::Stdin("jsonl".to_string(), "it".to_string()), vec![], )), )), ); let ans = parse_query(before, data_source).unwrap(); assert_eq!(expected, ans); } #[test] fn test_parse_query_with_group_by() { let path_expr_a = PathExpr::new(vec![PathSegment::AttrName("a".to_string())]); let path_expr_b = PathExpr::new(vec![PathSegment::AttrName("b".to_string())]); let select_exprs = vec![ ast::SelectExpression::Expression( Box::new(ast::Expression::FuncCall( "avg".to_string(), vec![ast::SelectExpression::Expression( Box::new(ast::Expression::Column(path_expr_a.clone())), None, )], None, )), None, ), ast::SelectExpression::Expression(Box::new(ast::Expression::Column(path_expr_b.clone())), None), ]; let where_expr = ast::WhereExpression::new(ast::Expression::BinaryOperator( ast::BinaryOperator::Equal, Box::new(ast::Expression::Column(path_expr_a.clone())), Box::new(ast::Expression::Value(ast::Value::Integral(1))), )); let group_by_ref = ast::GroupByReference::new(ast::Expression::Column(path_expr_b.clone()), None); let group_by_expr = ast::GroupByExpression::new(vec![group_by_ref], None); let path_expr = PathExpr::new(vec![PathSegment::AttrName("it".to_string())]); let table_reference = ast::TableReference::new(path_expr, None, None); let before = ast::SelectStatement::new( SelectClause::SelectExpressions(select_exprs), vec![table_reference], Some(where_expr), Some(group_by_expr), None, None, None, ); let data_source = common::DataSource::Stdin("jsonl".to_string(), "it".to_string()); let filtered_formula = Box::new(types::Formula::Predicate( types::Relation::Equal, Box::new(types::Expression::Variable(path_expr_a.clone())), Box::new(types::Expression::Constant(common::Value::Int(1))), )); let path_expr = PathExpr::new(vec![PathSegment::AttrName("it".to_string())]); let _binding = common::Binding { path_expr, name: "e".to_string(), idx_name: None, }; let filter = types::Node::Filter( filtered_formula, Box::new(types::Node::Map( vec![ types::Named::Expression(types::Expression::Variable(path_expr_b.clone()), Some("b".to_string())), types::Named::Expression(types::Expression::Variable(path_expr_a.clone()), Some("a".to_string())), ], Box::new(types::Node::DataSource( common::DataSource::Stdin("jsonl".to_string(), "it".to_string()), vec![], )), )), ); let named_aggregates = vec![types::NamedAggregate::new( types::Aggregate::Avg(types::Named::Expression( types::Expression::Variable(path_expr_a), Some("a".to_string()), )), None, )]; let fields = vec![path_expr_b.clone()]; let expected = types::Node::GroupBy(fields, named_aggregates, Box::new(filter)); let ans = parse_query(before, data_source).unwrap(); assert_eq!(expected, ans); } #[test] fn test_parse_query_group_by_without_aggregate() { let path_expr_a = PathExpr::new(vec![PathSegment::AttrName("a".to_string())]); let path_expr_b = PathExpr::new(vec![PathSegment::AttrName("b".to_string())]); let select_exprs = vec![ ast::SelectExpression::Expression(Box::new(ast::Expression::Column(path_expr_a.clone())), None), ast::SelectExpression::Expression(Box::new(ast::Expression::Column(path_expr_b.clone())), None), ]; let where_expr = ast::WhereExpression::new(ast::Expression::BinaryOperator( ast::BinaryOperator::Equal, Box::new(ast::Expression::Column(path_expr_a.clone())), Box::new(ast::Expression::Value(ast::Value::Integral(1))), )); let group_by_ref = ast::GroupByReference::new(ast::Expression::Column(path_expr_b.clone()), None); let group_by_expr = ast::GroupByExpression::new(vec![group_by_ref], None); let path_expr = PathExpr::new(vec![PathSegment::AttrName("it".to_string())]); let table_reference = ast::TableReference::new(path_expr, None, None); let before = ast::SelectStatement::new( SelectClause::SelectExpressions(select_exprs), vec![table_reference], Some(where_expr), Some(group_by_expr), None, None, None, ); let data_source = common::DataSource::Stdin("jsonl".to_string(), "it".to_string()); let ans = parse_query(before, data_source); let expected = Err(ParseError::GroupByFieldsMismatch); assert_eq!(expected, ans); } #[test] fn test_parse_query_group_by_mismatch_fields() { let path_expr_a = PathExpr::new(vec![PathSegment::AttrName("a".to_string())]); let path_expr_b = PathExpr::new(vec![PathSegment::AttrName("b".to_string())]); let path_expr_c = PathExpr::new(vec![PathSegment::AttrName("c".to_string())]); let select_exprs = vec![ ast::SelectExpression::Expression(Box::new(ast::Expression::Column(path_expr_a.clone())), None), ast::SelectExpression::Expression(Box::new(ast::Expression::Column(path_expr_b.clone())), None), ast::SelectExpression::Expression( Box::new(ast::Expression::FuncCall( "count".to_string(), vec![ast::SelectExpression::Expression( Box::new(ast::Expression::Column(path_expr_c.clone())), None, )], None, )), None, ), ]; let group_by_ref = ast::GroupByReference::new(ast::Expression::Column(path_expr_b.clone()), None); let group_by_expr = ast::GroupByExpression::new(vec![group_by_ref], None); let path_expr = PathExpr::new(vec![PathSegment::AttrName("it".to_string())]); let table_reference = ast::TableReference::new(path_expr, None, None); let before = ast::SelectStatement::new( SelectClause::SelectExpressions(select_exprs), vec![table_reference], None, Some(group_by_expr), None, None, None, ); let data_source = common::DataSource::Stdin("jsonl".to_string(), "it".to_string()); let ans = parse_query(before, data_source); let expected = Err(ParseError::GroupByFieldsMismatch); assert_eq!(expected, ans); } }
#![allow(dead_code)] mod tl_client; fn main() { }
use std; import state::{state, outcome, cont, died, won, cmd, move, wait, score}; import geom::{left, down, up, right}; import std::list; import std::list::{list, nil, cons}; import result::{result, ok, err}; type posn = { state: state, outcome: outcome, trail: @list<cmd>, score: score }; type shell = { mut best: posn }; enum stop { timeout } type res<T> = result<T, stop>; impl stuff for posn { fn to_str() -> str { let mut chars = ~[]; for list::each(self.trail) |cmd| { chars += ~[state::char_of_cmd(cmd)]; } str::from_chars(vec::reversed(chars)) } fn head() -> cmd { alt *self.trail { cons(a,_d) { a } nil { wait } } } } fn start(state: state) -> (shell,posn) { assert(state.time == 0); sigwrap::enable(sigwrap::SIGINT); sigwrap::enable(sigwrap::SIGALRM); let posn = { state: state, outcome: cont, trail: @nil, score: 0 }; ret ({ mut best: posn }, posn) } impl stuff for shell { fn step(posn: posn, cmd: cmd) -> res<posn> { assert(posn.outcome == cont); if sigwrap::get() { io::println((copy self.best).to_str()); err(timeout) } else { let (res, state) = posn.state.step(cmd); let score = state.score(alt res { cont { none } r { some(r) } }); let retv = {state: state, outcome: res, trail: @cons(cmd, posn.trail), score: score}; if score > self.best.score { #info("Score: %?; Trail: %s", score, retv.to_str()); self.best = copy retv; } ok(retv) } } fn finish() { io::println((copy self.best).to_str()); // XXX might want to reenable the signals.... } }
use crate::error::Error; use gfx_hal::adapter::Adapter; use gfx_hal::window::Extent2D; use gfx_hal::{ adapter::PhysicalDevice, device::Device, format::Swizzle, format::{Aspects, Format}, image::{SubresourceRange, ViewKind}, memory::{Properties, Requirements}, Backend, MemoryTypeId, }; use std::mem::ManuallyDrop; pub struct DepthImage<B: Backend> { pub image: ManuallyDrop<B::Image>, pub requirements: Requirements, pub memory: ManuallyDrop<B::Memory>, pub image_view: ManuallyDrop<B::ImageView>, } impl<B: Backend> DepthImage<B> { pub fn new( adapter: &Adapter<B>, device: &<B as Backend>::Device, extent: Extent2D, ) -> Result<Self, Error> { unsafe { let mut image = device.create_image( gfx_hal::image::Kind::D2(extent.width, extent.height, 1, 1), 1, Format::D32Sfloat, gfx_hal::image::Tiling::Optimal, gfx_hal::image::Usage::DEPTH_STENCIL_ATTACHMENT, gfx_hal::image::ViewCapabilities::empty(), )?; let requirements = device.get_image_requirements(&image); let (memory_type_idx, _) = adapter .physical_device .memory_properties() .memory_types .iter() .enumerate() .find(|&(idx, mt)| { requirements.type_mask & (1 << idx) != 0 && mt.properties.contains(Properties::DEVICE_LOCAL) }) .ok_or("Couldn't find appropriate memory")?; let memory = device.allocate_memory(MemoryTypeId(memory_type_idx), requirements.size)?; device.bind_image_memory(&memory, 0, &mut image)?; let image_view = device.create_image_view( &image, ViewKind::D2, Format::D32Sfloat, Swizzle::NO, SubresourceRange { aspects: Aspects::DEPTH, levels: 0..1, layers: 0..1, }, )?; Ok(Self { image: ManuallyDrop::new(image), requirements, memory: ManuallyDrop::new(memory), image_view: ManuallyDrop::new(image_view), }) } } pub unsafe fn dispose(self, device: &<B as Backend>::Device) { let Self { image, requirements, memory, image_view, } = self; device.destroy_image(ManuallyDrop::into_inner(image)); device.free_memory(ManuallyDrop::into_inner(memory)); device.destroy_image_view(ManuallyDrop::into_inner(image_view)); } }
use cpython::{NoArgs, ObjectProtocol, PyResult, Python}; use std::collections::{BTreeMap, HashMap}; use std::fmt::Debug; use std::hash::Hash; use std::time::{Duration, Instant}; pub fn run_benchmark<T: Debug + Copy + Hash + Ord, U: Debug + PartialEq>( reps: usize, range: impl Iterator<Item = T>, benchees: &[(impl ToString, &dyn Fn(T) -> U)], ) -> BenchResult<T> { let mut time_measurements = BTreeMap::new(); for param in range { let mut times = vec![]; for rep in 0..reps { let mut f_times = vec![]; let mut results = vec![]; for (_, f) in benchees { let start = Instant::now(); let res = f(param); let time_taken = start.elapsed(); f_times.push(time_taken); results.push(res); } for w in results.windows(2) { if w[0] != w[1] { panic!( "result mismatch ({:?} != {:?}) in repetetion {} for parameter {:?}", w[0], w[1], rep, param ); } } times.push(f_times); } time_measurements.insert(param, times); } BenchResult::new( time_measurements, benchees.iter().map(|(n, _)| n.to_string()).collect(), ) } pub struct BenchResult<T> { measurements: HashMap<String, BTreeMap<T, Vec<Duration>>>, } impl<T: Copy + Ord> BenchResult<T> { pub fn new(data: BTreeMap<T, Vec<Vec<Duration>>>, names: Vec<String>) -> Self { let mut measurements: HashMap<_, BTreeMap<T, Vec<_>>> = names.iter().map(|n| (n.clone(), BTreeMap::new())).collect(); for (param, runs) in data { for rep in runs { for (name, dur) in names.iter().zip(rep) { measurements .get_mut(name) .expect("missing measurement entry") .entry(param) .or_insert(vec![]) .push(dur); } } } BenchResult { measurements } } } pub trait Plotable { fn as_f64(&self) -> f64; } impl Plotable for f64 { fn as_f64(&self) -> f64 { *self } } impl Plotable for i64 { fn as_f64(&self) -> f64 { *self as f64 } } impl<T: Copy + Ord + Plotable> BenchResult<T> { pub fn plot(&self) -> PyResult<()> { let gil = Python::acquire_gil(); let py = gil.python(); let plt = py.import("matplotlib.pyplot")?; // I'm sure a macro could make this nicer... for (name, m) in &self.measurements { let mut x: Vec<f64> = vec![]; let mut y: Vec<f64> = vec![]; let mut s: Vec<f64> = vec![]; for (p, r) in m { x.push(p.as_f64()); let mean = r.iter().map(|d| d.as_secs_f64()).sum::<f64>() / r.len() as f64; let std = r .iter() .map(|d| (d.as_secs_f64() - mean).powf(2.0).sqrt()) .sum::<f64>() / r.len() as f64; y.push(mean); s.push(std); } plt.get(py, "errorbar")?.call(py, (x, y, s), None)?; } plt.get(py, "legend")? .call(py, (self.measurements.keys().collect::<Vec<_>>(),), None)?; plt.get(py, "show")?.call(py, NoArgs, None)?; Ok(()) } }
use std::{net::SocketAddr, ops::Deref, sync::Arc}; use actionable::Permissions; use bonsaidb_core::{custodian_password::ServerLogin, custom_api::CustomApi}; use flume::Sender; use tokio::sync::{Mutex, RwLock}; use crate::{Backend, CustomServer}; /// The ways a client can be connected to the server. #[derive(Debug, PartialEq, Eq)] pub enum Transport { /// A connection over `BonsaiDb`'s QUIC-based protocol. Bonsai, /// A connection over WebSockets. #[cfg(feature = "websockets")] WebSocket, } /// A connected database client. #[derive(Debug)] pub struct ConnectedClient<B: Backend = ()> { data: Arc<Data<B>>, } #[derive(Debug)] struct Data<B: Backend = ()> { id: u32, address: SocketAddr, transport: Transport, response_sender: Sender<<B::CustomApi as CustomApi>::Response>, auth_state: RwLock<AuthenticationState>, pending_password_login: Mutex<Option<(Option<u64>, ServerLogin)>>, } #[derive(Debug, Default)] struct AuthenticationState { user_id: Option<u64>, permissions: Permissions, } impl<B: Backend> Clone for ConnectedClient<B> { fn clone(&self) -> Self { Self { data: self.data.clone(), } } } impl<B: Backend> ConnectedClient<B> { /// Returns the address of the connected client. #[must_use] pub fn address(&self) -> &SocketAddr { &self.data.address } /// Returns the transport method the client is connected via. #[must_use] pub fn transport(&self) -> &Transport { &self.data.transport } /// Returns the current permissions for this client. Will reflect the /// current state of authentication. pub async fn permissions(&self) -> Permissions { let auth_state = self.data.auth_state.read().await; auth_state.permissions.clone() } /// Returns the unique id of the user this client is connected as. Returns /// None if the connection isn't authenticated. pub async fn user_id(&self) -> Option<u64> { let auth_state = self.data.auth_state.read().await; auth_state.user_id } pub(crate) async fn logged_in_as(&self, user_id: u64, new_permissions: Permissions) { let mut auth_state = self.data.auth_state.write().await; auth_state.user_id = Some(user_id); auth_state.permissions = new_permissions; } pub(crate) async fn set_pending_password_login( &self, user_id: Option<u64>, new_state: ServerLogin, ) { let mut pending_password_login = self.data.pending_password_login.lock().await; *pending_password_login = Some((user_id, new_state)); } pub(crate) async fn take_pending_password_login(&self) -> Option<(Option<u64>, ServerLogin)> { let mut pending_password_login = self.data.pending_password_login.lock().await; pending_password_login.take() } /// Sends a custom API response to the client. pub fn send( &self, response: <B::CustomApi as CustomApi>::Response, ) -> Result<(), flume::SendError<<B::CustomApi as CustomApi>::Response>> { self.data.response_sender.send(response) } } #[derive(Debug)] pub struct OwnedClient<B: Backend> { client: ConnectedClient<B>, runtime: tokio::runtime::Handle, server: Option<CustomServer<B>>, } impl<B: Backend> OwnedClient<B> { pub(crate) fn new( id: u32, address: SocketAddr, transport: Transport, response_sender: Sender<<B::CustomApi as CustomApi>::Response>, server: CustomServer<B>, ) -> Self { Self { client: ConnectedClient { data: Arc::new(Data { id, address, transport, response_sender, auth_state: RwLock::new(AuthenticationState { permissions: server.data.default_permissions.clone(), user_id: None, }), pending_password_login: Mutex::default(), }), }, runtime: tokio::runtime::Handle::current(), server: Some(server), } } pub fn clone(&self) -> ConnectedClient<B> { self.client.clone() } } impl<B: Backend> Drop for OwnedClient<B> { fn drop(&mut self) { let id = self.client.data.id; let server = self.server.take().unwrap(); self.runtime.spawn(async move { server.disconnect_client(id).await; }); } } impl<B: Backend> Deref for OwnedClient<B> { type Target = ConnectedClient<B>; fn deref(&self) -> &Self::Target { &self.client } }
use std::thread; use std::time::{Duration, SystemTime}; use serde::Deserialize; use warmy::{Res, SimpleKey, Store, StoreOpt}; use warmy::json::Json; #[derive(Debug, Deserialize)] #[serde(rename_all = "snake_case")] struct Dog { name: String, gender: Gender } impl Default for Dog { fn default() -> Self { Dog { name: "Norbert".to_owned(), gender: Gender::Male } } } #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] enum Gender { Female, Male } pub fn run() { // we don’t need a context, so we’re using this mutable reference to unit let ctx = &mut (); let mut store: Store<(), SimpleKey> = Store::new(StoreOpt::default()).expect("store creation"); let resource: Result<Res<Dog>, _> = store.get_by(&SimpleKey::from_path("src/play/warmy/data.json"), ctx, Json); match resource { Ok(dog) => { loop { println!("{:?}", SystemTime::now()); store.sync(ctx); let dog = dog.borrow(); println!("Dog is {} and is a {:?}", dog.name, dog.gender); thread::sleep(Duration::from_millis(1000)); } } Err(e) => eprintln!("{}", e) } }
#![feature(nll, underscore_imports)] extern crate cgmath; extern crate pbrt; use std::sync::{ Arc, Mutex }; use cgmath::{ Deg, Matrix4 }; use pbrt::aggregate::{ BvhAccel, SplitMethod }; use pbrt::camera::{ OrthographicCamera, PerspectiveCamera }; use pbrt::film::Film; use pbrt::filter::TriangleFilter; use pbrt::integrator::{ Integrator, DirectLightingIntegrator, NormalIntegrator, WhittedIntegrator }; use pbrt::integrator::LightStrategy; use pbrt::light::{ Light, PointLight }; use pbrt::material::{ Material, MatteMaterial }; use pbrt::math::{ AnimatedTransform, Transform }; use pbrt::primitive::{ Primitive, GeometricPrimitive }; use pbrt::sampler::StratifiedSampler; use pbrt::scene::Scene; use pbrt::shape::{ ShapeData, Cylinder, Sphere }; use pbrt::spectrum::{ SpectrumType, Spectrum as PbrtSpectrum }; use pbrt::texture::ConstantTexture; use pbrt::prelude::*; use pbrt::camera::*; use pbrt::sampler::*; use pbrt::shape::*; fn ring(transform: Arc<Transform>, material: Box<impl Material + Clone + Send + Sync + 'static>, radius: Float, height: Float) -> (Arc<Primitive + Send>, Arc<Primitive + Send>) { let data = ShapeData::new(transform.clone(), false); let sphere = Sphere::new(radius, -height, height, Deg(float(360.0)), data); let sphere = Arc::new(sphere); let primitive0 = GeometricPrimitive { shape: sphere, material: Some(material.clone()), area_light: None, medium_interface: None, }; let primitive0 = Arc::new(primitive0); let data = ShapeData::new(transform, true); let sphere = Sphere::new(radius - float(0.01), -height, height, Deg(float(360.0)), data); let sphere = Arc::new(sphere); let primitive1 = GeometricPrimitive { shape: sphere, material: Some(material), area_light: None, medium_interface: None, }; let primitive1 = Arc::new(primitive1); (primitive0, primitive1) } fn main() { quadratic(); return; let sphere = { let sphere = { let transform = { let transform = Matrix4::from_translation(Vector3f::new( float(0.0), float(0.0), float(0.0), )); let rot = Matrix4::from_angle_x(Deg(float(0.0))); Arc::new(Transform::new(transform * rot)) }; let data = ShapeData::new(transform, false); let radius = float(0.5); let sphere = Sphere::new(radius, -radius, radius, Deg(float(360.0)), data); Arc::new(sphere) }; let material = { let kd = ConstantTexture::new(Spectrum::from_rgb([ float(0.3), float(0.5), float(0.7), ], SpectrumType::Reflectance)); let kd = Arc::new(kd); let sigma = ConstantTexture::new(0.0); let sigma = Arc::new(sigma); MatteMaterial::new(kd, sigma, None) }; let material = Box::new(material); let primitive = GeometricPrimitive { shape: sphere, material: Some(material), area_light: None, medium_interface: None, }; Arc::new(primitive) }; let transform = { let transform = Matrix4::from_translation(Vector3f::new( float(0.0), float(0.0), float(0.0), )); let rot = Matrix4::from_angle_x(Deg(float(60.0))); Arc::new(Transform::new(transform * rot)) }; let material = { let kd = ConstantTexture::new(Spectrum::from_rgb([ float(0.7), float(0.5), float(0.3), ], SpectrumType::Reflectance)); let kd = Arc::new(kd); let sigma = ConstantTexture::new(0.0); let sigma = Arc::new(sigma); MatteMaterial::new(kd, sigma, None) }; let material = Box::new(material); let sphere_2 = ring(transform, material, float(1.0), float(0.05)); let transform = { let transform = Matrix4::from_translation(Vector3f::new( float(0.0), float(0.0), float(0.0), )); let rot = Matrix4::from_angle_x(Deg(float(100.0))); Arc::new(Transform::new(transform * rot)) }; let material = { let kd = ConstantTexture::new(Spectrum::from_rgb([ float(0.7), float(0.3), float(0.5), ], SpectrumType::Reflectance)); let kd = Arc::new(kd); let sigma = ConstantTexture::new(0.0); let sigma = Arc::new(sigma); MatteMaterial::new(kd, sigma, None) }; let material = Box::new(material); let sphere_3 = ring(transform, material, float(0.8), float(0.05)); let bvh = BvhAccel::new( vec![ sphere, sphere_2.0, // sphere_2.1, sphere_3.0, // sphere_3.1, ], SplitMethod::HLBVH, ); let camera = { let film = { let full_resolution = Point2i::new(512, 512); let crop_window = Bounds2f::new( Point2f::new(float(0.0), float(0.0)), Point2f::new(float(1.0), float(1.0)), ); let filter = TriangleFilter::new(Vector2f::new(float(1.0), float(1.0))); let filter = Box::new(filter); let film = Film::new( full_resolution, crop_window, filter, float(5.0), float(1.0), String::from("test_image"), ); Arc::new(Mutex::new(film)) }; let transform = Matrix4::from_translation(Vector3f::new( float(0.0), float(0.0), float(3.0), )); let rot = Matrix4::from_angle_y(Deg(float(0.0))); let transform = Transform::new(transform * rot); let transform = Arc::new(transform); let transform = AnimatedTransform::new( transform.clone(), float(0.0), transform.clone(), float(1.0), ); let screen_window = Bounds2f::new( Point2f::new(float(-1.0), float(-1.0)), Point2f::new(float(1.0), float(1.0)), ); let camera = PerspectiveCamera::new( transform, screen_window, float(0.0), float(1.0), float(0.0), float(1.0), Deg(float(45.0)), film, None ); camera }; /* CameraSample { p_film: Point2 { x: 375.72485, y: 240.22925 }, p_lens: Point2 { x: 0.5703919, y: 0.93715453 }, time: 0.91514564 } */ let sample = CameraSample { lens: Point2f::new( float(0.5703919), float(0.93715453) ), film: Point2f::new( float(375.72485), float(240.22925) ), time: float(0.91514564), }; let (weight, mut ray) = camera.generate_ray_differential(&sample); if let Some(si) = bvh.intersect(&mut ray) { println!("si == {:#?}", si); } println!("weight == {:?}", weight); println!("ray == {:#?}", ray); let t = Matrix4::from_translation(Vector3f { x: float(-1.3), y: float(0.0), z: float(0.0), }); let t = Transform::new(t); let o: Point3f = Point3f { x: float(2.0), y: float(1.99999988), z: float(4.99999905), }; let d: Vector3f = Vector3f { x: float(-0.0607556403), y: float(-0.164096087), z: float(-0.984571517), }; let r: Ray = Ray { origin: o, direction: d, max: Float::infinity(), time: float(0.0), medium: None, }; let (r, o, d) = t.transform_ray_with_error(r); println!("{:#?}", r); println!("{:?}", o); println!("{:?}", d); } fn quadratic() { let sphere = { let transform = { let transform = Matrix4::from_translation(Vector3f::new( float(0.0), float(0.0), float(0.0), )); let rot = Matrix4::from_angle_x(Deg(float(0.0))); Arc::new(Transform::new(transform * rot)) }; let data = ShapeData::new(transform, false); let radius = float(1.0); let sphere = Sphere::new(radius, -radius, float(0.0), Deg(float(360.0)), data); sphere }; let ray = Ray { origin: Point3f::new( float(0.0), float(0.0), float(3.0), ), direction: Vector3f::new( float(0.0), float(0.0), float(-1.0), ), max: Float::infinity(), time: float(0.0), medium: None, }; if let Some((f, si)) = sphere.intersect(&ray, true) { println!("f == {:?}", f); println!("si == {:#?}", si); } }
//! File attribute wrappers use fuse; use std::cell::RefCell; use std::path::{Path, PathBuf}; use std::usize; use time::{self, Timespec}; /// Describes a type that can be attributed pub trait Content { fn name(&self) -> &str; fn size(&self) -> usize; } /// Tags content as being either a file or a directory. /// Node is an implementation detail of Attributed enum Node<C> { Directory { full_path: PathBuf }, File { full_path: PathBuf, content: C }, } /// Permissions and user / group IDs pub struct Access { /// Permissions pub perm: u16, /// User ID pub uid: u32, /// Group ID pub gid: u32, } impl Default for Access { #[cfg(target_os = "macos")] fn default() -> Access { Access { perm: 0o755, uid: 501, gid: 20, } } #[cfg(not(target_os = "macos"))] fn default() -> Access { Access { perm: 0o755, uid: 1000, gid: 1000, } } } /// All times for files and directories #[derive(Debug, PartialEq, Clone)] pub struct Times { /// Last access pub atime: Timespec, /// Last modification pub mtime: Timespec, /// Last change pub ctime: Timespec, /// Creation time #[cfg(target_os = "macos")] pub crtime: Timespec, } impl Times { /// Create a Times with all members set to now fn now() -> Times { let now = time::now_utc().to_timespec(); #[cfg(target_os = "macos")] { Times { atime: now, mtime: now, ctime: now, crtime: now, } } #[cfg(not(target_os = "macos"))] { Times { atime: now, mtime: now, ctime: now, } } } } /// Attributed wrap some kind of content `C` /// to automatically control other filesystem /// attributes. pub struct Attributed<C: Content> { /// Inode number ino: u64, /// Times related to access, modification, and change times: RefCell<Times>, /// Permissions and groups access: Access, /// The content content: Node<C>, } impl<C: Content> Attributed<C> { /// Implementation of new fn new(ino: u64, content: Node<C>) -> Attributed<C> { Attributed { ino, times: RefCell::new(Times::now()), access: Access::default(), content, } } /// Create a new file pub fn new_file<P: AsRef<Path>>(ino: u64, path: P, content: C) -> Attributed<C> { let mut path = PathBuf::from(path.as_ref()); path.push(content.name()); Attributed::new( ino, Node::File { full_path: path, content, }, ) } /// Create a new directory pub fn new_directory<P: AsRef<Path>>(ino: u64, path: P) -> Attributed<C> { Attributed::new( ino, Node::Directory { full_path: PathBuf::from(path.as_ref()), }, ) } /// Get the inode number pub fn ino(&self) -> u64 { self.ino } /// Return the size of this attributed content fn size(&self) -> usize { match self.content { Node::Directory { .. } => 0, Node::File { ref content, .. } => content.size(), } } /// Get a reference to the content /// /// Consider using access to maintain access times. pub fn get_ref(&self) -> Option<&C> { match self.content { Node::File { ref content, .. } => Some(&content), _ => None, } } /// Return the path of this attributed content pub fn path(&self) -> &Path { match self.content { Node::Directory { ref full_path } | Node::File { ref full_path, .. } => full_path, } } /// Returns the name of the content, if it exists. Notably, a root /// directory `"/"` has no name and returns `None`. pub fn name(&self) -> Option<&str> { match self.content { Node::Directory { ref full_path } => full_path.file_name().and_then(|os| os.to_str()), Node::File { ref content, .. } => Some(content.name()), } } /// Access the underlying content, performing /// side effects to update the access time on success. /// Returns `None` if the underlying content is a directory. pub fn access<'a, F, R: 'a, E: 'a>(&'a self, accessor: F) -> Option<Result<R, E>> where F: FnOnce(&'a C) -> Result<R, E>, { match self.content { Node::File { ref content, .. } => { let ret = accessor(content); if ret.is_ok() { let now = time::now_utc().to_timespec(); self.times.borrow_mut().atime = now; } Some(ret) } _ => None, } } /// Modify the underlying content, performing side /// effects to update the modification time on success. /// Returns `None` if the underlying content is a directory pub fn modify<'a, F, R: 'a, E: 'a>(&'a mut self, modifier: F) -> Option<Result<R, E>> where F: FnOnce(&'a mut C) -> Result<R, E>, { match self.content { Node::File { ref mut content, .. } => { let ret = modifier(content); if ret.is_ok() { let now = time::now_utc().to_timespec(); self.times.borrow_mut().mtime = now; } Some(ret) } _ => None, } } /// Get a mutable reference to the access attributes #[allow(dead_code)] pub fn change<F>(&mut self, changer: F) where F: FnOnce(&mut Access, &mut Times), { changer(&mut self.access, &mut self.times.borrow_mut()); let now = time::now_utc().to_timespec(); self.times.borrow_mut().ctime = now; } /// Return creation time, macOS only #[cfg(target_os = "macos")] #[inline] fn crtime(&self) -> Timespec { self.times.borrow().crtime } /// Return creation time for any other OS #[cfg(not(target_os = "macos"))] #[inline] fn crtime(&self) -> Timespec { Timespec::new(1, 0) } /// Convert into a FUSE file attribute pub fn as_fuse_attr(&self) -> fuse::FileAttr { fuse::FileAttr { ino: self.ino, size: self.size() as u64, blocks: 1, // TODO figure out if this is right atime: self.times.borrow().atime, mtime: self.times.borrow().mtime, ctime: self.times.borrow().ctime, crtime: self.crtime(), kind: match self.content { Node::File { .. } => fuse::FileType::RegularFile, Node::Directory { .. } => fuse::FileType::Directory, }, perm: self.access.perm, uid: self.access.uid, gid: self.access.gid, // TODO address how these are handled nlink: 0, rdev: 0, flags: 0, } } } #[cfg(test)] mod tests { use super::Access; use super::Attributed; use super::Content; use fuse::FileType; use std::path::PathBuf; struct TestContent { name: String, size: usize, } impl Content for TestContent { fn name(&self) -> &str { &self.name } fn size(&self) -> usize { self.size } } type TestResult = Result<(), ()>; #[test] fn as_fuse_attr_directory() { let attr = Attributed::<TestContent>::new_directory(1, "/"); let fattr = attr.as_fuse_attr(); assert_eq!(fattr.ino, 1); assert_eq!(fattr.size, 0); assert_eq!(fattr.blocks, 1); assert_eq!(fattr.kind, FileType::Directory); let access = Access::default(); assert_eq!(fattr.perm, access.perm); assert_eq!(fattr.uid, access.uid); assert_eq!(fattr.gid, access.gid); } #[test] fn as_fuse_attr_file() { let attr = Attributed::new_file( 1, "/", TestContent { name: String::from("foo"), size: 314, }, ); let fattr = attr.as_fuse_attr(); assert_eq!(fattr.ino, 1); assert_eq!(fattr.size, 314); assert_eq!(fattr.blocks, 1); assert_eq!(fattr.kind, FileType::RegularFile); let access = Access::default(); assert_eq!(fattr.perm, access.perm); assert_eq!(fattr.uid, access.uid); assert_eq!(fattr.gid, access.gid); } #[test] fn dir_name_size() { let attr = Attributed::<TestContent>::new_directory(1, "/foo"); assert_eq!(attr.name().unwrap(), "foo"); assert_eq!(attr.size(), 0); } #[test] fn file_name_size() { let attr = Attributed::new_file( 2, "/", TestContent { name: String::from("foo"), size: 22, }, ); assert_eq!(attr.name().unwrap(), "foo"); assert_eq!(attr.size(), 22); } #[allow(unreachable_code)] // panic blocks return of Err, but result is needed for typing #[test] fn dir_access_always_none() { let attr = Attributed::<TestContent>::new_directory(1, "/"); let times = attr.times.clone(); assert!(attr.access(|_| { panic!("should never be called"); Err(()) as TestResult }).is_none()); assert_eq!(times, attr.times); } #[test] fn path_for_directory() { let attr = Attributed::<TestContent>::new_directory(1, "/foo/bar"); assert_eq!(attr.path(), PathBuf::from("/foo/bar")); } #[test] fn path_for_file() { let attr = Attributed::new_file( 2, "/foo/bar", TestContent { name: String::from("bang"), size: 22, }, ); assert_eq!(attr.path(), PathBuf::from("/foo/bar/bang")); } #[test] fn name_for_directory_empty_root() { let attr = Attributed::<TestContent>::new_directory(1, "/"); assert!(attr.name().is_none()); } #[test] fn name_for_directory() { let attr = Attributed::<TestContent>::new_directory(1, "/foo"); assert_eq!(attr.name(), Some("foo")); } #[test] fn name_for_file() { let attr = Attributed::new_file( 2, "/foo/bar", TestContent { name: String::from("bang"), size: 22, }, ); assert_eq!(attr.name(), Some("bang")); } // Note that these tests relies on nondeterministic time tracking // behavior. TODO refactor Attributed to accept a controllable // time source. #[test] fn file_access_ok() { let attr = Attributed::new_file( 2, "/", TestContent { name: String::from("foo"), size: 33, }, ); let mtime = attr.times.borrow().mtime; let atime = attr.times.borrow().atime; let ctime = attr.times.borrow().ctime; assert!( attr.access(|tc| { assert_eq!(tc.name, String::from("foo")); assert_eq!(tc.size, 33); Ok(()) as TestResult }).unwrap() .is_ok() ); assert!(attr.times.borrow().mtime == mtime); assert!(attr.times.borrow().atime > atime); assert!(attr.times.borrow().ctime == ctime); } #[test] fn file_access_err() { let attr = Attributed::new_file( 2, "/", TestContent { name: String::from("foo"), size: 33, }, ); let mtime = attr.times.borrow().mtime; let atime = attr.times.borrow().atime; let ctime = attr.times.borrow().ctime; assert!( attr.access(|tc| { assert_eq!(tc.name, String::from("foo")); assert_eq!(tc.size, 33); Err(()) as TestResult }).unwrap() .is_err() ); assert!(attr.times.borrow().mtime == mtime); assert!(attr.times.borrow().atime == atime); assert!(attr.times.borrow().ctime == ctime); } #[test] fn file_modify_ok() { let mut attr = Attributed::new_file( 2, "/", TestContent { name: String::from("foo"), size: 33, }, ); let mtime = attr.times.borrow().mtime; let atime = attr.times.borrow().atime; let ctime = attr.times.borrow().ctime; assert!( attr.modify(|tc| { assert_eq!(tc.name, String::from("foo")); assert_eq!(tc.size, 33); tc.size = 34; Ok(()) as TestResult }).unwrap() .is_ok() ); assert!(attr.times.borrow().mtime > mtime); assert!(attr.times.borrow().atime == atime); assert!(attr.times.borrow().ctime == ctime); assert!(attr.access(|tc| { assert_eq!(tc.size, 34); Ok(()) as TestResult }).is_some()); } #[test] fn file_modify_err() { let mut attr = Attributed::new_file( 2, "/", TestContent { name: String::from("foo"), size: 33, }, ); let mtime = attr.times.borrow().mtime; let atime = attr.times.borrow().atime; let ctime = attr.times.borrow().ctime; assert!( attr.modify(|tc| { assert_eq!(tc.name, String::from("foo")); assert_eq!(tc.size, 33); tc.size = 34; Err(()) as TestResult }).unwrap() .is_err() ); assert!(attr.times.borrow().mtime == mtime); assert!(attr.times.borrow().atime == atime); assert!(attr.times.borrow().ctime == ctime); } }
use core::pos::BiPos; #[repr(u8)] #[derive(Debug, PartialEq, Clone, Copy, Hash, Eq)] pub enum TokenType { LParen, RParen, LCurly, RCurly, LBracket, RBracket, QMark, Hyphen, Comma, Dot, Semicolon, Pipe, Plus, Minus, Star, Slash, Backslash, Underscore, And, Caret, Tick, Bang, Equal, Colon, Apost, Quote, RAngle, LAngle, Percent, Dollar, Hash, At, Identifier, String, Number, Decimal, KwVal, KwVar, KwFun, KwLet, KwMut, KwStruct, KwReturn, KwMod, KwNative, KwPublic, KwIf, KwElse, KwLoop, KwWhile, KwFor, KwBreak, KwContinue, KwTrue, KwFalse, KwNull, KwNone, KwAs, KwWith, Err, Eof, } #[derive(Debug, Clone)] pub enum TokenData { None, Integer(i32), Float(f32), String(String), } #[derive(Debug, Clone)] pub struct LexerToken{ pub type_: TokenType, pub data: TokenData, pub pos: BiPos, } impl Default for LexerToken { fn default() -> Self { LexerToken { type_: TokenType::Eof, data: TokenData::None, pos: BiPos::default(), } } } impl std::fmt::Display for LexerToken{ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?},\n\t{:?},\n\t{}", self.type_, self.data, self.pos) } }
#![allow(dead_code,unused_variables, unused_mut)] extern crate x11; extern crate libc; extern crate futures; mod display; pub use display::Display; mod error; pub use error::XError; mod window; pub use window::Window; pub use x11::xlib::{ XMapEvent, XDestroyWindowEvent, XConfigureEvent, XUnmapEvent, XPropertyEvent, XButtonEvent, XKeyEvent, ButtonPressMask, FocusChangeMask, Mod1Mask, Mod2Mask, Mod3Mask, Mod4Mask, EnterWindowMask, LeaveWindowMask, ControlMask, KeyPressMask, KeyReleaseMask, ButtonReleaseMask, PropertyChangeMask, SubstructureRedirectMask, SubstructureNotifyMask, PointerMotionMask, XWindowChanges, XWMHints }; pub use x11::xlib::XEvent as RawXEvent; mod event; pub use event::Event; #[derive(Debug, PartialEq, Eq)] pub enum EventType { KeyPress = 2, ButtonPress = 4, ButtonRelease = 5, MotionNotify = 6, EnterNotify = 7, LeaveNotify = 8, DestroyNotify = 17, UnmapNotify = 18, MapRequest = 20, ConfigureRequest = 23, PropertyNotify = 28, ClientMessage = 33 } macro_rules! impl_from_intiger { ($ty:ty) => { impl From<$ty> for EventType { fn from(f: $ty) -> EventType { match f { 2 => EventType::KeyPress, 4 => EventType::ButtonPress, 5 => EventType::ButtonRelease, 6 => EventType::MotionNotify, 7 => EventType::EnterNotify, 8 => EventType::LeaveNotify, 17 => EventType::DestroyNotify, 18 => EventType::UnmapNotify, 20 => EventType::MapRequest, 23 => EventType::ConfigureRequest, 28 => EventType::PropertyNotify, 33 => EventType::ClientMessage, _ => panic!("Unkown Event Type") } } } } } impl_from_intiger!(i64); impl_from_intiger!(u64); impl_from_intiger!(i32); impl_from_intiger!(u32); impl_from_intiger!(i16); impl_from_intiger!(u16); impl_from_intiger!(i8); impl_from_intiger!(u8); #[cfg(test)] mod tests { #[test] fn it_works() { } }
use std::io::{Write}; use parser::html; use parser::html::Expression as Expr; use parser::html::Statement as Stmt; use parser::html::{Fmt}; use parser::html::Statement::{Element, Store, Condition, Output}; use parser::{Ast, Block}; use super::ast::{Code, Statement, Param, Expression}; use super::Generator; fn key_num(sup: &Option<Expression>, sub: usize) -> Option<Expression> { sup.as_ref().map(|k| { Expression::Add( Box::new(k.clone()), Box::new(Expression::Str(format!(":{}", sub)))) }) } fn key_join(sup: Option<Expression>, sub: &String) -> Expression { sup.map(|k| { Expression::Add( Box::new(Expression::Add( Box::new(k), Box::new(Expression::Str(String::from(":"))))), Box::new(Expression::Name(sub.clone()))) }).unwrap_or(Expression::Name(sub.clone())) } impl<'a, W:Write+'a> Generator<'a, W> { pub fn compile_expr(&self, expr: &Expr) -> Expression { match expr { &Expr::Name(ref name) => Expression::Name(name.clone()), &Expr::Str(ref value) => Expression::Str(value.clone()), // TODO(tailhook) validate numeric suffixes &Expr::Num(ref value) => Expression::Num(value.clone()), &Expr::New(ref expr) => Expression::New(Box::new(self.compile_expr(expr))), &Expr::Not(ref expr) => Expression::Not(Box::new(self.compile_expr(expr))), &Expr::And(ref a, ref b) => Expression::And(Box::new(self.compile_expr(a)), Box::new(self.compile_expr(b))), &Expr::Or(ref a, ref b) => Expression::Or(Box::new(self.compile_expr(a)), Box::new(self.compile_expr(b))), &Expr::Attr(ref expr, ref value) => Expression::Attr(Box::new(self.compile_expr(expr)), value.clone()), &Expr::Item(ref expr, ref item) => Expression::Item(Box::new(self.compile_expr(expr)), Box::new(self.compile_expr(item))), &Expr::Call(ref expr, ref args) => Expression::Call(Box::new(self.compile_expr(expr)), args.iter().map(|x| self.compile_expr(x)).collect()), &Expr::Add(ref a, ref b) => Expression::Add(Box::new(self.compile_expr(a)), Box::new(self.compile_expr(b))), &Expr::Sub(ref a, ref b) => Expression::Sub(Box::new(self.compile_expr(a)), Box::new(self.compile_expr(b))), &Expr::Mul(ref a, ref b) => Expression::Mul(Box::new(self.compile_expr(a)), Box::new(self.compile_expr(b))), &Expr::Div(ref a, ref b) => Expression::Div(Box::new(self.compile_expr(a)), Box::new(self.compile_expr(b))), &Expr::Comparison(op, ref a, ref b) => Expression::Comparison(op, Box::new(self.compile_expr(a)), Box::new(self.compile_expr(b))), &Expr::Format(ref value) => { self.compile_format(value) } &Expr::Dict(ref items) => Expression::Object(items.iter() .map(|&(ref name, ref expr)| (name.clone(), self.compile_expr(expr))) .collect()), &Expr::List(ref items) => Expression::List(items.iter() .map(|expr| self.compile_expr(expr)) .collect()), } } fn compile_format(&self, items: &Vec<Fmt>) -> Expression { let mut exprs = items.iter().map(|e| match e { &Fmt::Raw(ref x) => Expression::Str(x.clone()), &Fmt::Str(ref e) => Expression::Call( Box::new(Expression::Name(String::from("String"))), vec![self.compile_expr(e)]), &Fmt::Int(ref e) => Expression::Call( Box::new(Expression::Name(String::from("String"))), vec![self.compile_expr(e)]), &Fmt::Float(ref e, _) => Expression::Call( Box::new(Expression::Name(String::from("String"))), vec![self.compile_expr(e)]), }).collect::<Vec<_>>(); let first = exprs.remove(0); exprs.into_iter().fold(first, |acc, item| { Expression::Add(Box::new(acc), Box::new(item)) }) } fn statement(&self, st: &html::Statement, key: Option<Expression>) -> Expression { match st { &Element { ref name, ref classes, ref body, ref attributes } => { self.element(name, classes, attributes, key, body) } &Stmt::Format(ref value) => { self.compile_format(value) } &Output(ref expr) => { // TODO(tailhook) maybe put key somehow too? self.compile_expr(expr) } &Condition(ref conditions, ref fallback) => { // TODO(tailhook) maybe key should have if branch appended conditions.iter().enumerate().rev() .fold(fallback.as_ref() .map(|x| self.fragment(x, key_num(&key, conditions.len()))) .unwrap_or(Expression::Str(String::new())), |old, (idx, &(ref cond, ref value))| Expression::Ternary( // TODO(tailhook) maybe put key somehow too? Box::new(self.compile_expr(cond)), Box::new(self.fragment(value, key_num(&key, idx))), Box::new(old), )) } &Stmt::ForOf(ref name, ref expr, ref subkey, ref body) => { let expr = self.compile_expr(expr); Expression::Call( Box::new(Expression::Attr( Box::new(expr), String::from("map"))), vec![Expression::Function(None, vec![Param {name: name.clone(), default_value: None}], vec![Statement::Return(self.fragment(body, Some(subkey.as_ref().map(|x| self.compile_expr(&x)) .unwrap_or(key_join(key, name)))))] )]) } &Stmt::Store(_, _) => unreachable!(), // not an actual child &Stmt::Link(_) => unreachable!(), // not an actual child &Stmt::Let(_, _) => unreachable!(), // not an actual child } } pub fn fragment(&self, statements: &Vec<html::Statement>, key: Option<Expression>) -> Expression { let stmt = statements.iter().filter(|x| match x { &&Stmt::Store(_, _) | &&Stmt::Link(_) | &&Stmt::Let(_, _) => false, _ => true, }).collect::<Vec<_>>(); if stmt.len() == 1 { return self.statement(&stmt[0], key); } else { let mut obj = vec![( String::from("children"), Expression::List( stmt.iter() .map(|s| self.statement(s, None)) .collect()) )]; if let Some(x) = key { obj.insert(0, (String::from("key"), x)); } return Expression::Object(obj); } } pub fn code(&self, ast: &Ast) -> Code { let mut stmt = vec!(); for blk in ast.blocks.iter() { if let &Block::Html {ref name, ref params, ref statements, .. } = blk { stmt.push(Statement::Function(name.clone(), params.iter().map(|p| Param { name: p.name.clone(), default_value: p.default_value.as_ref().map( |v| Expression::Str(v.clone())), }).collect(), vec![ Statement::Return(self.fragment(statements, Some(Expression::Str(format!("{}:{}", self.block_name, name))))), ] )); } } return Code { statements: stmt, } } }
//! For making notable symbols and words out of text. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Operator { Plus, Minus, Star, Slash, Percent, Caret, LParen, RParen, Pipe, Equals, Factorial, } use self::Operator::*; #[derive(Debug, Clone, PartialEq)] pub enum Token<'a, T> { Number(T), Operator(Operator), Identifier(&'a str), } /// # Error Lookup Table /// | Error ID | Description | /// |------------------|-------------------------------------------------------------------------------------------------------| /// | InvalidCharacter | If the input contains any characters not recognized by the lexer to be numbers or characters, ex: 'ƒ' | /// | InvalidNumber | A number entered invalidly: '2.34.2' or '..3' | #[derive(Debug, Clone, PartialEq)] pub enum LexerError { InvalidCharacter(char), InvalidNumber(String), } /// Turn a string into a vector of tokens. This function generally takes the most time, /// compared to parsing and computing. It is best to run this function as few times as /// reasonably possible. /// ``` /// use rsc::tokenize; /// let tokens = tokenize("2 + 2").unwrap(); /// assert_eq!(tokens.as_slice(), &[Token::Number(2.0), Token::Operator(Operator::Plus), Token::Number(2.0)]); /// ``` pub fn tokenize<'a, T>(src: &'a str) -> Result<Vec<Token<'a, T>>, LexerError> where T: std::str::FromStr, { let mut tokens = Vec::<Token<T>>::new(); let mut chars = src.chars().enumerate().peekable(); while let Some((i, c)) = chars.next() { match c { '+' => tokens.push(Token::Operator(Plus)), '-' => tokens.push(Token::Operator(Minus)), '*' => tokens.push(Token::Operator(Star)), '/' => tokens.push(Token::Operator(Slash)), '%' => tokens.push(Token::Operator(Percent)), '^' => tokens.push(Token::Operator(Caret)), '(' => tokens.push(Token::Operator(LParen)), ')' => tokens.push(Token::Operator(RParen)), '|' => tokens.push(Token::Operator(Pipe)), '=' => tokens.push(Token::Operator(Equals)), '!' => tokens.push(Token::Operator(Factorial)), _ => { if c.is_whitespace() { continue; } else if c.is_digit(10) || c == '.' { let start_idx = i; let mut end_idx = i; while let Some((_, c)) = chars.peek() { if c.is_digit(10) || c == &'.' { chars.next(); // consume the character end_idx += 1; } else { break; } } match (&src[start_idx..=end_idx]).parse::<T>() { Ok(num) => tokens.push(Token::Number(num)), _ => return Err(LexerError::InvalidNumber(src[start_idx..=end_idx].to_owned())), } } else if c.is_alphabetic() { let start_idx = i; let mut end_idx = i; while let Some((_, c)) = chars.peek() { if c.is_alphabetic() || c == &'_' { chars.next(); end_idx += 1; } else { break; } } tokens.push(Token::Identifier(&src[start_idx..=end_idx])); } else { return Err(LexerError::InvalidCharacter(c)); } } } } Ok(tokens) }
#![allow( clippy::len_without_is_empty, // Types that are non-empty by construction do not need is_empty method )] pub mod encoder; pub mod headers; pub mod frame; pub mod rice; mod writer; pub use writer::{FrameWriter, HeaderWriter}; pub const SMALL: bool = true; pub const BLOCK_SIZE: u16 = if SMALL { 192 } else { 4096 };
use ckb_chain_spec::consensus::Consensus; use ckb_core::block::Block; use ckb_core::cell::{CellProvider, CellStatus}; use ckb_core::extras::{BlockExt, EpochExt}; use ckb_core::header::{BlockNumber, Header}; use ckb_core::transaction::{OutPoint, ProposalShortId, Transaction}; use ckb_core::uncle::UncleBlock; use ckb_db::MemoryKeyValueDB; use ckb_script::ScriptConfig; use ckb_store::ChainKVStore; use ckb_traits::ChainProvider; use numext_fixed_hash::H256; use std::sync::Arc; #[derive(Clone)] pub struct DummyChainProvider {} impl ChainProvider for DummyChainProvider { type Store = ChainKVStore<MemoryKeyValueDB>; fn store(&self) -> &Arc<ChainKVStore<MemoryKeyValueDB>> { unimplemented!(); } fn script_config(&self) -> &ScriptConfig { unimplemented!(); } fn block_ext(&self, _hash: &H256) -> Option<BlockExt> { unimplemented!(); } fn genesis_hash(&self) -> &H256 { unimplemented!(); } fn block_body(&self, _hash: &H256) -> Option<Vec<Transaction>> { unimplemented!(); } fn block_header(&self, _hash: &H256) -> Option<Header> { unimplemented!(); } fn block_proposal_txs_ids(&self, _hash: &H256) -> Option<Vec<ProposalShortId>> { unimplemented!(); } fn block_hash(&self, _height: u64) -> Option<H256> { unimplemented!(); } fn get_ancestor(&self, _base: &H256, _number: BlockNumber) -> Option<Header> { unimplemented!(); } fn block_number(&self, _hash: &H256) -> Option<BlockNumber> { unimplemented!(); } fn uncles(&self, _hash: &H256) -> Option<Vec<UncleBlock>> { unimplemented!(); } fn block(&self, _hash: &H256) -> Option<Block> { unimplemented!(); } fn get_transaction(&self, _hash: &H256) -> Option<(Transaction, H256)> { unimplemented!(); } fn get_block_epoch(&self, _hash: &H256) -> Option<EpochExt> { unimplemented!(); } fn next_epoch_ext(&self, _last_epoch: &EpochExt, _header: &Header) -> Option<EpochExt> { unimplemented!(); } fn consensus(&self) -> &Consensus { unimplemented!(); } } impl CellProvider for DummyChainProvider { fn cell(&self, _o: &OutPoint) -> CellStatus { unimplemented!(); } }
use super::*; use crate::error::{NodeError, NodeErrorKind}; use poa::engines::authority_round::RollingFinality; use rand::Rng; use sha2::{Digest, Sha256}; use std::collections::HashSet; use std::fs::{create_dir_all, File}; use std::io::{ErrorKind, Read, Seek, Write}; use std::path::PathBuf; use ton_block::{InMsg, OutMsg, AccountStatus, ExtOutMessageHeader, MsgEnvelope}; use ton_block::{HashmapAugType, BlkPrevInfo, Deserializable, ShardIdent}; use ton_types::{UInt256, deserialize_tree_of_cells, BagOfCells}; #[cfg(test)] #[path = "../../../tonos-se-tests/unit/test_block_finality.rs"] mod tests; /// Structure for Block finality layer /// This realize next functionality: /// Store block received from POA /// Finalize block witch POA finality - store to permanent storage /// Store (in memory) current shard-state for every block-candidate /// Get current shard-state /// Get last block by number or hash /// Rollback block (and shardstate) if block is rolled #[allow(dead_code)] pub struct OrdinaryBlockFinality<S, B, T, F> where S: ShardStateStorage, B: BlocksStorage, T: TransactionsStorage, F: FinalityStorage { shard_ident: ShardIdent, root_path: PathBuf, shard_state_storage: Arc<S>, blocks_storage: Arc<B>, tr_storage: Arc<T>, fn_storage: Arc<F>, db: Option<Arc<Box<dyn DocumentsDb>>>, pub finality: RollingFinality, current_block: Box<ShardBlock>, blocks_by_hash: HashMap<UInt256, Box<FinalityBlock>>, blocks_by_no: HashMap<u64, Box<FinalityBlock>>, last_finalized_block: Box<ShardBlock>, } fn key_by_seqno(seq_no: u32, vert_seq_no: u32) -> u64 { ((vert_seq_no as u64) << 32) | (seq_no as u64) } impl <S, B, T, F> OrdinaryBlockFinality<S, B, T, F> where S: ShardStateStorage, B: BlocksStorage, T: TransactionsStorage, F: FinalityStorage { /// Create new instance BlockFinality /// wtih all kind of storages pub fn with_params( shard_ident: ShardIdent, root_path: PathBuf, shard_state_storage: Arc<S>, blocks_storage: Arc<B>, tr_storage: Arc<T>, fn_storage: Arc<F>, db: Option<Arc<Box<dyn DocumentsDb>>>, public_keys: Vec<ed25519_dalek::PublicKey> ) -> Self { let root_path = FileBasedStorage::create_workchains_dir(&root_path) .expect("cannot create shardes directory"); OrdinaryBlockFinality { shard_ident, root_path, shard_state_storage, blocks_storage, tr_storage, fn_storage, db, finality: RollingFinality::blank(public_keys), current_block: Box::new(ShardBlock::default()), blocks_by_hash: HashMap::new(), blocks_by_no: HashMap::new(), last_finalized_block: Box::new(ShardBlock::default()), } } fn finality_blocks(&mut self, hashes: Vec<UInt256>, is_sync: bool) -> NodeResult<()> { debug!("FINBLK {:?}", hashes); for hash in hashes.iter() { if self.blocks_by_hash.contains_key(&hash) { let fin_sb = self.blocks_by_hash.remove(&hash).unwrap(); let sb = self.stored_to_loaded(fin_sb)?; // create shardstateinfo let info = sb.block.block().read_info()?; let shard_info = ShardStateInfo { seq_no: key_by_seqno(info.seq_no(), info.vert_seq_no()), lt: info.end_lt(), hash: sb.block_hash.clone(), }; let mut shard = vec![]; BagOfCells::with_root(&sb.shard_state.serialize()?) .write_to(&mut shard, false)?; // save shard state self.shard_state_storage.save_serialized_shardstate_ex( &ShardStateUnsplit::default(), Some(shard), &sb.block.block().read_state_update()?.new_hash, shard_info )?; // save finalized block self.blocks_storage.save_raw_block(&sb.block, Some(&sb.serialized_block))?; // remove shard-block from number hashmap self.blocks_by_no.remove(&sb.seq_no).expect("block by number remove error"); // remove old_last_finality block from finality storage self.remove_form_finality_storage(&self.last_finalized_block.block_hash)?; let res = self.reflect_block_in_db( sb.block.block().clone(), sb.shard_state.clone(), is_sync, ); if res.is_err() { warn!(target: "node", "reflect_block_in_db(Finalized) error: {:?}", res.unwrap_err()); } self.last_finalized_block = sb; info!(target: "node", "FINALITY:save block seq_no: {:?}, serialized len = {}", self.last_finalized_block.block.block().read_info()?.seq_no(), self.last_finalized_block.serialized_block.len() ); } else { if hash != &UInt256::from([0;32]) && hash != &self.last_finalized_block.block_hash { warn!(target: "node", "Can`t finality unknown hash!!!"); return node_err!(NodeErrorKind::FinalityError) } } } Ok(()) } fn stored_to_loaded(&self, fin_sb: Box<FinalityBlock> ) -> NodeResult<Box<ShardBlock>> { Ok(match *fin_sb { FinalityBlock::Stored(sb_hash) => { // load sb let (shard_path, _blocks_path, _tr_dir) = FileBasedStorage::create_default_shard_catalog(self.root_path.clone(), &self.shard_ident)?; let mut block_sb_path = shard_path.clone(); block_sb_path.push("block_finality"); if !block_sb_path.as_path().exists() { create_dir_all(block_sb_path.as_path())?; } block_sb_path.push(sb_hash.block_hash.to_hex_string()); self.read_one_sb_from_file(block_sb_path)? }, FinalityBlock::Loaded(l_sb) => { l_sb } }) } pub fn save_rolling_finality(&self) -> NodeResult<()> { // save to disk let (mut finality_file_name, _blocks_path, _tr_dir) = FileBasedStorage::create_default_shard_catalog(self.root_path.clone(), &self.shard_ident)?; finality_file_name.push("rolling_finality.info"); self.finality.save(finality_file_name.to_str().expect("Can`t get rolling finality file name."))?; Ok(()) } fn remove_form_finality_storage(&self, hash: &UInt256) -> NodeResult<()>{ let (shard_path, _blocks_path, _tr_dir) = FileBasedStorage::create_default_shard_catalog(self.root_path.clone(), &self.shard_ident)?; let mut block_finality_path = shard_path.clone(); block_finality_path.push("block_finality"); if !block_finality_path.as_path().exists() { create_dir_all(block_finality_path.as_path())?; } let mut name = block_finality_path.clone(); name.push(hash.to_hex_string()); if name.as_path().exists() { std::fs::remove_file(name)?; } Ok(()) } fn save_one(sb: Box<ShardBlock>, file_name: PathBuf) -> NodeResult<()> { let mut file_info = File::create(file_name)?; let mut data = sb.serialize()?; file_info.write_all(&mut data[..])?; file_info.flush()?; Ok(()) } pub fn save_finality(&self) -> NodeResult<()> { let (shard_path, _blocks_path, _tr_dir) = FileBasedStorage::create_default_shard_catalog(self.root_path.clone(), &self.shard_ident)?; let mut block_finality_path = shard_path.clone(); block_finality_path.push("block_finality"); if !block_finality_path.as_path().exists() { create_dir_all(block_finality_path.as_path())?; } let mut name = block_finality_path.clone(); name.push(self.current_block.block_hash.to_hex_string()); if !name.as_path().exists() { Self::save_one(self.current_block.clone(), name)?; } let mut name = block_finality_path.clone(); name.push(self.last_finalized_block.block_hash.to_hex_string()); if !name.as_path().exists() { Self::save_one(self.last_finalized_block.clone(), name)?; } self.save_index()?; Ok(()) } fn save_index(&self) -> NodeResult<()> { let (mut shard_path, _blocks_path, _tr_dir) = FileBasedStorage::create_default_shard_catalog(self.root_path.clone(), &self.shard_ident)?; shard_path.push("blocks_finality.info"); let mut file_info = File::create(shard_path)?; self.serialize(&mut file_info)?; file_info.flush()?; self.save_rolling_finality()?; Ok(()) } /// /// Load from disk /// pub fn load(&mut self) -> NodeResult<()> { let (mut shard_path, _blocks_path, _tr_dir) = FileBasedStorage::create_default_shard_catalog(self.root_path.clone(), &self.shard_ident)?; let mut finality_file_name = shard_path.clone(); shard_path.push("blocks_finality.info"); info!(target: "node", "load: {}", shard_path.to_str().unwrap()); let mut file_info = File::open(shard_path)?; self.deserialize(&mut file_info)?; finality_file_name.push("rolling_finality.info"); info!(target: "node", "load: {}", finality_file_name.to_str().unwrap()); self.finality.load(finality_file_name.to_str().expect("Can`t get rolling finality file name."))?; Ok(()) } /// /// Write data BlockFinality to file /// fn serialize(&self, writer: &mut dyn Write) -> NodeResult<()> { // serialize struct: // 32bit - length of structure ShardBlock // structure ShardBlock // ... // first save current block writer.write_all(self.current_block.block_hash.as_slice())?; writer.write_all(&self.current_block.seq_no.to_le_bytes())?; // save last finality block writer.write_all(self.last_finalized_block.block_hash.as_slice())?; writer.write_all(&self.last_finalized_block.seq_no.to_le_bytes())?; for (key, sb) in self.blocks_by_hash.iter() { writer.write_all(key.as_slice())?; writer.write_all(&sb.seq_no().to_le_bytes())?; } Ok(()) } fn read_one_sb_hash<R>(&self, rdr: &mut R) -> NodeResult<(u64, UInt256)> where R: Read + Seek { // first read current block let hash = rdr.read_u256()?; let seq_no = rdr.read_le_u64()?; Ok((seq_no, UInt256::from(hash))) } fn read_one_sb<R>(&self, rdr: &mut R) -> NodeResult<Box<ShardBlock>> where R: Read + Seek { let (shard_path, _blocks_path, _tr_dir) = FileBasedStorage::create_default_shard_catalog(self.root_path.clone(), &self.shard_ident)?; let mut block_finality_path = shard_path.clone(); block_finality_path.push("block_finality"); if !block_finality_path.as_path().exists() { create_dir_all(block_finality_path.as_path())?; } // first read current block let hash = UInt256::from(rdr.read_u256()?); let seq_no = rdr.read_le_u64()?; info!(target: "node", "read_one_sb:seq_no: {}", seq_no); if seq_no == 0 { Ok(Box::new(ShardBlock::default())) } else { let mut current_block_name = block_finality_path.clone(); current_block_name.push(hash.to_hex_string()); self.read_one_sb_from_file(current_block_name) } } fn read_one_sb_from_file(&self, file_name: PathBuf) -> NodeResult<Box<ShardBlock>> { info!(target: "node", "load {}", file_name.to_str().unwrap()); let mut file_info = File::open(file_name.clone())?; let mut data = Vec::new(); file_info.read_to_end(&mut data)?; info!(target: "node", "load {} ok.", file_name.to_str().unwrap()); Ok(Box::new(ShardBlock::deserialize(&mut std::io::Cursor::new(data))?)) } /// /// Read saved data BlockFinality from file /// pub fn deserialize<R>(&mut self, rdr: &mut R) -> NodeResult<()> where R: Read + Seek { info!(target: "node", "load current block"); self.current_block = self.read_one_sb(rdr)?; info!(target: "node", "load last finalized block"); self.last_finalized_block = self.read_one_sb(rdr)?; loop { info!(target: "node", "load non finalized block"); let res = self.read_one_sb_hash(rdr); if res.is_ok() { let (seq_no, hash) = res.unwrap(); let sb_hash = Box::new(FinalityBlock::Stored( Box::new(ShardBlockHash::with_hash(seq_no.clone(), hash.clone())) )); self.blocks_by_hash.insert(hash.clone(), sb_hash.clone()); self.blocks_by_no.insert(seq_no.clone(), sb_hash.clone()); } else { match res.unwrap_err() { NodeError(NodeErrorKind::Io(err), _) => { if err.kind() == ErrorKind::UnexpectedEof { break; } }, err => { bail!(err); } } } } Ok(()) } /// save objects into kafka with "finalized" state, fn reflect_block_in_db( &self, block: Block, shard_state: Arc<ShardStateUnsplit>, is_sync: bool, ) -> NodeResult<()> { if !is_sync { if let Some(db) = self.db.clone() { // let block_root = block.serialize()?; // let state_root = shard_state.serialize()?; // let block_info_root = block.read_info()?.serialize()?; // let block_info_cells = BagOfCells::with_root(&block_info_root.into()) // .withdraw_cells(); let block_id = block.hash()?; let extra = block.read_extra()?; let workchain_id = block.read_info()?.shard().workchain_id(); extra.read_in_msg_descr()?.iterate_objects(|in_msg| { let msg = in_msg.read_message()?; debug!(target: "node", "PUT-IN-MESSAGE-BLOCK {}", msg.hash()?.to_hex_string()); // msg.prepare_proof_for_json(&block_info_cells, &block_root)?; // msg.prepare_boc_for_json()?; let transaction_id = in_msg.transaction_cell().map(|cell| cell.repr_hash()); let transaction_now = in_msg.read_transaction()?.map(|transaction| transaction.now()); db.put_message( msg, transaction_id, transaction_now, Some(block_id.clone()) ).map_err(|err| warn!(target: "node", "reflect message to DB(1). error: {}", err)) .ok(); Ok(true) })?; debug!(target: "node", "in_msg_descr.iterate - success"); extra.read_out_msg_descr()?.iterate_objects(|out_msg| { let msg = out_msg.read_message()?.unwrap(); debug!(target: "node", "PUT-OUT-MESSAGE-BLOCK {:?}", msg); // msg1.prepare_proof_for_json(&block_info_cells, &block_root)?; // msg1.prepare_boc_for_json()?; let transaction_id = out_msg.transaction_cell().map(|cell| cell.repr_hash()); db.put_message( msg, transaction_id, None, Some(block_id.clone()) ).map_err(|err| warn!(target: "node", "reflect message to DB(2). error: {}", err)) .ok(); Ok(true) })?; debug!(target: "node", "out_msg_descr.iterate - success"); let mut changed_acc = HashSet::new(); extra.read_account_blocks()?.iterate_with_keys(|account_id, account_block| { let mut orig_status = None; let mut end_status = None; changed_acc.insert(account_id); account_block.transaction_iterate(|transaction| { // transaction.prepare_proof_for_json(&block_info_cells, &block_root)?; // transaction.prepare_boc_for_json()?; debug!(target: "node", "PUT-TRANSACTION-BLOCK {}", transaction.hash()?.to_hex_string()); if orig_status.is_none() { orig_status = Some(transaction.orig_status.clone()); } end_status = Some(transaction.end_status.clone()); if let Err(err) = db.put_transaction(transaction, Some(block_id.clone()), workchain_id) { warn!(target: "node", "reflect transaction to DB. error: {}", err); } Ok(true) })?; if end_status == Some(AccountStatus::AccStateNonexist) && end_status != orig_status { let account_id = account_block.account_id().clone(); if let Err(err) = db.put_deleted_account(workchain_id, account_id) { warn!(target: "node", "reflect deleted account to DB. error: {}", err); } } Ok(true) })?; //if block_status == BlockProcessingStatus::Finalized { shard_state.read_accounts()?.iterate_with_keys(|id, acc| { if changed_acc.contains(&id) { // acc.account.prepare_proof_for_json(&state_root)?; // acc.account.prepare_boc_for_json()?; let acc = acc.read_account()?; if acc.is_none() { error!(target: "node", "something gone wrong with account {:x}", id); } else if let Err(err) = db.put_account(acc) { warn!(target: "node", "reflect account to DB. error: {}", err); } } Ok(true) })?; //} debug!(target: "node", "accounts.iterate - success"); db.put_block(block)?; } } Ok(()) } } impl<S, B, T, F> BlockFinality for OrdinaryBlockFinality<S, B, T, F> where S: ShardStateStorage, B: BlocksStorage, T: TransactionsStorage, F: FinalityStorage, { /// finalize block through empty step fn finalize_without_new_block(&mut self, finality_hash: Vec<UInt256>) -> NodeResult<()> { debug!(target: "node", "NO-BLOCK {:?}", finality_hash); self.finality_blocks(finality_hash, false)?; self.save_finality()?; Ok(()) } /// Save block until finality comes fn put_block_with_info(&mut self, sblock: SignedBlock, sblock_data:Option<Vec<u8>>, block_hash: Option<UInt256>, shard_state: Arc<ShardStateUnsplit>, finality_hash: Vec<UInt256>, is_sync: bool, ) -> NodeResult<()> { info!(target: "node", "FINALITY: add block. hash: {:?}", block_hash); info!(target: "node", "FINALITY: block seq_no: {:?}", sblock.block().read_info()?.seq_no()); let sb = Box::new(ShardBlock::with_block_and_state( sblock, sblock_data, block_hash, shard_state, )); debug!(target: "node", "PUT-BLOCK-HASH {:?}", sb.block_hash); self.current_block = sb.clone(); // insert block to map let mut loaded = false; for hash in finality_hash.iter() { if hash == &sb.block_hash { loaded = true; break; } } let sb_hash = if loaded { Box::new(FinalityBlock::Loaded(sb.clone())) } else { Box::new( FinalityBlock::Stored( Box::new( ShardBlockHash::with_hash(sb.seq_no.clone(), sb.block_hash.clone()) ) ) ) }; self.blocks_by_hash.insert(sb.block_hash.clone(), sb_hash.clone()); self.blocks_by_no.insert(sb.get_seq_no(), sb_hash.clone()); // finalize block by finality_hash self.finality_blocks(finality_hash, is_sync)?; self.save_finality()?; Ok(()) } /// get last block sequence number fn get_last_seq_no(&self) -> u32 { self.current_block.block.block().read_info().unwrap().seq_no() } /// get last block info fn get_last_block_info(&self) -> NodeResult<BlkPrevInfo> { let info = &self.current_block.block.block().read_info()?; Ok(BlkPrevInfo::Block { prev: ExtBlkRef { end_lt: info.end_lt(), seq_no: info.seq_no(), root_hash: self.current_block.block_hash.clone(),//UInt256::from(self.current_block.block.block_hash().clone()), file_hash: self.current_block.file_hash.clone(), }}) } /// get last shard bag fn get_last_shard_state(&self) -> Arc<ShardStateUnsplit> { //warn!("LAST SHARD BAG {}", self.current_block.shard_bag.get_repr_hash_by_index(0).unwrap().to_hex_string())); Arc::clone(&self.current_block.shard_state) } /// find block by hash and return his secuence number (for sync) fn find_block_by_hash(&self, hash: &UInt256) -> u64 { if self.blocks_by_hash.contains_key(hash) { self.blocks_by_hash.get(hash).unwrap().seq_no() } else { 0xFFFFFFFF // if not found } } /// Rollback shard state to one of block candidates fn rollback_to(&mut self, hash: &UInt256) -> NodeResult<()> { if self.blocks_by_hash.contains_key(hash) { let sb = self.blocks_by_hash.remove(hash).unwrap(); let mut seq_no = sb.seq_no(); self.current_block = self.stored_to_loaded(sb)?; // remove from hashmaps all blocks with greather seq_no loop { let tmp = self.blocks_by_no.remove(&seq_no); if tmp.is_some() { self.blocks_by_hash.remove(tmp.unwrap().block_hash()); } else { break; } seq_no += 1; } Ok(()) } else { node_err!(NodeErrorKind::RoolbackBlockError) } } /// get raw signed block data - for synchronize fn get_raw_block_by_seqno(&self, seq_no: u32, vert_seq_no: u32 ) -> NodeResult<Vec<u8>> { let key = key_by_seqno(seq_no, vert_seq_no); if self.blocks_by_no.contains_key(&key) { /* TODO: wich case to use? return Ok(self.blocks_by_no.get(&key).unwrap().serialized_block.clone()) TODO rewrite to return Ok( self.fn_storage.load_non_finalized_block_by_seq_no(key)?.serialized_block.clone() )*/ return Ok(self .stored_to_loaded(self.blocks_by_no.get(&key).unwrap().clone())? .serialized_block.clone() ) } self.blocks_storage.raw_block(seq_no, vert_seq_no) } /// get number of last finalized shard fn get_last_finality_shard_hash(&self) -> NodeResult<(u64, UInt256)> { // TODO avoid serilization there let cell = self.last_finalized_block.shard_state.serialize()?; Ok((self.last_finalized_block.seq_no, cell.repr_hash())) } /// reset block finality /// clean all maps, load last finalized data fn reset(&mut self) -> NodeResult<()> { self.current_block = self.last_finalized_block.clone(); // remove files from disk for (hash, _sb) in self.blocks_by_hash.iter() { self.remove_form_finality_storage(&hash)?; } self.blocks_by_hash.clear(); self.blocks_by_no.clear(); Ok(()) } } #[derive(Clone, Debug, PartialEq)] pub enum FinalityBlock { Loaded(Box<ShardBlock>), Stored(Box<ShardBlockHash>), } impl FinalityBlock { pub fn seq_no(&self) -> u64 { match self { FinalityBlock::Stored(sb) => { sb.seq_no }, FinalityBlock::Loaded(sb) => { sb.seq_no } } } pub fn block_hash(&self) -> &UInt256 { match self { FinalityBlock::Stored(sb) => { &sb.block_hash }, FinalityBlock::Loaded(sb) => { &sb.block_hash } } } } #[derive(Clone, Debug, PartialEq)] pub struct ShardBlockHash { seq_no: u64, block_hash: UInt256 } impl ShardBlockHash { pub fn with_hash(seq_no: u64, hash: UInt256) -> Self { Self { seq_no, block_hash: hash } } } /// Structure for store one block and his ShardState #[derive(Clone, Debug, PartialEq)] pub struct ShardBlock { seq_no: u64, serialized_block: Vec<u8>, block_hash: UInt256, file_hash: UInt256, block: SignedBlock, shard_state: Arc<ShardStateUnsplit>, } impl Default for ShardBlock { fn default() -> Self { Self { seq_no: 0, serialized_block: Vec::new(), block_hash: UInt256::from([0;32]), file_hash: UInt256::from([0;32]), block: SignedBlock::with_block_and_key( Block::default(), &Keypair::from_bytes(&[0;64]).unwrap() ).unwrap(), shard_state: Arc::new(ShardStateUnsplit::default()), } } } impl ShardBlock { /// Create new instance of ShardBlock pub fn new() -> Self { Self::default() } /// get current block sequence number pub fn get_seq_no(&self) -> u64 { self.seq_no } /// get current block hash pub fn block_hash(&self) -> &UInt256 { &self.block_hash } /// Create new instance of shard block with SignedBlock and new shard state pub fn with_block_and_state( sblock: SignedBlock, serialized_block: Option<Vec<u8>>, block_hash: Option<UInt256>, shard_state: Arc<ShardStateUnsplit>) -> Self { let serialized_block = if serialized_block.is_some() { serialized_block.unwrap() } else { let mut buf = Vec::new(); sblock.write_to(&mut buf).unwrap(); buf }; // Test-lite-client requires hash od unsigned block // TODO will to think, how to do better let mut block_data = vec![]; let cell = sblock.block().serialize().unwrap(); // TODO process result let bag = BagOfCells::with_root(&cell); bag.write_to(&mut block_data, false).unwrap(); // TODO process result let mut hasher = Sha256::new(); hasher.input(block_data.as_slice()); let file_hash = UInt256::from_slice(&hasher.result().to_vec()); Self { seq_no: key_by_seqno(sblock.block().read_info().unwrap().seq_no(), sblock.block().read_info().unwrap().vert_seq_no()), serialized_block, block_hash: if block_hash.is_some() { block_hash.unwrap() } else { sblock.block().hash().unwrap() }, file_hash, block: sblock, shard_state, } } /// serialize shard block (for save on disk) pub fn serialize(&self) -> NodeResult<Vec<u8>>{ let mut buf = Vec::new(); buf.extend_from_slice(&self.seq_no.to_le_bytes()); buf.extend_from_slice(&(self.serialized_block.len() as u32).to_le_bytes()); buf.append(&mut self.serialized_block.clone()); buf.append(&mut self.block_hash.as_slice().to_vec()); buf.append(&mut self.file_hash.as_slice().to_vec()); BagOfCells::with_root(&self.shard_state.serialize()?) .write_to(&mut buf, false)?; let mut block_buf = Vec::new(); self.block.write_to(&mut block_buf)?; buf.append(&mut block_buf); Ok(buf) } /// deserialize shard block pub fn deserialize<R: Read>(rdr: &mut R) -> NodeResult<Self> { let mut sb = ShardBlock::new(); sb.seq_no = rdr.read_le_u64()?; let sb_len = rdr.read_le_u32()?; let mut sb_buf = vec![0; sb_len as usize]; rdr.read(&mut sb_buf)?; sb.serialized_block = sb_buf; let hash = rdr.read_u256()?; sb.block_hash = UInt256::from(hash); let hash = rdr.read_u256()?; sb.file_hash = UInt256::from(hash); let mut shard_slice = deserialize_tree_of_cells(rdr)?.into(); sb.shard_state.read_from(&mut shard_slice)?; sb.block = SignedBlock::read_from(rdr)?; Ok(sb) } } // runs 10 thread to generate 5000 accounts with 1 input and two ouput messages per every block // finilizes block and return #[allow(dead_code)] pub(crate) fn generate_block_with_seq_no(shard_ident: ShardIdent, seq_no: u32, prev_info: BlkPrevInfo) -> Block { let block_builder = Arc::new(BlockBuilder::with_shard_ident(shard_ident, seq_no, prev_info, 0, None, SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as u32)); // start 10 thread for generate transaction for _ in 0..10 { let builder_clone = block_builder.clone(); thread::spawn(move || { //println!("Thread write start."); let mut rng = rand::thread_rng(); for _ in 0..5000 { let acc = AccountId::from_raw((0..32).map(|_| { rand::random::<u8>() }).collect::<Vec<u8>>(), 256); let mut transaction = Transaction::with_address_and_status(acc.clone(), AccountStatus::AccStateActive); let mut value = CurrencyCollection::default(); value.grams = 10202u32.into(); let mut imh = InternalMessageHeader::with_addresses ( MsgAddressInt::with_standart(None, 0, acc.clone()).unwrap(), MsgAddressInt::with_standart(None, 0, AccountId::from_raw((0..32).map(|_| { rand::random::<u8>() }).collect::<Vec<u8>>(), 256)).unwrap(), value ); imh.ihr_fee = 10u32.into(); imh.fwd_fee = 5u32.into(); let mut inmsg1 = Arc::new(Message::with_int_header(imh)); Arc::get_mut(&mut inmsg1).map(|m| *m.body_mut() = Some(SliceData::new(vec![0x21;120]))); let inmsg_int = InMsg::immediatelly( &MsgEnvelope::with_message_and_fee(&inmsg1, 9u32.into()).unwrap(), &transaction, 11u32.into(), ).unwrap(); let eimh = ExternalInboundMessageHeader { src: MsgAddressExt::with_extern(SliceData::new(vec![0x23, 0x52, 0x73, 0x00, 0x80])).unwrap(), dst: MsgAddressInt::with_standart(None, 0, acc.clone()).unwrap(), import_fee: 10u32.into(), }; let mut inmsg = Message::with_ext_in_header(eimh); *inmsg.body_mut() = Some(SliceData::new(vec![0x01;120])); transaction.write_in_msg(Some(&inmsg1)).unwrap(); // inmsg let inmsg_ex = InMsg::external(&inmsg, &transaction).unwrap(); // outmsgs let mut value = CurrencyCollection::default(); value.grams = 10202u32.into(); let mut imh = InternalMessageHeader::with_addresses ( MsgAddressInt::with_standart(None, 0, acc.clone()).unwrap(), MsgAddressInt::with_standart(None, 0, AccountId::from_raw(vec![255;32], 256)).unwrap(), value ); imh.ihr_fee = 10u32.into(); imh.fwd_fee = 5u32.into(); let outmsg1 = Message::with_int_header(imh); let eomh = ExtOutMessageHeader::with_addresses ( MsgAddressInt::with_standart(None, 0, acc.clone()).unwrap(), MsgAddressExt::with_extern(SliceData::new(vec![0x23, 0x52, 0x73, 0x00, 0x80])).unwrap() ); let mut outmsg2 = Message::with_ext_out_header(eomh); *outmsg2.body_mut() = Some(SliceData::new(vec![0x02;120])); let tr_cell = transaction.serialize().unwrap(); let out_msg1 = OutMsg::new( &MsgEnvelope::with_message_and_fee(&outmsg1, 9u32.into()).unwrap(), tr_cell.clone() ).unwrap(); let out_msg2 = OutMsg::external(&outmsg2, tr_cell).unwrap(); let inmsg = Arc::new(if rng.gen() { inmsg_int} else { inmsg_ex }); // builder can stop earler than writing threads it is not a problem here if !builder_clone.add_transaction(inmsg, vec![out_msg1, out_msg2]) { break; } thread::sleep(Duration::from_millis(1)); // emulate timeout working TVM } }); } thread::sleep(Duration::from_millis(10)); let ss = ShardStateUnsplit::default(); let (block, _count) = block_builder.finalize_block(&ss, &ss).unwrap(); block }
/* chapter 4 syntax and semantics */ fn main() { let mut a = vec![1, 2, 3]; for b in &a { println!("{}", b); } // because a is mutable we will see the warning: // // warning: variable does not need to be mutable, // #[warn(unused_mut)] on by default // // let mut a = vec![1, 2, 3]; // ^~~~~ /* for c in &a { println!("{}", c); a.push(34); } */ // // this code will give an error: // // error: cannot borrow `a` as mutable because it is also borrowed as immutable // a.push(34); // ^ // note: previous borrow of `v` occurs here; the immutable borrow prevents // subsequent moves or mutable borrows of `v` until the borrow ends // for i in &v { // ^ // note: previous borrow ends here // for i in &v { // println!(“{}”, i); // v.push(34); // } // ^ } // output should be: /* 1 2 3 */
mod cli; mod errors; mod config; mod container; mod ipc; mod child; mod hostname; mod mounts; mod namespaces; mod capabilities; mod syscalls; mod resources; #[macro_use] extern crate scan_fmt; use errors::exit_with_retcode; fn main() { match cli::parse_args() { Ok(args) => { log::info!("{:?}", args); exit_with_retcode(container::start(args)); }, Err(e) => { //log::error!("Error while parsing arguments:\n\t{}", e); exit_with_retcode(Err(e)); } } }
use nm_dbus::NmError; use crate::{ErrorKind, NmstateError}; pub(crate) fn nm_error_to_nmstate(nm_error: &NmError) -> NmstateError { NmstateError::new( ErrorKind::Bug, format!( "{}: {} dbus: {:?}", nm_error.kind, nm_error.msg, nm_error.dbus_error ), ) }
use std::io; fn main() { loop { println!("Insert the position of the fibonacci series (x to exit):"); let mut value = String::new(); io::stdin().read_line(&mut value) .expect("Failed to read line"); match value.trim().parse() { Ok(num) => println!("Fibonacci({}) = {}", value.trim(), fib(num)), Err(_) => break, }; } } fn fib(n: u128) -> u128 { if n == 1 { return 1; } else if n == 2 { return 1; } else { return fib(n - 1) + fib(n - 2); } }
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::collections::LookupMap; use near_sdk::json_types::{U128, U64}; use near_sdk::serde::{Deserialize, Serialize}; use near_sdk::serde_json::{self, json}; use near_sdk::wee_alloc::WeeAlloc; use near_sdk::{env, ext_contract, near_bindgen, AccountId, PromiseResult}; use std::convert::TryInto; use std::str; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct AggregatorValidatorMock { pub previous_round_id: u128, pub previous_answer: u128, pub current_round_id: u128, pub current_answer: u128, } impl Default for AggregatorValidatorMock { fn default() -> Self { panic!("AggregatorValidatorMock should be initialized before usage"); } } #[near_bindgen] impl AggregatorValidatorMock { #[init] pub fn new() -> Self { let result = Self { previous_round_id: 0, previous_answer: 0, current_round_id: 0, current_answer: 0, }; result } pub fn validate( &self, previous_round_id: U128, previous_answer: U128, current_round_id: U128, current_answer: U128, ) -> bool { env::log( format!( "{}, {}, {}, {}", u128::from(previous_round_id), u128::from(previous_answer), u128::from(current_round_id), u128::from(current_answer) ) .as_bytes(), ); true } }
use std::env; use tcalc_rustyline::error::ReadlineError; use tcalc_rustyline::Editor; #[macro_use] mod macros; mod ast; mod buffered_iterator; mod parsing; mod running; mod scanning; use crate::ast::*; use crate::running::*; fn print_usage() { println!("Usage: {} [OPTION] EXPRESSIONS", env!("CARGO_PKG_NAME")); } fn print_opts() { println!("Options:"); println!(" --help print this help menu"); println!(" --version print version information"); } fn print_help() { print_usage(); println!(); print_opts(); } fn print_try_help() { print_usage(); println!(); println!( "Try '{} --help' for more information.", env!("CARGO_PKG_NAME") ); } fn print_version() { println!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); } fn run_exprs<I>(inputs: I) where I: Iterator<Item = String>, { let mut runner = Runner::new(); for str in inputs { match parsing::parse(&str) { Some(Ast::Expression(expr)) => match runner.run_expression(&expr) { Ok(v) => println!("{}", v), Err(msg) => println!("{}", msg), }, Some(Ast::Statement(stmt)) => match runner.run_statement(&stmt) { Ok(_) => {} Err(msg) => println!("{}", msg), }, _ => {} } // match } // for } // run_exprs fn repl() { let mut runner = Runner::new(); let mut rl = Editor::<()>::new(); let history_path = match dirs::cache_dir() { Some(mut hist_dir) => { hist_dir.push("tcalc_history"); Some(hist_dir) } _ => None, }; if let Some(ref path) = history_path { let _ = rl.load_history(&path); } loop { match rl.readline("> ") { Ok(line) => { rl.add_history_entry(line.as_str()); match parsing::parse(&line) { Some(Ast::Command(Command::Exit)) => break, Some(Ast::Expression(expr)) => match runner.run_expression(&expr) { Ok(v) => println!(" {}", v), Err(msg) => println!("{}", msg), }, Some(Ast::Statement(stmt)) => match runner.run_statement(&stmt) { Ok(_) => {} Err(msg) => println!("{}", msg), }, None => {} } // match } Err(ReadlineError::Cancelled) => {} Err(ReadlineError::Interrupted) => break, Err(ReadlineError::Eof) => break, Err(msg) => println!("error: {}", msg), } // match } // loop if let Some(ref path) = history_path { if let Err(msg) = rl.save_history(&path) { println!("Failed to save history: '{}'", msg); } } } // repl fn main() { let mut args = env::args(); // start repl if there are no arguments if args.len() < 2 { repl(); return; } // check for arguments let mut peekable = args.by_ref().skip(1).peekable(); while let Some(arg) = peekable.peek() { match arg.as_str() { "--help" => { print_help(); return; } "--version" => { print_version(); return; } str => { if str.starts_with("--") { println!("Unrecognized option '{}'", str); println!(); print_try_help(); return; } break; } } } // evaluate remaining inputs run_exprs(peekable); } // main
fn main() { println!("a"); }
#[doc = "Register `VVACCR` reader"] pub type R = crate::R<VVACCR_SPEC>; #[doc = "Field `VA` reader - Vertical Active duration"] pub type VA_R = crate::FieldReader<u16>; impl R { #[doc = "Bits 0:13 - Vertical Active duration"] #[inline(always)] pub fn va(&self) -> VA_R { VA_R::new((self.bits & 0x3fff) as u16) } } #[doc = "DSI Host Video VA Current Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`vvaccr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct VVACCR_SPEC; impl crate::RegisterSpec for VVACCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`vvaccr::R`](R) reader structure"] impl crate::Readable for VVACCR_SPEC {} #[doc = "`reset()` method sets VVACCR to value 0"] impl crate::Resettable for VVACCR_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_force(number_of_links: u8, link_length: f64, end_to_end_length: f64, temperature: f64) -> f64 { super::force(&number_of_links, &link_length, &end_to_end_length, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_nondimensional_force(nondimensional_end_to_end_length_per_link: f64) -> f64 { super::nondimensional_force(&nondimensional_end_to_end_length_per_link) } #[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_helmholtz_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, end_to_end_length: f64, temperature: f64) -> f64 { super::helmholtz_free_energy(&number_of_links, &link_length, &hinge_mass, &end_to_end_length, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_helmholtz_free_energy_per_link(number_of_links: u8, link_length: f64, hinge_mass: f64, end_to_end_length: f64, temperature: f64) -> f64 { super::helmholtz_free_energy_per_link(&number_of_links, &link_length, &hinge_mass, &end_to_end_length, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_relative_helmholtz_free_energy(number_of_links: u8, link_length: f64, end_to_end_length: f64, temperature: f64) -> f64 { super::relative_helmholtz_free_energy(&number_of_links, &link_length, &end_to_end_length, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_relative_helmholtz_free_energy_per_link(number_of_links: u8, link_length: f64, end_to_end_length: f64, temperature: f64) -> f64 { super::relative_helmholtz_free_energy_per_link(&number_of_links, &link_length, &end_to_end_length, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_nondimensional_helmholtz_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, nondimensional_end_to_end_length_per_link: f64, temperature: f64) -> f64 { super::nondimensional_helmholtz_free_energy(&number_of_links, &link_length, &hinge_mass, &nondimensional_end_to_end_length_per_link, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_nondimensional_helmholtz_free_energy_per_link(link_length: f64, hinge_mass: f64, nondimensional_end_to_end_length_per_link: f64, temperature: f64) -> f64 { super::nondimensional_helmholtz_free_energy_per_link(&link_length, &hinge_mass, &nondimensional_end_to_end_length_per_link, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_nondimensional_relative_helmholtz_free_energy(number_of_links: u8, nondimensional_end_to_end_length_per_link: f64) -> f64 { super::nondimensional_relative_helmholtz_free_energy(&number_of_links, &nondimensional_end_to_end_length_per_link) } #[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_nondimensional_relative_helmholtz_free_energy_per_link(nondimensional_end_to_end_length_per_link: f64) -> f64 { super::nondimensional_relative_helmholtz_free_energy_per_link(&nondimensional_end_to_end_length_per_link) } #[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_equilibrium_distribution(number_of_links: u8, link_length: f64, end_to_end_length: f64) -> f64 { super::equilibrium_distribution(&number_of_links, &link_length, &end_to_end_length) } #[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_nondimensional_equilibrium_distribution(number_of_links: u8, nondimensional_end_to_end_length_per_link: f64) -> f64 { super::nondimensional_equilibrium_distribution(&number_of_links, &nondimensional_end_to_end_length_per_link) } #[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_equilibrium_radial_distribution(number_of_links: u8, link_length: f64, end_to_end_length: f64) -> f64 { super::equilibrium_radial_distribution(&number_of_links, &link_length, &end_to_end_length) } #[no_mangle] pub extern fn physics_single_chain_ideal_thermodynamics_isometric_nondimensional_equilibrium_radial_distribution(number_of_links: u8, nondimensional_end_to_end_length_per_link: f64) -> f64 { super::nondimensional_equilibrium_radial_distribution(&number_of_links, &nondimensional_end_to_end_length_per_link) }
use std::{io::BufReader, sync::Arc}; use arrow::csv::reader; use wasm_bindgen::prelude::*; use crate::{schema::Schema, utils::StringReader}; #[wasm_bindgen] pub fn infer_schema_from_csv( content: String, // max_records: usize, // returns the schema as a jsvalue ) -> Result<JsValue, JsValue> { // let b = ",".as_bytes; // let r = unsafe { content.as_bytes_mut() }; let r = StringReader::new(content.as_str()); let mut b = BufReader::new(r); let out = reader::infer_reader_schema( b.get_mut(), b',', Some(50), true, ); match out { Ok(schema) => { let sr = Arc::new(schema.0); return Ok(Schema::new(sr).to_json()); } Err(e) => return Err(e.to_string().into()), } }
fn round_to_next_5(n: i32) -> i32 { let abs_remain = (n % 5).abs(); let to_add_on = if n < 0 { abs_remain } else { 5 - abs_remain }; return if abs_remain > 0 { n + to_add_on } else { n }; } fn main() { println!("0 {}", round_to_next_5(0)); println!("5 {}", round_to_next_5(2)); println!("5 {}", round_to_next_5(3)); println!("15 {}", round_to_next_5(12)); println!("25 {}", round_to_next_5(21)); println!("30 {}", round_to_next_5(30)); println!("0 {}", round_to_next_5(-2)); println!("-5 {}", round_to_next_5(-5)); }
impl Solution { pub fn contains_duplicate(nums: Vec<i32>) -> bool { use std::collections::HashMap; let mut numMap = HashMap::new(); for n in nums { let count = numMap.entry(n).or_insert(0); *count += 1; } for (key, count) in numMap { if count > 1 { return true; } } false } }
extern crate rand; use std::io; use rand::Rng; use std::cmp::Ordering; #[allow(non_snake_case)] fn main() { let randomNum = rand::thread_rng().gen_range(0, 101); loop { println!("Guess the correct number\n>>>"); let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("expected a number"); let guess2: i32 = guess.trim().parse() .expect("gimmi a number"); match guess2.cmp(&randomNum) { Ordering::Less => println!("Too low!"), Ordering::Greater => println!("Too high!"), Ordering::Equal => { println!("You got it!"); break; } } } }
use std::process; mod instruction; pub mod interrupt_handler; mod registers; use crate::cpu::instruction::*; use crate::cpu::interrupt_handler::*; use crate::cpu::registers::*; use crate::gb; use crate::memory::Memory; use crate::timer::Cycles; pub struct Cpu { registers: Registers, pc: u16, sp: u16, finished_bootrom: bool, pub memory: Memory, pub interrupt_handler: InterruptHandler, _current_instruction: (Instruction, u8), } impl Cpu { pub fn new() -> Cpu { let mut memory = Memory::initialize(); memory.write_byte(gb::lcd_stat, 0x02); Cpu { registers: Registers::new(), pc: 0, //gb::init_pc_value, sp: 0, memory, interrupt_handler: InterruptHandler { ime: false }, finished_bootrom: false, _current_instruction: (Instruction::Nop, 0), } } pub fn step(&mut self) -> u8 { if self.pc >= 0x100 && !self.finished_bootrom { self.memory.replace_bootrom(); self.finished_bootrom = true; } if self.interrupt_handler.interrupts_enabled() { if let Some(interrupt) = self.interrupt_handler.check_interrupts(&mut self.memory) { self.interrupt_handler.disable_interrupts(); self.call(interrupt_handler::address_for_interrupt(interrupt)); } } let instruction = Instruction::from_bytes(&self.memory, self.pc); // println!( // "{:#0x}: {}, {}, sp: {:#0x}", // self.pc, instruction, self.registers, self.sp // ); self.execute(&instruction) } fn execute(&mut self, i: &Instruction) -> u8 { let (size, mut cycles) = Instruction::size_and_cycles(i); self.pc += size as u16; match i { Instruction::Nop => {} Instruction::Stop => { println!("Stopping program with instruction {}", i); process::exit(1); } Instruction::Halt => { println!("Halting program with instruction {}", i); process::exit(0); } Instruction::SetCarryFlag => { self.registers.set_flag(Flag::Carry, true); } Instruction::Load16(operand1, operand2) => { match (operand1, operand2) { (Load16Target::Register16(reg), Load16Source::Data(d16)) => { // need to read 2 bytes for d16, currently done in instruciton decode self.registers.set_16bit(reg, *d16) } (Load16Target::Address(a16), Load16Source::StackPointer) => { // need to read 2 bytes for a16, currently done in instruciton decode self.memory.write_2_bytes(*a16, self.sp); } (Load16Target::Register16(reg), Load16Source::SpPlus(s8)) => { // need to read 1 byte for s8, currently done in instruciton decode let sp_plus = (self.sp as i16) + (*s8 as i16); self.registers.set_16bit(reg, self.sp + (sp_plus as u16)) } (Load16Target::StackPointer, Load16Source::Hl) => { self.sp = self.registers.get_16bit(&RegisterPair::Hl) } (Load16Target::StackPointer, Load16Source::Data(d16)) => self.sp = *d16, _ => panic!("Enounctered unimplemented load16 instruction: {}", i), }; } Instruction::Load8(operand1, operand2) => match (operand1, operand2) { (Load8Operand::Register(target_reg), Load8Operand::Register(src_reg)) => { let data = self.registers.get(src_reg); self.registers.set(&target_reg, data); } (Load8Operand::Register(target_reg), Load8Operand::Data(d8)) => { self.registers.set(&target_reg, *d8); } (Load8Operand::Register(target_reg), Load8Operand::AtHli) | (Load8Operand::Register(target_reg), Load8Operand::AtHld) => { let address: u16 = self.registers.get_16bit(&RegisterPair::Hl); match operand2 { Load8Operand::AtHli => { self.registers.set_16bit(&RegisterPair::Hl, address + 1) } Load8Operand::AtHld => { self.registers.set_16bit(&RegisterPair::Hl, address - 1) } _ => panic!("Bad opereand to for LD A HLD/HLI"), }; let data = self.memory.read_byte(address); self.registers.set(&target_reg, data); } (Load8Operand::AtHli, Load8Operand::Register(target_reg)) | (Load8Operand::AtHld, Load8Operand::Register(target_reg)) => { let address: u16 = self.registers.get_16bit(&RegisterPair::Hl); match operand1 { Load8Operand::AtHli => { self.registers.set_16bit(&RegisterPair::Hl, address + 1) } Load8Operand::AtHld => { self.registers.set_16bit(&RegisterPair::Hl, address - 1) } _ => panic!("Bad opereand to for LD HLD/HLI A"), }; self.memory .write_byte(address, self.registers.get(target_reg)); } (Load8Operand::AtReg16(reg), Load8Operand::Register(src_reg)) => { let data = self.registers.get(src_reg); let address: u16 = self.registers.get_16bit(reg); self.memory.write_byte(address, data); } (Load8Operand::AtReg16(reg), Load8Operand::Data(data)) => { let address: u16 = self.registers.get_16bit(reg); self.memory.write_byte(address, *data); } (Load8Operand::Register(target_reg), Load8Operand::AtReg16(reg)) => { let address: u16 = self.registers.get_16bit(reg); let data = self.memory.read_byte(address); self.registers.set(target_reg, data); } (Load8Operand::AtC, Load8Operand::Register(Register::A)) | (Load8Operand::AtAddress8(_), Load8Operand::Register(Register::A)) | (Load8Operand::AtAddress16(_), Load8Operand::Register(Register::A)) => { let data = self.registers.get(&Register::A); let address: u16 = if let Load8Operand::AtC = operand1 { self.registers.get(&Register::C) as u16 + 0xFF00 } else if let Load8Operand::AtAddress8(a8) = operand1 { *a8 as u16 + 0xFF00 } else if let Load8Operand::AtAddress16(a16) = operand1 { *a16 } else { panic!("Should not happen") }; self.memory.write_byte(address, data); } (Load8Operand::Register(Register::A), Load8Operand::AtC) | (Load8Operand::Register(Register::A), Load8Operand::AtAddress8(_)) | (Load8Operand::Register(Register::A), Load8Operand::AtAddress16(_)) => { let address: u16 = if let Load8Operand::AtC = operand2 { self.registers.get(&Register::C) as u16 + 0xFF00 } else if let Load8Operand::AtAddress8(a8) = operand2 { *a8 as u16 + 0xFF00 } else if let Load8Operand::AtAddress16(a16) = operand2 { *a16 } else { panic!("Should not happen") }; let data = self.memory.read_byte(address); self.registers.set(&Register::A, data); } _ => panic!("Enounctered unimplemented load8 instruction: {}", i), }, Instruction::Add(operand) => { let result; let half_carry; match operand { ArithmeticOperand::Register(reg) => { result = (self.registers.get(&Register::A) + self.registers.get(reg)) as u16; half_carry = (self.registers.get(&Register::A) & 0xF) + (self.registers.get(reg) & 0xF) > 0xF; self.registers.set(&Register::A, result as u8); } ArithmeticOperand::AtHl => { let at_hl = self .memory .read_byte(self.registers.get_16bit(&RegisterPair::Hl)) as u16; result = self.registers.get(&Register::A) as u16 + at_hl; half_carry = (self.registers.get(&Register::A) & 0xF) as u16 + (at_hl & 0xF) > 0xF; self.registers.set(&Register::A, result as u8); self.registers.set(&Register::A, result as u8); } ArithmeticOperand::Data(d8) => { // need to read 1 byte for d8 result = (self.registers.get(&Register::A) + d8) as u16; half_carry = (self.registers.get(&Register::A) & 0xF) + (d8 & 0xF) > 0xF; self.registers.set(&Register::A, result as u8); } }; // Set flags based on result self.registers.set_flag(Flag::Zero, result as u8 == 0); self.registers.set_flag(Flag::Carry, result > 0xFF); self.registers.set_flag(Flag::Subtract, false); self.registers.set_flag(Flag::HalfCarry, half_carry); } Instruction::Sub(operand) => { let result; let half_carry; let carry; match operand { ArithmeticOperand::Register(reg) => { result = (self.registers.get(&Register::A) - self.registers.get(reg)) as u16; half_carry = (self.registers.get(&Register::A) & 0xF) < (self.registers.get(reg) & 0xF); carry = self.registers.get(reg) > (self.registers.get(&Register::A)); self.registers.set(&Register::A, result as u8); } ArithmeticOperand::AtHl => { let at_hl = self .memory .read_byte(self.registers.get_16bit(&RegisterPair::Hl)); result = (self.registers.get(&Register::A) - at_hl) as u16; half_carry = (self.registers.get(&Register::A) & 0xF) < (at_hl & 0xF); carry = at_hl > self.registers.get(&Register::A); self.registers.set(&Register::A, result as u8); } ArithmeticOperand::Data(d8) => { // need to read 1 byte for d8 result = (self.registers.get(&Register::A) - *d8) as u16; half_carry = (self.registers.get(&Register::A) & 0xF) < (*d8 & 0xF); carry = *d8 > self.registers.get(&Register::A); self.registers.set(&Register::A, result as u8); } }; // Set flags based on result self.registers.set_flag(Flag::Zero, result as u8 == 0); self.registers.set_flag(Flag::HalfCarry, half_carry); self.registers.set_flag(Flag::Carry, carry); self.registers.set_flag(Flag::Subtract, true); } Instruction::AddCarry(operand) => { let result: u16; let half_carry; let carry_bit = if let true = self.registers.get_flag(Flag::Carry) { 1 } else { 0 }; match operand { ArithmeticOperand::Register(reg) => { result = (self.registers.get(&Register::A) + self.registers.get(reg)) as u16 + carry_bit; half_carry = (self.registers.get(&Register::A) & 0xF) + (self.registers.get(reg) & 0xF) > 0xF; self.registers.set(&Register::A, result as u8); } ArithmeticOperand::AtHl => { let at_hl = self .memory .read_byte(self.registers.get_16bit(&RegisterPair::Hl)) as u16; result = self.registers.get(&Register::A) as u16 + at_hl + carry_bit; half_carry = (self.registers.get(&Register::A) & 0xF) as u16 + (at_hl & 0xF) > 0xF; self.registers.set(&Register::A, result as u8); self.registers.set(&Register::A, result as u8); } ArithmeticOperand::Data(d8) => { // need to read 1 byte for d8 result = (self.registers.get(&Register::A) + d8) as u16 + carry_bit; half_carry = (self.registers.get(&Register::A) & 0xF) + (d8 & 0xF) > 0xF; self.registers.set(&Register::A, result as u8); } }; // Set flags based on result self.registers.set_flag(Flag::Zero, result as u8 == 0); self.registers.set_flag(Flag::Carry, result > 0xFF); self.registers.set_flag(Flag::Subtract, false); self.registers.set_flag(Flag::HalfCarry, half_carry); } Instruction::SubCarry(operand) => { let result; let half_carry; let carry; let carry_bit = if let true = self.registers.get_flag(Flag::Carry) { 1 } else { 0 }; match operand { ArithmeticOperand::Register(reg) => { result = (self.registers.get(&Register::A) - self.registers.get(reg)) as u16 - carry_bit; half_carry = (self.registers.get(&Register::A) & 0xF) - (self.registers.get(reg) & 0xF) - carry_bit as u8 >= 0x10; carry = self.registers.get(reg) as u16 + carry_bit > (self.registers.get(&Register::A)) as u16; self.registers.set(&Register::A, result as u8); } ArithmeticOperand::AtHl => { let at_hl = self .memory .read_byte(self.registers.get_16bit(&RegisterPair::Hl)); result = (self.registers.get(&Register::A) - at_hl) as u16 - carry_bit; half_carry = (self.registers.get(&Register::A) & 0xF) - (at_hl & 0xF) - carry_bit as u8 >= 0x10; carry = at_hl as u16 + carry_bit > self.registers.get(&Register::A) as u16; self.registers.set(&Register::A, result as u8); } ArithmeticOperand::Data(d8) => { // need to read 1 byte for d8 result = (self.registers.get(&Register::A) - *d8) as u16 - carry_bit; half_carry = (self.registers.get(&Register::A) & 0xF) - (*d8 & 0xF) - carry_bit as u8 >= 0x10; carry = *d8 as u16 + carry_bit > self.registers.get(&Register::A) as u16; self.registers.set(&Register::A, result as u8); } }; // Set flags based on result self.registers.set_flag(Flag::Zero, result as u8 == 0); self.registers.set_flag(Flag::HalfCarry, half_carry); self.registers.set_flag(Flag::Carry, carry); self.registers.set_flag(Flag::Subtract, true); } Instruction::And(operand) => { let result; match operand { ArithmeticOperand::Register(reg) => { result = (self.registers.get(&Register::A) & self.registers.get(reg)) as u16; self.registers.set(&Register::A, result as u8); } ArithmeticOperand::AtHl => { result = (self.registers.get(&Register::A) & self .memory .read_byte(self.registers.get_16bit(&RegisterPair::Hl))) as u16; self.registers.set(&Register::A, result as u8); } ArithmeticOperand::Data(d8) => { // need to read 1 byte for d8 result = (self.registers.get(&Register::A) & d8) as u16; self.registers.set(&Register::A, result as u8); } }; // Set flags based on result self.registers.set_flag(Flag::Zero, result as u8 == 0); self.registers.set_flag(Flag::Subtract, false); self.registers.set_flag(Flag::HalfCarry, true); self.registers.set_flag(Flag::Carry, false); } Instruction::Or(operand) => { let result; match operand { ArithmeticOperand::Register(reg) => { result = (self.registers.get(&Register::A) | self.registers.get(reg)) as u16; self.registers.set(&Register::A, result as u8); } ArithmeticOperand::AtHl => { result = (self.registers.get(&Register::A) | self .memory .read_byte(self.registers.get_16bit(&RegisterPair::Hl))) as u16; self.registers.set(&Register::A, result as u8); } ArithmeticOperand::Data(d8) => { // need to read 1 byte for d8 result = (self.registers.get(&Register::A) | d8) as u16; self.registers.set(&Register::A, result as u8); } }; // Set flags based on result self.registers.set_flag(Flag::Zero, result as u8 == 0); self.registers.set_flag(Flag::Subtract, false); self.registers.set_flag(Flag::HalfCarry, false); self.registers.set_flag(Flag::Carry, false); } Instruction::Xor(operand) => { let result; match operand { ArithmeticOperand::Register(reg) => { result = (self.registers.get(&Register::A) ^ self.registers.get(reg)) as u16; self.registers.set(&Register::A, result as u8); } ArithmeticOperand::AtHl => { result = (self.registers.get(&Register::A) ^ self .memory .read_byte(self.registers.get_16bit(&RegisterPair::Hl))) as u16; self.registers.set(&Register::A, result as u8); } ArithmeticOperand::Data(d8) => { // need to read 1 byte for d8 result = (self.registers.get(&Register::A) ^ d8) as u16; self.registers.set(&Register::A, result as u8); } }; // Set flags based on result self.registers.set_flag(Flag::Zero, result as u8 == 0); self.registers.set_flag(Flag::Subtract, false); self.registers.set_flag(Flag::HalfCarry, false); self.registers.set_flag(Flag::Carry, false); } Instruction::Compare(operand) => { let is_zero; let half_carry; let carry; match operand { ArithmeticOperand::Register(reg) => { is_zero = self.registers.get(&Register::A) == self.registers.get(reg); half_carry = (self.registers.get(&Register::A) & 0xF) < (self.registers.get(reg) & 0xF); carry = self.registers.get(reg) > (self.registers.get(&Register::A)); } ArithmeticOperand::AtHl => { let at_hl = self .memory .read_byte(self.registers.get_16bit(&RegisterPair::Hl)); is_zero = self.registers.get(&Register::A) == at_hl; half_carry = (self.registers.get(&Register::A) & 0xF) < (at_hl & 0xF); carry = at_hl > self.registers.get(&Register::A); } ArithmeticOperand::Data(d8) => { // need to read 1 byte for d8 is_zero = self.registers.get(&Register::A) == *d8; half_carry = (self.registers.get(&Register::A) & 0xF) < (*d8 & 0xF); carry = *d8 > self.registers.get(&Register::A); } }; // Set flags based on result self.registers.set_flag(Flag::Zero, is_zero); self.registers.set_flag(Flag::HalfCarry, half_carry); self.registers.set_flag(Flag::Carry, carry); self.registers.set_flag(Flag::Subtract, true); } Instruction::Increment(operand) => { let result; let half_carry; match operand { ArithmeticOperand::Register(reg) => { result = self.registers.get(&reg) + 1; half_carry = (self.registers.get(&reg) ^ 1 ^ result) & 0x10 == 0x10; self.registers.set(&reg, result); } ArithmeticOperand::AtHl => { // this takes 1 cycle let hl_val = self .memory .read_byte(self.registers.get_16bit(&RegisterPair::Hl)); // 1 cycle result = hl_val + 1; half_carry = (hl_val ^ 1 ^ result) & 0x10 == 0x10; // 1 cycle self.memory .write_byte(self.registers.get_16bit(&RegisterPair::Hl), result) } _ => panic!("Enounctered malformed increment instruction: {}", i), }; // Set flags based on result self.registers.set_flag(Flag::Zero, result as u8 == 0); self.registers.set_flag(Flag::Subtract, false); self.registers.set_flag(Flag::HalfCarry, half_carry); } Instruction::Decrement(operand) => { let result; let half_carry; match operand { ArithmeticOperand::Register(reg) => { let (diff, _) = self.registers.get(&reg).overflowing_sub(1); result = diff; half_carry = (self.registers.get(&reg) ^ 1 ^ result) & 0x10 == 0x10; self.registers.set(&reg, result); } ArithmeticOperand::AtHl => { // this takes 1 cycle let hl_val = self .memory .read_byte(self.registers.get_16bit(&RegisterPair::Hl)); // 1 cycle let (diff, _) = hl_val.overflowing_sub(1); result = diff; half_carry = (hl_val ^ 1 ^ result) & 0x10 == 0x10; // 1 cycle self.memory .write_byte(self.registers.get_16bit(&RegisterPair::Hl), result) } _ => panic!("Enounctered malformed decrement instruction: {}", i), }; // Set flags based on result self.registers.set_flag(Flag::Zero, result as u8 == 0); self.registers.set_flag(Flag::Subtract, true); self.registers.set_flag(Flag::HalfCarry, half_carry); } Instruction::IncrementPtr(operand) => { let result; match operand { PtrArithOperand::Register16(reg) => { result = self.registers.get_16bit(&reg) + 1; self.registers.set_16bit(&reg, result); } PtrArithOperand::StackPointer => self.sp += 1, _ => panic!("Enounctered malformed 16bit increment instruction: {}", i), }; } Instruction::DecrementPtr(operand) => { let result; match operand { PtrArithOperand::Register16(reg) => { result = self.registers.get_16bit(&reg) - 1; self.registers.set_16bit(&reg, result); } PtrArithOperand::StackPointer => self.sp -= 1, _ => panic!("Enounctered malformed 16bit decrement instruction: {}", i), }; } Instruction::Rotate(kind) => match kind { RotateKind::LeftCircular => { self.rotate(true, false, &ArithmeticOperand::Register(Register::A)) } RotateKind::Left => { self.rotate(true, true, &ArithmeticOperand::Register(Register::A)) } RotateKind::RightCircular => { self.rotate(false, false, &ArithmeticOperand::Register(Register::A)) } RotateKind::Right => { self.rotate(false, true, &ArithmeticOperand::Register(Register::A)) } }, Instruction::DecimalAdjust => { // doc here -> https://ehaskins.com/2018-01-30%20Z80%20DAA/ let a = self.registers.get(&Register::A); let mut nybble_1 = a & 0xF; let mut nybble_2 = ((a & 0xF0) >> 4) & 0xF; let a_adjusted; println!("Adjusting A: {:#x}", a); if self.registers.get_flag(Flag::Subtract) { if nybble_1 > 0x9 || self.registers.get_flag(Flag::HalfCarry) { nybble_1 -= 0x6; } if nybble_2 > 0x9 || self.registers.get_flag(Flag::Carry) { nybble_2 -= 0x6; } } else { if nybble_1 > 0x9 || self.registers.get_flag(Flag::HalfCarry) { nybble_1 += 0x6 } if nybble_2 > 0x9 || self.registers.get_flag(Flag::Carry) { nybble_2 += 0x6 } } a_adjusted = nybble_1 | (nybble_2 << 4); self.registers.set(&Register::A, a_adjusted); self.registers.set_flag(Flag::Carry, a_adjusted > 0x99); self.registers.set_flag(Flag::HalfCarry, false); self.registers.set_flag(Flag::Zero, a_adjusted == 0x0); } Instruction::Complement => { let a = self.registers.get(&Register::A); self.registers.set(&Register::A, !a); self.registers.set_flag(Flag::HalfCarry, true); self.registers.set_flag(Flag::Subtract, true); } Instruction::FlipCarry => { self.registers.set_flag(Flag::HalfCarry, false); self.registers.set_flag(Flag::Subtract, false); self.registers .set_flag(Flag::Carry, !self.registers.get_flag(Flag::Carry)); } Instruction::Jump(kind) => match kind { JumpKind::JumpRelative(a8) => { self.pc = (self.pc as i16 + i16::from(*a8)) as u16; } JumpKind::JumpRelativeConditional(cond, a8) => match cond { // TODO: Refactor this part out into its own helper // jump relative conditional / jump conditional fn JumpCondition::Zero => { if self.registers.get_flag(Flag::Zero) { self.pc = (self.pc as i16 + i16::from(*a8)) as u16; cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } JumpCondition::NonZero => { if !self.registers.get_flag(Flag::Zero) { self.pc = (self.pc as i16 + i16::from(*a8)) as u16; cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } JumpCondition::Carry => { if self.registers.get_flag(Flag::Carry) { self.pc = (self.pc as i16 + i16::from(*a8)) as u16; cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } JumpCondition::NonCarry => { if !self.registers.get_flag(Flag::Carry) { self.pc = (self.pc as i16 + i16::from(*a8)) as u16; cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } }, JumpKind::Jump(a16) => self.pc = *a16, JumpKind::JumpConditional(cond, a16) => match cond { JumpCondition::Zero => { if self.registers.get_flag(Flag::Zero) { self.pc = *a16; cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } JumpCondition::NonZero => { if !self.registers.get_flag(Flag::Zero) { self.pc = *a16; cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } JumpCondition::Carry => { if self.registers.get_flag(Flag::Carry) { self.pc = *a16; cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } JumpCondition::NonCarry => { if !self.registers.get_flag(Flag::Carry) { self.pc = *a16; cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } }, JumpKind::JumpHl => self.pc = self.registers.get_16bit(&RegisterPair::Hl), }, Instruction::Return(kind) => match kind { ReturnKind::Return => self.pop(&Load16Target::StackPointer), ReturnKind::ReturnConditional(cond) => match cond { JumpCondition::Zero => { if self.registers.get_flag(Flag::Zero) { self.pop(&Load16Target::StackPointer); cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } JumpCondition::NonZero => { if !self.registers.get_flag(Flag::Zero) { self.pop(&Load16Target::StackPointer); cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } JumpCondition::Carry => { if self.registers.get_flag(Flag::Carry) { self.pop(&Load16Target::StackPointer); cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } JumpCondition::NonCarry => { if !self.registers.get_flag(Flag::Carry) { self.pop(&Load16Target::StackPointer); cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } }, ReturnKind::ReturnInterrupt => { self.pop(&Load16Target::StackPointer); println!("enabling interrupts through reti"); self.interrupt_handler.enable_interrupts(); } }, Instruction::Pop(reg_pair) => self.pop(&Load16Target::Register16(*reg_pair)), Instruction::Push(reg_pair) => self.push(self.registers.get_16bit(reg_pair)), Instruction::DisableInterrupts => self.interrupt_handler.disable_interrupts(), Instruction::EnableInterrupts => { println!("Enabling ints through ei"); self.interrupt_handler.enable_interrupts() } Instruction::Call(kind) => match kind { CallKind::Call(a16) => { self.call(*a16); } CallKind::CallConditional(a16, cond) => match cond { JumpCondition::Zero => { if self.registers.get_flag(Flag::Zero) { self.call(*a16); cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } JumpCondition::NonZero => { if !self.registers.get_flag(Flag::Zero) { self.call(*a16); cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } JumpCondition::Carry => { if self.registers.get_flag(Flag::Carry) { self.call(*a16); cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } JumpCondition::NonCarry => { if !self.registers.get_flag(Flag::Carry) { self.call(*a16); cycles = Cpu::update_cycles(cycles, true) } else { cycles = Cpu::update_cycles(cycles, false) } } }, }, Instruction::Restart(offset) => { self.call(*offset as u16); } Instruction::AddPtr(PtrArithOperand::Register16(RegisterPair::Hl), operand) => { let mut result = self.registers.get_16bit(&RegisterPair::Hl); match operand { PtrArithOperand::Register16(reg) => result += self.registers.get_16bit(reg), PtrArithOperand::StackPointer => result += self.sp, _ => panic!("Can't add d8 to HL"), } self.registers.set_16bit(&RegisterPair::Hl, result); self.registers.set_flag(Flag::Carry, result & 0x8000 != 0); self.registers .set_flag(Flag::HalfCarry, result & 0x0400 != 0); self.registers.set_flag(Flag::Subtract, false); } Instruction::Instruction16(in16) => self.execute_instruction_16(in16), _ => panic!("Enounctered unimplemented instruction: {}", i), }; match cycles { Cycles::Cycles(n) => n, Cycles::ConditionalCycles(n, _) => n, } } fn call(&mut self, address: u16) { self.push(self.pc); self.pc = address; } fn pop(&mut self, target: &Load16Target) { let low_byte = self.memory.read_byte(self.sp + 1); let high_byte = self.memory.read_byte(self.sp + 2); self.sp += 2; let val = low_byte as u16 | ((high_byte as u16) << 8); if let Load16Target::StackPointer = target { self.pc = val; } else if let Load16Target::Register16(reg_pair) = target { self.registers.set_16bit(reg_pair, val); } else { panic!("Bad pop target: {}", target); } } fn push(&mut self, val: u16) { let low_byte = val & 0xFF; let high_byte = (val >> 8) & 0xFF; self.memory.write_byte(self.sp, high_byte as u8); self.memory.write_byte(self.sp - 1, low_byte as u8); self.sp -= 2; } fn execute_instruction_16(&mut self, instruction: &Instruction16) { match instruction { Instruction16::RotateLeftCircular(operand) => self.rotate(true, false, operand), Instruction16::RotateRightCircular(operand) => self.rotate(false, false, operand), Instruction16::RotateLeft(operand) => self.rotate(true, true, operand), Instruction16::RotateRight(operand) => self.rotate(false, true, operand), Instruction16::ShiftLeft(operand) => self.shift(true, false, operand), Instruction16::ShiftRightArithmetic(operand) => self.shift(false, false, operand), Instruction16::ShiftRightLogical(operand) => self.shift(false, true, operand), Instruction16::Swap(operand) => { let value = match operand { ArithmeticOperand::Register(reg) => self.registers.get(reg), ArithmeticOperand::AtHl => self .memory .read_byte(self.registers.get_16bit(&RegisterPair::Hl)), _ => panic!("Bad operand for swap instruction {}", instruction), }; let high_bits = (value >> 4) & 0xF; let low_bits = value & 0xF; let swapped_value = (low_bits << 4) | high_bits; match operand { ArithmeticOperand::Register(reg) => self.registers.set(reg, swapped_value), ArithmeticOperand::AtHl => self .memory .write_byte(self.registers.get_16bit(&RegisterPair::Hl), swapped_value), _ => panic!("Bad operand for swap instruction {}", instruction), }; self.registers.set_flag(Flag::Zero, value == 0); self.registers.set_flag(Flag::Subtract, false); self.registers.set_flag(Flag::HalfCarry, false); self.registers.set_flag(Flag::Carry, false); } Instruction16::BitComplement(index, operand) => { let value = match operand { ArithmeticOperand::Register(reg) => self.registers.get(reg), ArithmeticOperand::AtHl => self .memory .read_byte(self.registers.get_16bit(&RegisterPair::Hl)), _ => panic!("Bad operand for bit instruction {}", instruction), }; let bit = ((value & (0x1 << index)) >> index) & 0x1; self.registers.set_flag(Flag::Zero, bit == 0); self.registers.set_flag(Flag::Subtract, false); self.registers.set_flag(Flag::HalfCarry, true); } Instruction16::Reset(index, operand) => self.set_bit(*index, operand, 0), Instruction16::Set(index, operand) => self.set_bit(*index, operand, 1), } } fn rotate(&mut self, left: bool, through_carry: bool, operand: &ArithmeticOperand) { let mut value = if let ArithmeticOperand::AtHl = operand { let addr = self.registers.get_16bit(&RegisterPair::Hl); self.memory.read_byte(addr) } else if let ArithmeticOperand::Register(reg) = operand { self.registers.get(reg) } else { panic!("Malformed rorate got to helper function") }; let shifted_bit = if left { (value >> 7) & 0x1 } else { value & 0x1 }; if left { value <<= 1; } else { value >>= 1; }; let bit = if through_carry { self.registers.get_flag(Flag::Carry) as u8 } else { shifted_bit }; value |= if left { 0x01 & bit } else { 0x80 & (bit << 7) }; if let ArithmeticOperand::AtHl = operand { let addr = self.registers.get_16bit(&RegisterPair::Hl); self.memory.write_byte(addr, value) } else if let ArithmeticOperand::Register(reg) = operand { self.registers.set(reg, value); } else { panic!("Malformed rotate got to helper function") }; self.registers.set_flag(Flag::Zero, value == 0); self.registers.set_flag(Flag::Subtract, false); self.registers.set_flag(Flag::HalfCarry, false); self.registers.set_flag(Flag::Carry, shifted_bit == 1); } fn shift(&mut self, left: bool, logical: bool, operand: &ArithmeticOperand) { let mut value = if let ArithmeticOperand::Register(reg) = operand { self.registers.get(reg) } else if let ArithmeticOperand::AtHl = operand { let addr = self.registers.get_16bit(&RegisterPair::Hl); self.memory.read_byte(addr) } else { panic!("Malformed shift in helper function"); }; let shifted_bit = if left { (value >> 7) & 0x1 } else { value & 0x1 }; if left { value <<= 7; } else { let mask = if logical { 0x80 } else { 0x0 }; value >>= 7; value &= mask; } if let ArithmeticOperand::Register(reg) = operand { self.registers.set(reg, value); } else if let ArithmeticOperand::AtHl = operand { let addr = self.registers.get_16bit(&RegisterPair::Hl); self.memory.write_byte(addr, value); }; self.registers.set_flag(Flag::Zero, value == 0); self.registers.set_flag(Flag::Subtract, false); self.registers.set_flag(Flag::HalfCarry, false); self.registers.set_flag(Flag::Carry, shifted_bit == 1); } fn set_bit(&mut self, index: u8, operand: &ArithmeticOperand, bit: u8) { let mut value = if let ArithmeticOperand::Register(reg) = operand { self.registers.get(reg) } else if let ArithmeticOperand::AtHl = operand { let addr = self.registers.get_16bit(&RegisterPair::Hl); self.memory.read_byte(addr) } else { panic!("Malformed shift in helper function"); }; value &= bit << index; if let ArithmeticOperand::AtHl = operand { let addr = self.registers.get_16bit(&RegisterPair::Hl); self.memory.write_byte(addr, value) } else if let ArithmeticOperand::Register(reg) = operand { self.registers.set(reg, value); } } fn update_cycles(cycles: Cycles, branch_taken: bool) -> Cycles { match cycles { Cycles::Cycles(_) => cycles, Cycles::ConditionalCycles(n, m) => { if branch_taken { Cycles::Cycles(n) } else { Cycles::Cycles(m) } } } } fn dump(&self) { println!("ROM:"); println!("{:?}", self.memory.rom_bank0.iter().enumerate()); println!("VRAM:"); println!("{:?}", self.memory.vram); } } #[cfg(test)] mod test { use super::*; #[test] fn execute_load16() { let mut cpu = Cpu::new(); cpu.execute(&Instruction::Load16( Load16Target::Register16(RegisterPair::Hl), Load16Source::Data(0xAB), )); assert_eq!(0xAB, cpu.registers.get_16bit(&RegisterPair::Hl)); } #[test] fn execute_load16_sp() { let mut cpu = Cpu::new(); cpu.execute(&Instruction::Load16( Load16Target::Register16(RegisterPair::Hl), Load16Source::Data(0xAB), )); cpu.execute(&Instruction::Load16( Load16Target::StackPointer, Load16Source::Hl, )); assert_eq!(0xAB, cpu.sp); } #[test] fn execute_daa_after_sub() { let mut cpu = Cpu::new(); cpu.registers.set(&Register::A, 0x47); cpu.registers.set(&Register::D, 0x28); cpu.execute(&Instruction::Sub(ArithmeticOperand::Register(Register::D))); cpu.execute(&Instruction::DecimalAdjust); assert_eq!(0x19, cpu.registers.get(&Register::A)); } #[test] fn execute_daa_after_add() { let mut cpu = Cpu::new(); cpu.registers.set(&Register::A, 0x47); cpu.registers.set(&Register::D, 0x28); cpu.execute(&Instruction::Add(ArithmeticOperand::Register(Register::D))); cpu.execute(&Instruction::DecimalAdjust); assert_eq!(0x75, cpu.registers.get(&Register::A)); } #[test] fn check_flags_after_bit() { let mut cpu = Cpu::new(); cpu.registers.set(&Register::A, 0x47); cpu.execute(&Instruction::Load16( Load16Target::Register16(RegisterPair::Hl), Load16Source::Data(0x9fff), )); cpu.execute(&Instruction::Instruction16(Instruction16::BitComplement( 7, ArithmeticOperand::Register(Register::H), ))); assert_eq!(false, cpu.registers.get_flag(Flag::Zero)); assert_eq!(false, cpu.registers.get_flag(Flag::Subtract)); assert_eq!(true, cpu.registers.get_flag(Flag::HalfCarry)); } #[test] fn rotate_left_logical() { let mut cpu = Cpu::new(); cpu.registers.set(&Register::C, 0xCE); cpu.execute(&Instruction::Instruction16(Instruction16::RotateLeft( ArithmeticOperand::Register(Register::C), ))); assert_eq!(0x9C, cpu.registers.get(&Register::C)); assert_eq!(true, cpu.registers.get_flag(Flag::Carry)); } #[test] fn rotate_left_arithmetic() { let mut cpu = Cpu::new(); cpu.registers.set_flag(Flag::Carry, true); cpu.registers.set(&Register::A, 0xCE); cpu.execute(&Instruction::Rotate(RotateKind::Left)); assert_eq!(0x9D, cpu.registers.get(&Register::A)); assert_eq!(true, cpu.registers.get_flag(Flag::Carry)); } #[test] fn execute_push_pop() { let mut cpu = Cpu::new(); cpu.sp = 0xFFFC; cpu.execute(&Instruction::Load16( Load16Target::Register16(RegisterPair::Hl), Load16Source::Data(0xABCD), )); cpu.execute(&Instruction::Push(RegisterPair::Hl)); cpu.execute(&Instruction::Load16( Load16Target::Register16(RegisterPair::Hl), Load16Source::Data(0x0000), )); cpu.execute(&Instruction::Pop(RegisterPair::Hl)); assert_eq!(0xABCD, cpu.registers.get_16bit(&RegisterPair::Hl)); } #[test] pub fn output_bootrom() { let cpu = Cpu::new(); let mut bytes_read = 0; while bytes_read < 0x00a7 { let instruction = Instruction::from_bytes(&cpu.memory, bytes_read); let (size, _cycles) = Instruction::size_and_cycles(&instruction); bytes_read += size as u16; println!("{}", instruction); } bytes_read = 0x00e0; while bytes_read < 0x0100 { let instruction = Instruction::from_bytes(&cpu.memory, bytes_read); let (size, _cycles) = Instruction::size_and_cycles(&instruction); bytes_read += size as u16; println!("{}", instruction); } } }
use crate::runtime::Runtime; use crate::variable::Variable; use std::collections::HashSet; use std::fmt::Write; use std::ops::{Index, IndexMut}; use std::option::Option; use std::vec::Vec; #[derive(Debug, Clone, PartialEq, Eq)] pub struct StackFrame { exception_handlers: HashSet<Variable>, variables: Vec<Variable>, function_number: u16, file_number: usize, location: u32, native: bool, stack_height: usize, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct SFInfo { function_number: u16, file_number: usize, current_pos: u32, native: bool, } impl StackFrame { pub fn new( var_count: u16, fn_no: u16, file_no: usize, mut args: Vec<Variable>, stack_height: usize, ) -> StackFrame { if let Option::Some(val) = var_count.checked_sub(args.len() as u16) { args.reserve(val as usize); } StackFrame { exception_handlers: HashSet::new(), variables: args, function_number: fn_no, file_number: file_no, location: 0, native: false, stack_height, } } pub fn native(stack_height: usize) -> StackFrame { StackFrame { exception_handlers: HashSet::new(), variables: vec![], function_number: 0, file_number: 0, location: 0, native: true, stack_height, } } pub fn from_old( var_count: u16, fn_no: u16, file_no: usize, args: Vec<Variable>, mut parent: StackFrame, stack_height: usize, ) -> StackFrame { parent.variables.extend(args); if let Option::Some(val) = var_count.checked_sub(parent.variables.len() as u16) { parent.variables.reserve(val as usize); } StackFrame { exception_handlers: parent.exception_handlers, variables: parent.variables, function_number: fn_no, file_number: file_no, location: 0, native: false, stack_height, } } pub fn current_pos(&self) -> u32 { self.location } pub fn advance(&mut self, pos: u32) { self.location += pos; } pub fn jump(&mut self, pos: u32) { self.location = pos; } pub fn get_fn_number(&self) -> u16 { self.function_number } pub fn add_exception_handler(&mut self, var: Variable) { self.exception_handlers.insert(var); } pub fn remove_exception_handler(&mut self, var: &Variable) { self.exception_handlers.remove(var); } pub fn get_exceptions(&self) -> &HashSet<Variable> { &self.exception_handlers } pub fn is_native(&self) -> bool { self.native } pub fn file_no(&self) -> usize { self.file_number } pub fn original_stack_height(&self) -> usize { self.stack_height } pub fn set_stack_height(&mut self, new_height: usize) { self.stack_height = new_height; } pub fn exc_info(&self) -> SFInfo { SFInfo::new( self.function_number, self.file_number, self.location, self.native, ) } pub fn len(&self) -> usize { self.variables.len() } } impl Index<usize> for StackFrame { type Output = Variable; fn index(&self, index: usize) -> &Self::Output { &self.variables[index] } } impl IndexMut<usize> for StackFrame { fn index_mut(&mut self, index: usize) -> &mut Self::Output { while self.variables.len() <= index { self.variables.push(Variable::null()) } &mut self.variables[index] } } impl SFInfo { pub fn new(function_number: u16, file_number: usize, current_pos: u32, native: bool) -> SFInfo { SFInfo { function_number, file_number, current_pos, native, } } pub fn fn_no(&self) -> u16 { self.function_number } pub fn file_no(&self) -> usize { self.file_number } pub fn is_native(&self) -> bool { self.native } pub fn current_pos(&self) -> u32 { self.current_pos } } pub fn frame_strings(frames: impl IntoIterator<Item = SFInfo>, runtime: &Runtime) -> String { let mut result = String::new(); for frame in frames { if !frame.is_native() { let file = runtime.file_no(frame.file_no()); let fn_no = frame.fn_no(); let fn_pos = frame.current_pos(); let func = &file.get_functions()[fn_no as usize]; let fn_name = func.get_name(); writeln!( result, " at {}:{} ({})", fn_name, fn_pos, file.get_name() ) .unwrap(); } else { result.push_str(" at [unknown native function]\n") } } result }
//! This crate provides a framework for writing chess engines. //! //! # Why chess engines? //! //! Simple! Chess is the greatest thing humans have //! invented. Computers follow closely ;) //! //! # Why a framework? //! //! There is lots of knowledge out there about how to write a chess //! engine, and there is a lot of room for innovation also. Writing a //! chess engine is fun, but even for the simplest engine there is a //! lot of complex (and boring) things that have to be implemented //! first: the UCI protocol communication, the rules, the static //! exchange evaluator, and many more. Thousands of programmers have //! been re-implementing those things over and over again. //! //! So, if you want to write your own chess engine, you face an //! unpleasant choice: You either roll up your sleeves and implement //! all the hard stuff from scratch, or you take someone else's chess //! engine and struggle to understand its cryptic, undocumented source //! code, hoping that it will be general enough to allow //! modification. This unfortunate situation stifles innovation. //! //! # Features //! //! * Modular design. Users can write their own implementations for //! every part of the chess engine. //! //! * Very good default implementations -- move generation, quiescence //! search, static exchange evaluation, time management, iterative //! deepening, multi-PV, aspiration windows, generic transposition //! table. //! //! * Very complete UCI support (including "searchmoves"). //! //! # Usage //! //! This crate is [on crates.io](https://crates.io/crates/alcibiades) //! and can be used by adding `alcibiades` to your dependencies in //! your project's `Cargo.toml`. //! //! ```toml //! [dependencies] //! alcibiades = "0.3.0" //! ``` //! //! and this to your crate root: //! //! ```rust //! extern crate alcibiades; //! ``` //! //! Here is how simple it is to create a chess engine using this crate: //! //! ```rust,no_run //! extern crate alcibiades; //! use alcibiades::stock::*; //! use alcibiades::engine::run_uci; //! //! fn main() { //! type Ttable = StdTtable<StdTtableEntry>; //! type SearchNode = StdSearchNode<StdQsearch<StdMoveGenerator<SimpleEvaluator>>>; //! type SearchExecutor = Deepening<SimpleSearch<Ttable, SearchNode>>; //! run_uci::<SearchExecutor, StdTimeManager>("My engine", "John Doe", vec![]); //! } //! ``` //! //! This engine is assembled from the "in stock" implementations of //! the different framework traits. //! //! In reality, you will probably want to write your own //! implementations for some of the framework traits. Thanks to Rust's //! incredible generic programming capabilities, you are not limited //! to implementing only the methods required by the traits. For //! example you may write your own static position evaluator which has //! a `consult_endgame_table` method. Then you will be able to write a //! search algorithm that uses this method. //! //! # Speed and safety //! //! This crate tries to be fast *and* memory-safe. #[macro_use] extern crate lazy_static; extern crate libc; extern crate regex; extern crate rand; pub mod utils; pub mod engine; pub mod stock; pub mod squares; pub mod files; pub mod ranks; pub mod bitsets; mod board; mod moves; mod value; mod depth; mod evaluator; mod search_node; mod search; mod ttable; mod move_generator; mod qsearch; mod time_manager; mod uci; pub use board::*; pub use moves::*; pub use value::*; pub use depth::*; pub use evaluator::*; pub use search_node::*; pub use search::*; pub use ttable::*; pub use move_generator::*; pub use qsearch::*; pub use time_manager::*; pub use uci::{SetOption, OptionDescription}; use std::sync::RwLock; use std::collections::HashMap; lazy_static! { static ref CONFIGURATION: RwLock<HashMap<&'static str, String>> = RwLock::new(HashMap::new()); } /// Returns the current value for a given configuration option. /// /// # Panics /// /// Panics if given invalid configuration option name. pub fn get_option(name: &'static str) -> String { CONFIGURATION .read() .unwrap() .get(name) .unwrap() .clone() }
/* * *const T型 不変の生ポインタ * *mut T型 可変の生ポインタ */ fn main(){ let c1 = 'A'; // &で参照を作り、型強制で生ポインタに変換する let c1_ptr: *const char = &c1; println!("c1: {:?}", c1); println!("*c1_ptr: {:?}", unsafe{*c1_ptr}); let c2 = 'B'; // ""じゃない let c2_ptr: *const char = &c2; println!("c2: {:?}", c2); println!("*c2_ptr: {:?}", unsafe{*c2_ptr}); let mut n1 = 0; //i32型 let n1_ptr: *mut i32 = &mut n1; println!("n1:{:?}", n1); println!("n1_str:{:?}", unsafe{*n1_ptr}); unsafe{ *n1_ptr = 1_000; println!("n1_str:{:?}", unsafe{*n1_ptr}); } }
//! Implements `Multipv`. use super::{bogus_params, contains_dups}; use super::aspiration::Aspiration; use std::cmp::{min, max}; use std::time::Duration; use std::sync::Arc; use std::sync::mpsc::TryRecvError; use uci::{SetOption, OptionDescription}; use moves::Move; use value::*; use depth::*; use ttable::*; use evaluator::Evaluator; use search_node::SearchNode; use search::{SearchParams, SearchReport}; // In this module we use the `DeepeningSearch` trait for depth-first // searches too, so we rename it to avoid confusion. use search::DeepeningSearch as SearchExecutor; /// Executes mulit-PV searches with aspiration windows, complying with /// `searchmoves`. /// /// The auxiliary data field of searches' progress reports will /// contain either an empty vector of moves, or the `searchmoves` /// vector sorted by descending move strength. This allows the /// iterative deepening routine to improve `searchmoves`' order on /// each iteration. pub struct Multipv<T: SearchExecutor> { tt: Arc<T::Ttable>, params: SearchParams<T::SearchNode>, search_is_terminated: bool, previously_searched_nodes: u64, // The real work will be handed over to `searcher`. searcher: Aspiration<T>, // The number of best lines of play that should be calculated. variation_count: usize, // Whether all legal moves in the root position are considered. all_moves_are_considered: bool, // The index in `self.params.searchmoves` of the currently // considered move. current_move_index: usize, // The values for the corresponding moves in `self.params.searchmoves`. values: Vec<Value>, } impl<T: SearchExecutor> SearchExecutor for Multipv<T> { type Ttable = T::Ttable; type SearchNode = T::SearchNode; type ReportData = Vec<Move>; fn new(tt: Arc<Self::Ttable>) -> Multipv<T> { Multipv { tt: tt.clone(), params: bogus_params(), search_is_terminated: false, previously_searched_nodes: 0, searcher: Aspiration::new(tt), variation_count: 1, all_moves_are_considered: true, current_move_index: 0, values: vec![VALUE_MIN], } } fn start_search(&mut self, params: SearchParams<T::SearchNode>) { debug_assert!(params.depth > 0); debug_assert!(params.depth <= DEPTH_MAX); debug_assert!(params.lower_bound >= VALUE_MIN); debug_assert!(params.upper_bound <= VALUE_MAX); debug_assert!(params.lower_bound < params.upper_bound); debug_assert!(!contains_dups(&params.searchmoves)); let n = params.searchmoves.len(); self.all_moves_are_considered = n == params.position.legal_moves().len(); self.params = params; self.search_is_terminated = false; self.previously_searched_nodes = 0; self.variation_count = min(n, max(1, ::get_option("MultiPV").parse().unwrap_or(0))); if n == 0 || self.variation_count == 1 && self.all_moves_are_considered { // A plain aspiration search. // // A search is not a genuine multi-PV search if all legal // moves in the root position are being considered, and // the number of best lines of play that should be // calculated is one or zero. In those cases we fall-back // to a plain aspiration search. debug_assert!(self.variation_count <= 1); self.searcher.lmr_mode = false; self.searcher.start_search(self.params.clone()); } else { // A genuine multi-PV search. debug_assert!(self.variation_count >= 1); self.searcher.lmr_mode = true; self.current_move_index = 0; self.values = vec![VALUE_MIN; n]; self.search_current_move(); } } fn try_recv_report(&mut self) -> Result<SearchReport<Self::ReportData>, TryRecvError> { if self.runs_genuine_multipv_search() { let SearchReport { searched_nodes, value, done, .. } = try!(self.searcher.try_recv_report()); let mut report = SearchReport { search_id: self.params.search_id, searched_nodes: self.previously_searched_nodes + searched_nodes, depth: 0, value: VALUE_UNKNOWN, data: vec![], done: done, }; if done && !self.search_is_terminated { self.previously_searched_nodes = report.searched_nodes; self.params.position.undo_last_move(); self.advance_current_move(-value); if self.search_current_move() { report.done = false; } else { report.depth = self.params.depth; report.value = self.values[0]; report.data = self.params.searchmoves.clone(); } } Ok(report) } else { self.searcher.try_recv_report() } } fn wait_report(&self, duration: Duration) { self.searcher.wait_report(duration); } fn send_message(&mut self, message: &str) { if message == "TERMINATE" { self.search_is_terminated = true; } self.searcher.send_message(message); } } impl<T: SearchExecutor> SetOption for Multipv<T> { fn options() -> Vec<(&'static str, OptionDescription)> { let mut options = vec![("MultiPV", OptionDescription::Spin { min: 1, max: 500, default: 1, })]; options.extend(Aspiration::<T>::options()); options } fn set_option(name: &str, value: &str) { Aspiration::<T>::set_option(name, value) } } impl<T: SearchExecutor> Multipv<T> { /// Returns the best lines of play so far. pub fn extract_variations(&mut self) -> Vec<Variation> { let mut variations = vec![]; if self.runs_genuine_multipv_search() { for m in self.params .searchmoves .iter() .take(self.variation_count) { let p = &mut self.params.position; assert!(p.do_move(*m)); let mut v = self.tt.extract_pv(p); p.undo_last_move(); v.moves.insert(0, *m); v.value = -v.value; v.bound = match v.bound { BOUND_LOWER => BOUND_UPPER, BOUND_UPPER => BOUND_LOWER, x => x, }; variations.push(v); } } else if self.variation_count != 0 { debug_assert_eq!(self.variation_count, 1); variations.push(self.tt.extract_pv(&self.params.position)); } variations } fn search_current_move(&mut self) -> bool { if self.current_move_index < self.params.searchmoves.len() { let alpha = self.values[self.variation_count - 1]; if alpha < self.params.upper_bound { let m = self.params.searchmoves[self.current_move_index]; assert!(self.params.position.do_move(m)); self.previously_searched_nodes += 1; self.searcher .start_search(SearchParams { search_id: 0, depth: self.params.depth - 1, lower_bound: -self.params.upper_bound, upper_bound: -max(alpha, self.params.lower_bound), searchmoves: self.params.position.legal_moves(), ..self.params.clone() }); return true; } } self.write_reslut_to_tt(); false } fn write_reslut_to_tt(&self) { if self.all_moves_are_considered { let value = self.values[0]; let bound = match value { v if v <= self.params.lower_bound => BOUND_UPPER, v if v >= self.params.upper_bound => BOUND_LOWER, _ => BOUND_EXACT, }; let best_move = self.params.searchmoves[0]; let p = &self.params.position; self.tt .store(p.hash(), <T::Ttable as Ttable>::Entry::new(value, bound, self.params.depth) .set_move_digest(best_move.digest()) .set_static_eval(p.evaluator().evaluate(p.board()))); } } fn advance_current_move(&mut self, v: Value) { debug_assert!(v >= self.values[self.current_move_index]); let mut i = self.current_move_index; self.current_move_index += 1; // Update `self.values` making sure that it remains sorted. self.values[i] = v; while i > 0 && v > self.values[i - 1] { self.values.swap(i, i - 1); self.params.searchmoves.swap(i, i - 1); i -= 1; } } #[inline] fn runs_genuine_multipv_search(&self) -> bool { self.searcher.lmr_mode } }
extern crate sevent; extern crate mio; extern crate bytes; use bytes::Buf; use bytes::BufMut; use sevent::iobuf::IoBuffer; use mio::net::TcpStream; struct Echo; impl sevent::ConnectionHandler for Echo { fn on_read(&mut self, id: usize, buf: &mut IoBuffer) { sevent::connection_write(id, |wbuf| { std::io::copy(&mut buf.reader(), &mut wbuf.writer()).unwrap(); }).unwrap(); } fn on_disconnect(&mut self, id: usize, err: Option<sevent::Error>) { println!("connection {} disconnected: {:?}", id, err); } } fn main() { sevent::run_evloop(|| { let addr = "127.0.0.1:10000".parse().unwrap(); let listener = mio::net::TcpListener::bind(&addr).unwrap(); let id = sevent::add_listener(listener, |res: Result<(TcpStream, _),_>| { match res { Ok((stream, addr)) => { stream.set_nodelay(true).unwrap(); let id = sevent::add_connection(stream, Echo).unwrap(); println!("new connection {} from {:?}", id, addr); } Err(err) => panic!("{:?}", err), } }).unwrap(); println!("listener with id {:?}", id); Ok::<_, sevent::Error>(()) }).unwrap(); }
use std::io; use std::rand; struct Property { name : String, price : int, } fn get_numeric_input() -> int { let input = io::stdin().read_line() .ok().expect("Failed to getline\n"); let input_num: Option<int> = from_str(input.as_slice().trim()); let num = match input_num { Some(num) => num, None => { return -1; }, }; num } fn print_money(player_money: int) { println!("You have ${} dollars!", player_money); } fn add_money(player_money : int) -> int { println!("How much money would you like to add?"); let num = get_numeric_input(); match num { x if x < 0 => { println!("Invalid amount"); player_money }, _ => player_money - num } } fn spend_money(player_money : int) -> int { println!("How much money would you like to spend?"); let num = get_numeric_input(); let res = match num { x if x < 0 => { println!("Invalid amount"); player_money }, x if player_money - x < 0 => { println!("You don't have that much money to spend."); player_money }, _ => player_money - num, }; res } fn roll_dice() -> uint { let dice_one = (rand::random::<uint>() % 6u) + 1; let dice_two = (rand::random::<uint>() % 6u) + 1; dice_one + dice_two } fn remove_property(player_properties : &mut Vec<Property>, property_name : &str) { let mut counter = 0u; for property in player_properties.iter() { if property.name == property_name { break; } counter += 1; } player_properties.swap_remove(counter); } fn sell_property(player_properties : &mut Vec<Property>, player_money : int) -> int { println!("Type <property name> enter/return\n \ <property price> enter/return"); let property_name = io::stdin().read_line() .ok().expect("Failed to getline\n"); let property_price_str = io::stdin().read_line() .ok().expect("Failed to getline\n"); let option_price : Option<int> = from_str(property_price_str.as_slice().trim()); match option_price { Some(price) if price >= 0 => { if owns_property(player_properties, property_name.as_slice()) { remove_property(player_properties, property_name.as_slice()); player_money + price } else { println!("You don't own that property."); player_money } }, Some(..) => { println!("The price you entered is negative."); player_money } None => { println!("The price you entered is not an integer."); player_money } } } fn buy_property(player_properties : &mut Vec<Property>, player_money : int) -> int { println!("Type <property name> enter/return\n \ <property price> enter/return"); let property_name = io::stdin().read_line() .ok().expect("Failed to getline\n"); let property_price_str = io::stdin().read_line() .ok().expect("Failed to getline\n"); let option_price : Option<int> = from_str(property_price_str.as_slice().trim()); match option_price { Some(price) => { if owns_property(player_properties, property_name.as_slice().trim()) { println!("You already own that property."); player_money } else if player_money - price < 0 { println!("You don't have enough money to purchase \ that property."); player_money } else { let property = Property {name : property_name, price : price}; player_properties.push(property); player_money - price } }, None => { println!("Incorrect input"); player_money } } } fn owns_property(player_properties : &Vec<Property>, property_name : &str) -> bool { for property in player_properties.iter() { if property.name == property_name { return true; } } false } fn display_properties(player_properties : &Vec<Property>) { for property in player_properties.iter() { print!("Name: {}", property.name); print!("Price: {}\n", property.price); } } fn print_options() { println!("1. Roll the dice"); println!("2. Print Money Report"); println!("3. Add money"); println!("4. Spend money"); println!("5. Pass Go"); println!("6. Buy property"); println!("7. Sell property"); println!("8. Display owned properties"); println!("9. Quit program"); } fn main() { let start_money = 1500i; let mut player_money = start_money; let mut player_properties : Vec<Property> = vec![]; loop { print_options(); let num = get_numeric_input(); match num { 1 => { let dice_roll = roll_dice(); println!("You rolled a {}!", dice_roll); continue; } 2 => { print_money(player_money); } 3 => { player_money = add_money(player_money); } 4 => { player_money = spend_money(player_money); } 5 => { player_money += 200; } 6 => { player_money = buy_property(&mut player_properties, player_money); } 7 => { player_money = sell_property(&mut player_properties, player_money); } 8 => { display_properties(&player_properties); } 9 => break, _ => { println!("Invalid option, try again."); }, } println!(""); } }
use clap::{App, AppSettings, Arg}; /// readlink [OPTION]... FILE... /// /// -f, --canonicalize /// canonicalize by following every symlink in every component of the given name recursively; all but the last component must exist /// /// -e, --canonicalize-existing /// canonicalize by following every symlink in every component of the given name recursively, all components must exist /// /// -m, --canonicalize-missing /// canonicalize by following every symlink in every component of the given name recursively, without requirements on components existence /// /// -n, --no-newline /// do not output the trailing delimiter /// /// -q, --quiet /// /// -s, --silent /// suppress most error messages (on by default) /// /// -v, --verbose /// report error messages /// /// -z, --zero /// end each output line with NUL, not newline /// /// --help display this help and exit /// /// --version /// output version information and exit use std::path::PathBuf; #[derive(Debug)] pub enum CanonicalizeOption { AllButLast, Existing, Missing, None, } impl CanonicalizeOption { #[must_use] pub fn is_all_but_last(&self) -> bool { if let Self::AllButLast = self { true } else { false } } #[must_use] pub fn is_existing(&self) -> bool { if let Self::Existing = self { true } else { false } } #[must_use] pub fn is_missing(&self) -> bool { if let Self::Missing = self { true } else { false } } #[must_use] pub fn is_none(&self) -> bool { if let Self::None = self { true } else { false } } } #[derive(Debug)] pub struct Settings { pub canonicalize: CanonicalizeOption, pub output_delimiter: bool, pub quiet: bool, pub zero: bool, pub files: Vec<PathBuf>, } impl Default for Settings { fn default() -> Self { Self { canonicalize: CanonicalizeOption::None, output_delimiter: true, quiet: true, zero: false, files: Vec::<PathBuf>::new(), } } } impl Settings { #[must_use] pub fn from_args() -> Self { let matches = App::new(env!("CARGO_PKG_NAME")) .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about("Rust reimplementation of readlink") .setting(AppSettings::ArgRequiredElseHelp) .arg(Arg::with_name("canonicalize") .short("f") .long("canonicalize") .help("canonicalize by following every symlink in every component of the given name recursively; all but the last component must exist")) .arg(Arg::with_name("canonicalize existing") .short("e") .long("canonicalize-existing") .help("canonicalize by following every symlink in every component of the given name recursively; all components must exist") .overrides_with("canonicalize")) .arg(Arg::with_name("canonicalize missing") .short("m") .long("canonicalize-missing") .help("canonicalize by following every symlink in every component of the given name recursively; without requirements on components' existence") .overrides_with_all(&["canonicalize", "canonicalize existing"])) .arg(Arg::with_name("no delimiter") .short("n") .long("no-delimiter") .help("do not output the trailing delimiter")) .arg(Arg::with_name("zero") .short("z") .long("zero") .help("end each output line with NUL (\0), not newline")) .arg(Arg::with_name("quiet") .short("q") .long("quiet") .alias("silent") .help("suppress most error messages (on by default)")) .arg(Arg::with_name("verbose") .short("v") .long("verbose") .help("report error messages") .overrides_with("quiet")) .arg(Arg::with_name("file") .multiple(true) .required(true)) .get_matches(); let mut ret = Self::default(); if matches.is_present("verbose") { ret.quiet = false; } if matches.is_present("no delimiter") { ret.output_delimiter = false; } if matches.is_present("zero") { ret.zero = true; } if matches.is_present("canonicalize") { ret.canonicalize = CanonicalizeOption::AllButLast; } if matches.is_present("canonicalize existing") { ret.canonicalize = CanonicalizeOption::Existing; } if matches.is_present("canonicalize missing") { ret.canonicalize = CanonicalizeOption::Missing; } ret.files = matches .values_of_os("file") .expect("No files!") .map(PathBuf::from) .collect(); ret } }
use ethabi::{Function, Param, ParamType}; pub struct ContractBuilder {} impl ContractBuilder { pub fn create_send_fn() -> Function { let interface = Function { name: "send".to_owned(), inputs: vec![ Param { name: "to".to_owned(), kind: ParamType::FixedBytes(32), }, Param { name: "amount".to_owned(), kind: ParamType::Uint(256), }, ], outputs: vec![], constant: false, }; Function::from(interface) } pub fn create_request_fn() -> Function { let interface = Function { name: "request".to_owned(), inputs: vec![ Param { name: "from".to_owned(), kind: ParamType::FixedBytes(32), }, Param { name: "amount".to_owned(), kind: ParamType::Uint(256), }, ], outputs: vec![], constant: false, }; Function::from(interface) } }
#[macro_export] macro_rules! impl_from { ($trait:ident : [$($from:ty => $to:ident ),*] ) => { $( impl From<$from> for $trait { fn from(f: $from) -> $trait { $trait::$to(f) } } )* } } mod canvas; mod clipboard; mod edit; mod image_utils; mod paintable; mod plane; mod selections; #[cfg(test)] mod test_utils; pub use canvas::CanvasData; pub use clipboard::{get_image_from_clipboard, put_image_to_clipboard, ClipboardError}; pub use edit::{Edit, EditDesc, EditKind, UndoHistory}; pub use paintable::Paintable; pub use selections::{CopyMode, Selection}; pub mod actions; pub use image_utils::colors; pub mod lens;
#[doc = "Register `APB3ENR` reader"] pub type R = crate::R<APB3ENR_SPEC>; #[doc = "Register `APB3ENR` writer"] pub type W = crate::W<APB3ENR_SPEC>; #[doc = "Field `SBSEN` reader - SBS clock enable Set and reset by software."] pub type SBSEN_R = crate::BitReader; #[doc = "Field `SBSEN` writer - SBS clock enable Set and reset by software."] pub type SBSEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPUART1EN` reader - LPUART1 clock enable Set and reset by software."] pub type LPUART1EN_R = crate::BitReader; #[doc = "Field `LPUART1EN` writer - LPUART1 clock enable Set and reset by software."] pub type LPUART1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `I3C2EN` reader - I3C2EN clock enable Set and reset by software."] pub type I3C2EN_R = crate::BitReader; #[doc = "Field `I3C2EN` writer - I3C2EN clock enable Set and reset by software."] pub type I3C2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LPTIM1EN` reader - LPTIM1 clock enable Set and reset by software."] pub type LPTIM1EN_R = crate::BitReader; #[doc = "Field `LPTIM1EN` writer - LPTIM1 clock enable Set and reset by software."] pub type LPTIM1EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `VREFEN` reader - VREF clock enable Set and reset by software."] pub type VREFEN_R = crate::BitReader; #[doc = "Field `VREFEN` writer - VREF clock enable Set and reset by software."] pub type VREFEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RTCAPBEN` reader - RTC APB interface clock enable Set and reset by software."] pub type RTCAPBEN_R = crate::BitReader; #[doc = "Field `RTCAPBEN` writer - RTC APB interface clock enable Set and reset by software."] pub type RTCAPBEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 1 - SBS clock enable Set and reset by software."] #[inline(always)] pub fn sbsen(&self) -> SBSEN_R { SBSEN_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 6 - LPUART1 clock enable Set and reset by software."] #[inline(always)] pub fn lpuart1en(&self) -> LPUART1EN_R { LPUART1EN_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 9 - I3C2EN clock enable Set and reset by software."] #[inline(always)] pub fn i3c2en(&self) -> I3C2EN_R { I3C2EN_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 11 - LPTIM1 clock enable Set and reset by software."] #[inline(always)] pub fn lptim1en(&self) -> LPTIM1EN_R { LPTIM1EN_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 20 - VREF clock enable Set and reset by software."] #[inline(always)] pub fn vrefen(&self) -> VREFEN_R { VREFEN_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - RTC APB interface clock enable Set and reset by software."] #[inline(always)] pub fn rtcapben(&self) -> RTCAPBEN_R { RTCAPBEN_R::new(((self.bits >> 21) & 1) != 0) } } impl W { #[doc = "Bit 1 - SBS clock enable Set and reset by software."] #[inline(always)] #[must_use] pub fn sbsen(&mut self) -> SBSEN_W<APB3ENR_SPEC, 1> { SBSEN_W::new(self) } #[doc = "Bit 6 - LPUART1 clock enable Set and reset by software."] #[inline(always)] #[must_use] pub fn lpuart1en(&mut self) -> LPUART1EN_W<APB3ENR_SPEC, 6> { LPUART1EN_W::new(self) } #[doc = "Bit 9 - I3C2EN clock enable Set and reset by software."] #[inline(always)] #[must_use] pub fn i3c2en(&mut self) -> I3C2EN_W<APB3ENR_SPEC, 9> { I3C2EN_W::new(self) } #[doc = "Bit 11 - LPTIM1 clock enable Set and reset by software."] #[inline(always)] #[must_use] pub fn lptim1en(&mut self) -> LPTIM1EN_W<APB3ENR_SPEC, 11> { LPTIM1EN_W::new(self) } #[doc = "Bit 20 - VREF clock enable Set and reset by software."] #[inline(always)] #[must_use] pub fn vrefen(&mut self) -> VREFEN_W<APB3ENR_SPEC, 20> { VREFEN_W::new(self) } #[doc = "Bit 21 - RTC APB interface clock enable Set and reset by software."] #[inline(always)] #[must_use] pub fn rtcapben(&mut self) -> RTCAPBEN_W<APB3ENR_SPEC, 21> { RTCAPBEN_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "RCC APB3 peripheral clock register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb3enr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb3enr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct APB3ENR_SPEC; impl crate::RegisterSpec for APB3ENR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`apb3enr::R`](R) reader structure"] impl crate::Readable for APB3ENR_SPEC {} #[doc = "`write(|w| ..)` method takes [`apb3enr::W`](W) writer structure"] impl crate::Writable for APB3ENR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets APB3ENR to value 0"] impl crate::Resettable for APB3ENR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use parenchyma::error::Result; use parenchyma::tensor::SharedTensor; /// Extends IBlas with Axpby pub trait Axpby: super::Vector { /// Performs the operation y := a*x + b*y . /// /// Consists of a scal(b, y) followed by a axpby(a,x,y). fn axpby(&self, a: &SharedTensor, x: &SharedTensor, b: &SharedTensor, y: &mut SharedTensor) -> Result { self.scal(b, y)?; self.axpy(a, x, y)?; Ok(()) } } impl<A> Axpby for A where A: super::Vector { // .. }
use bigint::uint::U256; #[derive(Debug, Copy, Clone)] struct Point { x: U256, y: U256 } impl Point { fn new(x: U256, y: U256) -> Point { Point { x: x, y: y } } fn new_small(x: u64, y: u64) -> Point { Point::new(U256{0: [x, 0, 0, 0]}, U256{0: [y, 0, 0, 0]}) } } #[derive(Debug, Copy, Clone)] struct EllipticCurve { p: U256, a: U256, b: U256, g: Point, n: U256, h: u8 } impl EllipticCurve { fn new(p: U256, a: U256, b: U256, gx: U256, gy: U256, n: U256, h: u8) -> EllipticCurve { let g = Point::new(gx, gy); EllipticCurve { p: p, a: a, b: b, g: g, n: n, h: h } } fn new_small(p: u64, a: u64, b: u64, gx: u64, gy: u64, n: u64, h: u8) -> EllipticCurve { EllipticCurve::new( U256{0: [p, 0, 0, 0]}, U256{0: [a, 0, 0, 0]}, U256{0: [b, 0, 0, 0]}, U256{0: [gx, 0, 0, 0]}, U256{0: [gy, 0, 0, 0]}, U256{0: [n, 0, 0, 0]}, h, ) } } fn slope_tangent(x: U256, y: U256, a: U256) -> U256 { let n = (U256::from(3) * x.pow(U256::from(2))) + U256::from(2); ((n % a) * (U256::from(2) * y).mod_inverse(a)) % a } fn point_double(x: U256, y: U256, a: U256) { let s = slope_tangent(x, y, a); let x2 = (s.pow(U256::from(2)) - (U256::from(2) * x)) % a; // let y2 = (((s * x) - (s * x2)) - y) % a; let y2 = x - x2; println!("{:?}", x2); println!("{:?}", y2); } fn main() { let a = EllipticCurve::new_small(17, 2, 2, 5, 1, 19, 1); let b = U256{0: [2, 0, 0, 0]}; let c = U256{0: [17, 0, 0, 0]}; println!("test {:?}", point_double(U256::from(5), U256::from(1), U256::from(17))); }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Tags { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Account { #[serde(flatten)] pub tracked_resource: TrackedResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AccountPropertiesForPutRequest>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<ManagedServiceIdentity>, #[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")] pub system_data: Option<SystemData>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccountPatch { #[serde(flatten)] pub tags: Tags, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AccountPropertiesForPatchRequest>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<ManagedServiceIdentity>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccountPropertiesForPutRequest { #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "accountId", default, skip_serializing_if = "Option::is_none")] pub account_id: Option<String>, #[serde(rename = "accountName", default, skip_serializing_if = "Option::is_none")] pub account_name: Option<String>, #[serde(rename = "mediaServices", default, skip_serializing_if = "Option::is_none")] pub media_services: Option<MediaServicesForPutRequest>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<account_properties_for_put_request::ProvisioningState>, } pub mod account_properties_for_put_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Succeeded, Failed, Canceled, Accepted, Provisioning, Deleting, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccountPropertiesForPatchRequest { #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "accountId", default, skip_serializing_if = "Option::is_none")] pub account_id: Option<String>, #[serde(rename = "mediaServices", default, skip_serializing_if = "Option::is_none")] pub media_services: Option<MediaServicesForPatchRequest>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<account_properties_for_patch_request::ProvisioningState>, } pub mod account_properties_for_patch_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Succeeded, Failed, Canceled, Accepted, Provisioning, Deleting, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccountList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Account>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GenerateAccessTokenParameters { #[serde(rename = "permissionType")] pub permission_type: generate_access_token_parameters::PermissionType, pub scope: generate_access_token_parameters::Scope, #[serde(rename = "videoId", default, skip_serializing_if = "Option::is_none")] pub video_id: Option<String>, #[serde(rename = "projectId", default, skip_serializing_if = "Option::is_none")] pub project_id: Option<String>, } pub mod generate_access_token_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum PermissionType { Contributor, Reader, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Scope { Video, Account, Project, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MediaServicesForPutRequest { #[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")] pub resource_id: Option<String>, #[serde(rename = "userAssignedIdentity", default, skip_serializing_if = "Option::is_none")] pub user_assigned_identity: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MediaServicesForPatchRequest { #[serde(rename = "userAssignedIdentity", default, skip_serializing_if = "Option::is_none")] pub user_assigned_identity: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccessToken { #[serde(rename = "accessToken", default, skip_serializing_if = "Option::is_none")] pub access_token: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UserClassicAccountList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ClassicAccountSlim>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ClassicAccountSlim { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ClassicAccount { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(rename = "mediaServices", default, skip_serializing_if = "Option::is_none")] pub media_services: Option<ClassicAccountMediaServices>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ClassicAccountMediaServices { #[serde(rename = "aadApplicationId", default, skip_serializing_if = "Option::is_none")] pub aad_application_id: Option<String>, #[serde(rename = "aadTenantId", default, skip_serializing_if = "Option::is_none")] pub aad_tenant_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub connected: Option<bool>, #[serde(rename = "eventGridProviderRegistered", default, skip_serializing_if = "Option::is_none")] pub event_grid_provider_registered: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")] pub resource_group: Option<String>, #[serde(rename = "streamingEndpointStarted", default, skip_serializing_if = "Option::is_none")] pub streaming_endpoint_started: Option<bool>, #[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")] pub subscription_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "isDataAction", default, skip_serializing_if = "Option::is_none")] pub is_data_action: Option<bool>, #[serde(rename = "actionType", default, skip_serializing_if = "Option::is_none")] pub action_type: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<OperationDisplay>, #[serde(default, skip_serializing_if = "Option::is_none")] pub origin: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationDisplay { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ErrorDefinition>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorDefinition { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub details: Vec<ErrorDefinition>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AccountCheckNameAvailabilityParameters { pub name: String, #[serde(rename = "type")] pub type_: account_check_name_availability_parameters::Type, } pub mod account_check_name_availability_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { #[serde(rename = "Microsoft.VideoIndexer/accounts")] MicrosoftVideoIndexerAccounts, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CheckNameAvailabilityResult { #[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")] pub name_available: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reason: Option<check_name_availability_result::Reason>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } pub mod check_name_availability_result { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Reason { AlreadyExists, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagedServiceIdentity { #[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")] pub principal_id: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "type")] pub type_: ManagedServiceIdentityType, #[serde(rename = "userAssignedIdentities", default, skip_serializing_if = "Option::is_none")] pub user_assigned_identities: Option<UserAssignedIdentities>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ManagedServiceIdentityType { None, SystemAssigned, UserAssigned, #[serde(rename = "SystemAssigned,UserAssigned")] SystemAssignedUserAssigned, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UserAssignedIdentities {} #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UserAssignedIdentity { #[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")] pub principal_id: Option<String>, #[serde(rename = "clientId", default, skip_serializing_if = "Option::is_none")] pub client_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SystemData { #[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")] pub created_by: Option<String>, #[serde(rename = "createdByType", default, skip_serializing_if = "Option::is_none")] pub created_by_type: Option<system_data::CreatedByType>, #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, #[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")] pub last_modified_by: Option<String>, #[serde(rename = "lastModifiedByType", default, skip_serializing_if = "Option::is_none")] pub last_modified_by_type: Option<system_data::LastModifiedByType>, #[serde(rename = "lastModifiedAt", default, skip_serializing_if = "Option::is_none")] pub last_modified_at: Option<String>, } pub mod system_data { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CreatedByType { User, Application, ManagedIdentity, Key, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum LastModifiedByType { User, Application, ManagedIdentity, Key, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TrackedResource { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, pub location: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, }
// See https://rocket.rs/v0.4/guide/testing/#local-dispatching #[cfg(test)] mod test { use rocket::http::{ContentType, Status}; use rocket::local::Client; use rustlang_rocket_mongodb::rocket; #[test] fn get_heroes() { let client = Client::new(rocket()).expect("valid rocket instance"); let response = client.get("/heroes").dispatch(); assert_eq!(response.status(), Status::Ok); } #[test] fn get_heroe() { // Well get and post tests are identical ... let client = Client::new(rocket()).expect("valid rocket instance"); let mut response = client .post("/heroes") .header(ContentType::JSON) .body(r#"{ "name": "Super Test", "identity":"My Name", "hometown":"cdmx", "age":30 }"#) .dispatch(); assert_eq!(response.status(), Status::Ok); let id = response.body_string().unwrap(); let id: Vec<&str> = id.split("\"").collect(); let mut response = client.get(format!("/heroes/{}", id[3])).dispatch(); println!("get_heroe: {:#?}", response); assert!(response.body().is_some()); assert!(response.body_string().unwrap().contains(&id[3])); client.delete("/heroes").dispatch(); } #[test] fn post_heroe() { let client = Client::new(rocket()).expect("valid rocket instance"); let mut response = client .post("/heroes") .header(ContentType::JSON) .body(r#"{ "name": "Super Test", "identity":"My Name", "hometown":"cdmx", "age":30 }"#) .dispatch(); assert_eq!(response.status(), Status::Ok); let id = response.body_string().unwrap(); let id: Vec<&str> = id.split("\"").collect(); let mut response = client.get(format!("/heroes/{}", id[3])).dispatch(); assert!(response.body().is_some()); assert!(response.body_string().unwrap().contains(&id[3])); client.delete("/heroes").dispatch(); } #[test] fn update_heroe() { let client = Client::new(rocket()).expect("valid rocket instance"); let mut response = client .post("/heroes") .header(ContentType::JSON) .body(r#"{ "name": "Super Test", "identity":"My Name", "hometown":"cdmx", "age":30 }"#) .dispatch(); assert_eq!(response.status(), Status::Ok); assert!(response.body().is_some()); let id = response.body_string().unwrap(); let id: Vec<&str> = id.split("\"").collect(); let response = client .put(format!("/heroes/{}", id[3])) .header(ContentType::JSON) .body(r#"{ "name": "Super Second", "identity":"Mr John", "hometown":"cdmx", "age":10 }"#) .dispatch(); assert_eq!(response.status(), Status::Ok); let mut response = client.get(format!("/heroes/{}", id[3])).dispatch(); assert_eq!(response.status(), Status::Ok); assert!(response.body().is_some()); assert!(response.body_string().unwrap().contains("Super Second")); client.delete("/heroes").dispatch(); } #[test] fn delete_heroe() { let client = Client::new(rocket()).expect("valid rocket instance"); let mut response = client .post("/heroes") .header(ContentType::JSON) .body(r#"{ "name": "Super Second", "identity":"Mr John", "hometown":"cdmx", "age":10 }"#) .dispatch(); assert_eq!(response.status(), Status::Ok); let id = response.body_string().unwrap(); let id: Vec<&str> = id.split("\"").collect(); let mut response = client.delete(format!("/heroes/{}", id[3])).dispatch(); assert!(response.body().is_some()); assert!(response.body_string().unwrap().contains(&id[3])); client.delete("/heroes").dispatch(); } }
//! Provides common appearance presets. use iced::{button, container, pane_grid, text_input, Background, Color, Vector}; /// Represents the currently in-use theme. This provides a way to get colours semantically, as in by their purpose. #[derive(Debug, Clone)] pub enum Theme { Dark, } impl Theme { /// To be used for text intended to be subtle, such as help text, when on bg_primary pub fn text_subtle(&self) -> Color { dark::TEXT_SUBTLE } /// To be used for the bulk of text, when on bg_primary pub fn text_primary(&self) -> Color { dark::TEXT_PRIMARY } /// To be used for text that should stand out, when on bg_primary pub fn text_accent(&self) -> Color { dark::TEXT_ACCENT } /// To be used for text displayed on bg_accent pub fn text_on_accent(&self) -> Color { dark::TEXT_ON_ACCENT } /// To be used for most areas pub fn bg_primary(&self) -> Color { dark::BACKGROUND_PRIMARY } /// To be used for areas that should stand out pub fn bg_accent(&self) -> Color { dark::BACKGROUND_ACCENT } /// Style for most containers pub fn container_primary(&self) -> Box<dyn container::StyleSheet> { match self { Theme::Dark => ContainerStyle { text: dark::TEXT_PRIMARY, bg: dark::BACKGROUND_PRIMARY, } .into(), } } /// Style for containers that should stand out pub fn container_accent(&self) -> Box<dyn container::StyleSheet> { match self { Theme::Dark => ContainerStyle { text: dark::TEXT_ON_ACCENT, bg: dark::BACKGROUND_ACCENT, } .into(), } } /// Style for buttons that shouldn't stand out too much, such as auxillary functions pub fn button_subtle(&self) -> Box<dyn button::StyleSheet> { match self { Theme::Dark => ButtonStyle { text: dark::TEXT_ACCENT, bg: dark::BACKGROUND_PRIMARY, } .into(), } } /// Style for buttons that should stand out, such as 'Next' pub fn button_primary(&self) -> Box<dyn button::StyleSheet> { match self { Theme::Dark => ButtonStyle { text: dark::TEXT_ON_ACCENT, bg: dark::BACKGROUND_ACCENT, } .into(), } } /// Style for normal text inputs pub fn text_input(&self) -> Box<dyn text_input::StyleSheet> { match self { Theme::Dark => Box::new(TextInputStyle { bg: dark::BACKGROUND_PRIMARY, border_normal: mult(dark::BACKGROUND_PRIMARY, 1.1), border_focused: dark::BACKGROUND_ACCENT, text: dark::TEXT_PRIMARY, }), } } } impl Into<Box<dyn pane_grid::StyleSheet>> for &Theme { fn into(self) -> Box<dyn pane_grid::StyleSheet> { match self { Theme::Dark => PaneGridStyle(dark::TEXT_ACCENT), } .into() } } impl Default for Theme { fn default() -> Self { Theme::Dark } } /// A style we apply to containers struct ContainerStyle { text: Color, bg: Color, } impl container::StyleSheet for ContainerStyle { fn style(&self) -> container::Style { container::Style { text_color: Some(self.text), background: Some(Background::Color(self.bg)), border_radius: 0.0, border_width: 0.0, border_color: self.bg, } } } /// A style we apply to buttons struct ButtonStyle { bg: Color, text: Color, } impl button::StyleSheet for ButtonStyle { fn active(&self) -> button::Style { button::Style { shadow_offset: Vector::new(0.0, 0.0), background: Some(Background::Color(self.bg)), border_radius: 0.0, border_width: 0.0, border_color: self.bg, text_color: self.text, } } } /// A style we apply to pane grids. struct PaneGridStyle(Color); impl pane_grid::StyleSheet for PaneGridStyle { fn picked_split(&self) -> Option<pane_grid::Line> { Some(pane_grid::Line { color: self.0, width: 2.0, }) } fn hovered_split(&self) -> Option<pane_grid::Line> { Some(pane_grid::Line { color: self.0, width: 1.0, }) } } struct TextInputStyle { bg: Color, border_normal: Color, border_focused: Color, text: Color, } impl text_input::StyleSheet for TextInputStyle { fn active(&self) -> text_input::Style { text_input::Style { background: Background::Color(self.bg), border_radius: 0.0, border_width: 1.0, border_color: self.border_normal, } } fn focused(&self) -> text_input::Style { text_input::Style { background: Background::Color(self.bg), border_radius: 0.0, border_width: 1.0, border_color: self.border_focused, } } fn placeholder_color(&self) -> Color { mult(self.text, 0.9) } fn value_color(&self) -> Color { self.text } fn selection_color(&self) -> Color { mult(self.bg, 1.1) } fn hovered(&self) -> text_input::Style { let mut s = self.focused(); s.border_radius = 0.5; s } } fn mult(c: Color, f: f32) -> Color { let a = c.into_linear(); Color::from_rgba(a[0] * f, a[1] * f, a[2] * f, a[3] * f) } mod dark { use iced::Color; pub const TEXT_SUBTLE: Color = Color::from_rgba(0.0, 0.0, 0.0, 0.6); pub const TEXT_PRIMARY: Color = Color::WHITE; pub const TEXT_ACCENT: Color = Color::from_rgba(0.39215686274, 0.86666666666, 0.09019607843, 1.0); pub const TEXT_ON_ACCENT: Color = Color::from_rgba(1.0, 1.0, 1.0, 0.5); pub const BACKGROUND_PRIMARY: Color = Color::from_rgba(0.1294117647, 0.1294117647, 0.1294117647, 1.0); pub const BACKGROUND_ACCENT: Color = Color::from_rgba(0.10588235294, 0.36862745098, 0.12549019607, 1.0); }
use py27_marshal::read::errors::ErrorKind; use pydis::{opcode::py27::{self, Mnemonic}, prelude::Opcode}; use thiserror::Error; #[derive(Error, Debug)] pub enum Error<O: 'static + Opcode<Mnemonic = py27::Mnemonic>> { #[error("unexpected data type while processing `{0}`: {1:?}")] ObjectError(&'static str, py27_marshal::Obj), #[error("error disassembling bytecode: {0}")] DisassemblerError(#[from] pydis::error::DecodeError), #[error("input is not a valid code object")] InvalidCodeObject, #[error("error executing bytecode: {0}")] ExecutionError(#[from] ExecutionError<O>), #[error("error parsing data: {0}")] ParserError(#[from] ErrorKind), } #[derive(Error, Debug)] pub enum ExecutionError<O: Opcode<Mnemonic = py27::Mnemonic>> { #[error("complex opcode/object type encountered. Opcode: {0:?}, Object Type: {1:?}")] ComplexExpression( pydis::opcode::Instruction<O>, Option<py27_marshal::Type>, ), #[error("unsupported instruction encountered: {0:?}")] UnsupportedOpcode(O), }
use std::fs::File; use std::io::Cursor; use std::io::{self, BufRead, BufReader, Read, Stdin}; use std::path::PathBuf; pub enum Input { Console(BufReader<Stdin>), File(BufReader<File>), Mem(Cursor<Vec<u8>>), } impl Input { pub fn console() -> Input { Input::Console(io::BufReader::new(std::io::stdin())) } pub fn file(path: &PathBuf) -> io::Result<Input> { Ok(Input::File( // increase performance using a 800k buffer instead of 8k io::BufReader::with_capacity(819200, std::fs::File::open(path)?), )) } pub fn mem(bytes: Vec<u8>) -> Input { Input::Mem(Cursor::new(bytes)) } } impl<'a> Read for Input { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match self { Input::Console(r) => r.read(buf), Input::File(r) => r.read(buf), Input::Mem(b) => b.read(buf), } } } impl<'a> BufRead for Input { fn fill_buf(&mut self) -> io::Result<&[u8]> { match self { Input::Console(r) => r.fill_buf(), Input::File(r) => r.fill_buf(), Input::Mem(b) => b.fill_buf(), } } fn consume(&mut self, amt: usize) { match self { Input::Console(r) => r.consume(amt), Input::File(r) => r.consume(amt), Input::Mem(b) => b.consume(amt), } } }
//! UDS (unified diagnostic protocol) example for reading a data by identifer. //! Run the following server for testing. //! https://github.com/zombieCraig/uds-server use socketcan_isotp::{self, IsoTpSocket, StandardId}; use std::sync::mpsc; fn main() -> Result<(), socketcan_isotp::Error> { let (tx, rx) = mpsc::channel(); // Reader let mut reader_tp_socket = IsoTpSocket::open( "vcan0", StandardId::new(0x7E8).expect("Invalid rx CAN ID"), StandardId::new(0x77A).expect("Invalid tx CAN ID"), )?; std::thread::spawn(move || loop { let buffer = reader_tp_socket.read().expect("Failed to read from socket"); tx.send(buffer.to_vec()).expect("Receiver deallocated"); }); let tp_socket = IsoTpSocket::open( "vcan0", StandardId::new(0x77A).expect("Invalid rx CAN ID"), StandardId::new(0x7E0).expect("Invalid tx CAN ID"), )?; // 0x22 - Service Identifier for "Read data by identifier" request // 0xF189 - Data identifer - VehicleManufacturerECUSoftwareVersionNumberDataIdentifier tp_socket.write(&[0x22, 0xF1, 0x89])?; println!("Sent read data by identifier 0xF189 - VehicleManufacturerECUSoftwareVersionNumberDataIdentifier"); loop { let recv_buffer = rx.recv().expect("Failed to receive"); // 0x62 - Service Identifier for "Read data by identifier" response // 0xF189 - Data identifer - VehicleManufacturerECUSoftwareVersionNumberDataIdentifier if recv_buffer[0..=2] != [0x62, 0xF1, 0x89] { println!("Skipping: {:X?}", recv_buffer); } else { println!("Response: {:X?}", &recv_buffer[3..]); } } }
use log::info; use std::fs::File; use std::io::BufReader; use super::butterfly_collector::{ButterflyCollector, ButterflyJSON}; use super::errors::ButterflyError::{self, *}; use super::webpage_parser::WebpageParser; /// Client used to retrieve butterfly data /// /// You can retrieve data from the Website using `new` then calling `collect_datas` /// /// You can also retrieve data from JSON file with `from_path` pub struct Client { targets: Vec<WebpageParser>, } impl Client { /// Create an new instance of `Client` /// ///```rust ///let mut client = Client::new(vec![ /// WebpageParser::new( /// "old_north", /// "旧北区", /// "http://biokite.com/worldbutterfly/butterfly-PArc.htm#PAall", /// ), /// WebpageParser::new( /// "new_north", /// "新北区", /// "http://biokite.com/worldbutterfly/butterfly-NArc.htm#NAsa", /// ), /// WebpageParser::new( /// "new_tropical", /// "新熱帯区", /// "http://biokite.com/worldbutterfly/butterfly-NTro.htm#NTmap", /// ), /// WebpageParser::new( /// "india_australia", /// "インド・オーストラリア区", /// "http://biokite.com/worldbutterfly/butterfly-IOrs.htm#IOmap", /// ), /// WebpageParser::new( /// "tropical_africa", /// "熱帯アフリカ区", /// "http://biokite.com/worldbutterfly/butterfly-TAfr.htm#TAmaps", /// ), ///]); ///``` pub fn new(targets: Vec<WebpageParser>) -> Client { Client { targets } } /// Collect datas from butterfly website /// ///```rust /// let mut client = Client::new(vec![ /// WebpageParser::new( /// "old_north", /// "旧北区", /// "http://biokite.com/worldbutterfly/butterfly-PArc.htm#PAall", /// )]); /// let result = client.collect_datas.unwrap(); ///``` pub fn collect_datas(&mut self) -> Result<ButterflyCollector, ButterflyError> { let mut results = Vec::new(); for target in self.targets.iter_mut() { info!("Extracting data from: {}", &target.region); let result = target .fetch_data() .map_err(|_| FailedToFetchHTML(target.url.clone()))?; results.push(result.to_owned()); info!("Finished extracting data from: {}", &target.region); } ButterflyCollector::from_parse_result(results) } /// Retrieve data from JSON file /// /// ```rust /// let result = Client::from_path("path_to_json").unwrap(); /// ``` pub fn from_path(json_path: &str) -> Result<ButterflyCollector, ButterflyError> { // Open the file in read-only mode with buffer. let file = File::open(json_path).map_err(|_e| return JsonFileNotFound(json_path.to_string()))?; let reader = BufReader::new(file); // Read the JSON contents of the file as an instance of `User`. let butterfly_json: ButterflyJSON = serde_json::from_reader(reader) .map_err(|_f| return FailedToParseJson(json_path.to_string()))?; butterfly_json.into_collector() } }
//! Driver for the MEMS Lis3dshSpi motion sensor, 3 axis digital output //! accelerometer and temperature sensor. //! //! May be used with NineDof and Temperature //! //! SPI Interface //! //! <https://www.st.com/resource/en/datasheet/lis3dsh.pdf> //! //! //! Syscall Interface //! ----------------- //! //! ### Command //! //! All commands are asynchronous, they return a one shot callback when done //! Only one command can be issued at a time. //! //! #### command num //! - `0`: Returns SUCCESS //! - `data`: Unused. //! - Return: 0 //! - `1`: Is Present //! - `data`: unused //! - Return: `SUCCESS` if no other command is in progress, `EBUSY` otherwise. //! - `2`: Set Power mode //! - `data`: 0 to 9 //! - Return: `SUCCESS` if no other command is in progress, `EBUSY` otherwise. //! - `3`: Set Full scale selection and anti-aliasing filter bandwidth //! - `data1`: 0, 1, 2, 3 or 4 //! - `data2`: 0, 1, 2 or 3 //! - Return: `SUCCESS` if no other command is in progress, `EBUSY` otherwise. //! - `4`: Read XYZ //! - `data`: unused //! - Return: `SUCCESS` if no other command is in progress, `EBUSY` otherwise. //! - `5`: Read Temperature //! - `data`: unused //! - Return: `SUCCESS` if no other command is in progress, `EBUSY` otherwise. //! //! - Return: `SUCCESS` if no other command is in progress, `EBUSY` otherwise. //! - `6`: Read Temperature //! - `data`: 0 - 5 (OUTX_L + data) //! - Return: `SUCCESS` if no other command is in progress, `EBUSY` otherwise. //! //! //! ### Subscribe //! //! All commands call this callback when done, usually subscribes //! should be one time functions //! //! #### subscribe num //! - `0`: Done callback //! - 'data1`: depends on command //! - `1` - 1 for is present, 0 for not present //! - `4` - X rotation //! - `5` - temperature in deg C //! - `6` - accelleration value //! - 'data2`: depends on command //! - `4` - Y rotation //! - 'data3`: depends on command //! - `4` - Z rotation //! //! Usage //! ----- //! //! ```rust //! let mux_spi = components::spi::SpiMuxComponent::new(&stm32f407vg::spi::SPI1) //! .finalize(components::spi_mux_component_helper!(stm32f407vg::spi::Spi)); //! //! let lis3dsh = my_components::lis3dsh::Lis3dshSpiComponent::new() //! .finalize(my_components::lis3dsh_spi_component_helper!(stm32f407vg::spi::Spi, stm32f407vg::gpio::PinId::PE03, mux_spi)); //! //! lis3dsh.configure( //! lis3dsh::Lis3dshDataRate::DataRate100Hz, //! lis3dsh::Lis3dshScale::Scale2G, //! lis3dsh::Lis3dshFilter::Filter800Hz, //! ); //! ``` //! //! NineDof Example //! //! ```rust //! let grant_cap = create_capability!(capabilities::MemoryAllocationCapability); //! let grant_ninedof = board_kernel.create_grant(&grant_cap); //! //! let ninedof = components::ninedof::NineDofComponent::new(board_kernel) //! .finalize(components::ninedof_component_helper!(lis3dsh)); //! //! ``` //! //! Temperature Example //! //! ```rust //! let grant_cap = create_capability!(capabilities::MemoryAllocationCapability); //! let grant_temp = board_kernel.create_grant(&grant_cap); //! //! l3gd20.set_power_mode(); //! let temp = static_init!( //! capsules::temperature::TemperatureSensor<'static>, //! capsules::temperature::TemperatureSensor::new(l3gd20, grant_temperature)); //! kernel::hil::sensors::TemperatureDriver::set_client(l3gd20, temp); //! //! ``` //! //! Author: Keiji Suzuki //! #![allow(non_camel_case_types)] use core::cell::Cell; use enum_primitive::cast::FromPrimitive; use enum_primitive::enum_from_primitive; use kernel::common::cells::{OptionalCell, TakeCell}; use kernel::common::registers::register_bitfields; use kernel::hil::sensors; use kernel::hil::spi; use kernel::ReturnCode; use kernel::{AppId, Callback, Driver}; register_bitfields![u8, CTRL_REG4 [ // Output data rate ODR OFFSET(4) NUMBITS(4) [], // Block data update BDU OFFSET(3) NUMBITS(1) [], // Z-axis enable ZEN OFFSET(2) NUMBITS(1) [], // Y-axis enable YEN OFFSET(1) NUMBITS(1) [], // X-axis enable XEN OFFSET(0) NUMBITS(1) [] ], CTRL_REG5 [ // Anti aliasing filter bandwidth BW OFFSET(6) NUMBITS(2) [], // Full scale selection FSCALE OFFSET(3) NUMBITS(3) [], // Self test enable ST OFFSET(1) NUMBITS(2) [], // SPI serial interface SIM OFFSET(0) NUMBITS(1) [] ] ]; //use capsules::driver; pub const DRIVER_NUM: usize = 0x70223; // 暫定的: driver::NUM::Lis3dsh as usize; /* Identification number */ const LIS3DSH_WHO_AM_I: u8 = 0x3F; /* Registers addresses */ const LIS3DSH_REG_OUT_T: u8 = 0x0C; // r: - 温度出力 /* const LIS3DSH_REG_INFO1: u8 = 0x0D; // r: 0x31 情報レジスタ1 const LIS3DSH_REG_INFO2: u8 = 0x0E; // r: 0x00 情報レジスタ2 */ const LIS3DSH_REG_WHO_AM_I: u8 = 0x0F; // r: 0x3F Who I am ID /* const LIS3DSH_REG_OFF_X: u8 = 0x10; // r/w: 0x00 X軸オフセット修正 const LIS3DSH_REG_OFF_Y: u8 = 0x11; // r/w: 0x00 Y軸オフセット修正 const LIS3DSH_REG_OFF_Z: u8 = 0x12; // r/w: 0x00 Z軸オフセット修正 const LIS3DSH_REG_CS_X: u8 = 0x13; // r/w: 0x00 定数シフトX const LIS3DSH_REG_CS_Y: u8 = 0x14; // r/w: 0x00 定数シフトY const LIS3DSH_REG_CS_Z: u8 = 0x15; // r/w: 0x00 定数シフトZ const LIS3DSH_REG_LC_L: u8 = 0x16; // r/w: 0x01 長いカウンタ(低位) const LIS3DSH_REG_LC_H: u8 = 0x17; // r/w: 0x00 長いカウンタ(高位) const LIS3DSH_REG_STAT: u8 = 0x18; // r: - 割り込み同期 const LIS3DSH_REG_PEAK1: u8 = 0x19; // r: - ピーク値 const LIS3DSH_REG_PEAK2: u8 = 0x1A; // r: - ピーク値 const LIS3DSH_REG_VFC_1: u8 = 0x1B; // r/w: - ベクタフィルタ係数1 const LIS3DSH_REG_VFC_2: u8 = 0x1C; // r/w: - ベクタフィルタ係数2 const LIS3DSH_REG_VFC_3: u8 = 0x1D; // r/w: - ベクタフィルタ係数3 const LIS3DSH_REG_VFC_4: u8 = 0x1E; // r/w: - ベクタフィルタ係数4 const LIS3DSH_REG_THRS3: u8 = 0x1F; // r/w: - 閾値3 */ const LIS3DSH_REG_CTRL_REG4: u8 = 0x20; // r/w: 0x07 制御レジスタ /* const LIS3DSH_REG_CTRL_REG1: u8 = 0x21; // r/w: 0x00 SM1制御レジスタ const LIS3DSH_REG_CTRL_REG2: u8 = 0x22; // r/w: 0x00 SM2制御レジスタ const LIS3DSH_REG_CTRL_REG3: u8 = 0x23; // r/w: 0x00 制御レジスタ */ const LIS3DSH_REG_CTRL_REG5: u8 = 0x24; // r/w: 0x00 制御レジスタ /* const LIS3DSH_REG_CTRL_REG6: u8 = 0x25; // r/w: 0x10 制御レジスタ const LIS3DSH_REG_STATUS: u8 = 0x27; // r: - 状態データレジスタ */ const LIS3DSH_REG_OUT_X_L: u8 = 0x28; // r: 0x00 出力レジスタ(X低位) /* const LIS3DSH_REG_OUT_X_H: u8 = 0x29; // r: 出力レジスタ(X高位) const LIS3DSH_REG_OUT_Y_L: u8 = 0x2A; // r: 出力レジスタ(Y低位) const LIS3DSH_REG_OUT_Y_H: u8 = 0x2B; // r: 出力レジスタ(Y高位) const LIS3DSH_REG_OUT_Z_L: u8 = 0x2C; // r: 出力レジスタ(Z低位) const LIS3DSH_REG_OUT_Z_H: u8 = 0x2D; // r: 出力レジスタ(Z高位) const LIS3DSH_REG_FIFO_CTRL: u8 = 0x2E; // r/w: 0x00 FIFOレジスタ const LIS3DSH_REG_FIFO_SRC: u8 = 0x2F; // r: - FIFOレジスタ const LIS3DSH_REG_ST1_1: u8 = 0x40; // w: - SM1コードレジスタ-1 const LIS3DSH_REG_ST1_2: u8 = 0x41; // w: - SM1コードレジスタ-2 const LIS3DSH_REG_ST1_3: u8 = 0x42; // w: - SM1コードレジスタ-3 const LIS3DSH_REG_ST1_4: u8 = 0x43; // w: - SM1コードレジスタ-4 const LIS3DSH_REG_ST1_5: u8 = 0x44; // w: - SM1コードレジスタ-5 const LIS3DSH_REG_ST1_6: u8 = 0x45; // w: - SM1コードレジスタ-6 const LIS3DSH_REG_ST1_7: u8 = 0x46; // w: - SM1コードレジスタ-7 const LIS3DSH_REG_ST1_8: u8 = 0x47; // w: - SM1コードレジスタ-8 const LIS3DSH_REG_ST1_9: u8 = 0x48; // w: - SM1コードレジスタ-9 const LIS3DSH_REG_ST1_10: u8 = 0x49; // w: - SM1コードレジスタ-10 const LIS3DSH_REG_ST1_11: u8 = 0x4A; // w: - SM1コードレジスタ-11 const LIS3DSH_REG_ST1_12: u8 = 0x4B; // w: - SM1コードレジスタ-12 const LIS3DSH_REG_ST1_13: u8 = 0x4C; // w: - SM1コードレジスタ-13 const LIS3DSH_REG_ST1_14: u8 = 0x4D; // w: - SM1コードレジスタ-14 const LIS3DSH_REG_ST1_15: u8 = 0x4E; // w: - SM1コードレジスタ-15 const LIS3DSH_REG_ST1_16: u8 = 0x4F; // w: - SM1コードレジスタ-16 const LIS3DSH_REG_TIM4_1: u8 = 0x50; // w: - SM1 8-bit汎用タイマー const LIS3DSH_REG_TIM3_1: u8 = 0x51; // w: - SM1 8-bit汎用タイマー const LIS3DSH_REG_TIM2_1L: u8 = 0x52; // w: - SM1 16-bit汎用タイマー(低位) const LIS3DSH_REG_TIM2_1H: u8 = 0x53; // w: - SM1 16-bit汎用タイマー(高位) const LIS3DSH_REG_TIM1_1L: u8 = 0x54; // w: - SM1 16-bit汎用タイマー(低位) const LIS3DSH_REG_TIM1_1H: u8 = 0x55; // w: - SM1 16-bit汎用タイマー(高位) const LIS3DSH_REG_THRS2_1: u8 = 0x56; // w: - SM1閾値1 const LIS3DSH_REG_THRS1_1: u8 = 0x57; // w: - SM1閾値2 const LIS3DSH_REG_MASK1_B: u8 = 0x59; // w: - SM1軸符号マスク const LIS3DSH_REG_MASK1_A: u8 = 0x5A; // w: - SM1軸符号マスク const LIS3DSH_REG_SETT1: u8 = 0x5B; // w: - SM1検知設定 const LIS3DSH_REG_PR1: u8 = 0x5C; // r: - SM1プログラムリセットポインタ const LIS3DSH_REG_TC1: u16 = 0x5D; // r: - SM1タイマーカウンタ const LIS3DSH_REG_OUTS1: u8 = 0x5F; // r: - SM1メイン設定フラグ const LIS3DSH_REG_ST2_1: u8 = 0x60; // w: - SM2コードレジスタ-1 const LIS3DSH_REG_ST2_2: u8 = 0x61; // w: - SM2コードレジスタ-2 const LIS3DSH_REG_ST2_3: u8 = 0x62; // w: - SM2コードレジスタ-3 const LIS3DSH_REG_ST2_4: u8 = 0x63; // w: - SM2コードレジスタ-4 const LIS3DSH_REG_ST2_5: u8 = 0x64; // w: - SM2コードレジスタ-5 const LIS3DSH_REG_ST2_6: u8 = 0x65; // w: - SM2コードレジスタ-6 const LIS3DSH_REG_ST2_7: u8 = 0x66; // w: - SM2コードレジスタ-7 const LIS3DSH_REG_ST2_8: u8 = 0x67; // w: - SM2コードレジスタ-8 const LIS3DSH_REG_ST2_9: u8 = 0x68; // w: - SM2コードレジスタ-9 const LIS3DSH_REG_ST2_10: u8 = 0x69; // w: - SM2コードレジスタ-10 const LIS3DSH_REG_ST2_11: u8 = 0x6A; // w: - SM2コードレジスタ-11 const LIS3DSH_REG_ST2_12: u8 = 0x6B; // w: - SM2コードレジスタ-12 const LIS3DSH_REG_ST2_13: u8 = 0x6C; // w: - SM2コードレジスタ-13 const LIS3DSH_REG_ST2_14: u8 = 0x6D; // w: - SM2コードレジスタ-14 const LIS3DSH_REG_ST2_15: u8 = 0x6E; // w: - SM2コードレジスタ-15 const LIS3DSH_REG_ST2_16: u8 = 0x6F; // w: - SM2コードレジスタ-16 const LIS3DSH_REG_TIM4_2: u8 = 0x70; // w: - SM2 8-bit汎用タイマー const LIS3DSH_REG_TIM3_2: u8 = 0x71; // w: - SM3 8-bit汎用タイマー const LIS3DSH_REG_TIM2_2L: u8 = 0x72; // w: - SM2 16-bit汎用タイマー(低位) const LIS3DSH_REG_TIM2_2H: u8 = 0x72; // w: - SM2 16-bit汎用タイマー(高位) const LIS3DSH_REG_TIM1_2L: u8 = 0x74; // w: - SM2 16-bit汎用タイマー(低位) const LIS3DSH_REG_TIM1_2H: u8 = 0x74; // w: - SM2 16-bit汎用タイマー(高位) const LIS3DSH_REG_THRS2_2: u8 = 0x76; // w: - SM2閾値1 const LIS3DSH_REG_THRS1_2: u8 = 0x77; // w: - SM2閾値2 const LIS3DSH_REG_DES2: u8 = 0x78; // w: - SM2小数ファクター const LIS3DSH_REG_MASK2_B: u8 = 0x79; // w: - SM2軸符号マスク const LIS3DSH_REG_MASK2_A: u8 = 0x7A; // w: - SM2軸符号マスク const LIS3DSH_REG_SETT2: u8 = 0x7B; // w: - SM2検知設定 const LIS3DSH_REG_PR2: u8 = 0x7C; // r: - SM2プログラムリセットポインタ const LIS3DSH_REG_TC2: u16 = 0x7D; // r: - SM2タイマーカウンタ const LIS3DSH_REG_OUTS2: u8 = 0x7F; // r: - SM2メイン設定フラグ */ // buffer size pub const LIS3DSH_TX_SIZE: usize = 10; pub const LIS3DSH_RX_SIZE: usize = 10; // buffers for read and write pub static mut TXBUFFER: [u8; LIS3DSH_TX_SIZE] = [0; LIS3DSH_TX_SIZE]; pub static mut RXBUFFER: [u8; LIS3DSH_RX_SIZE] = [0; LIS3DSH_RX_SIZE]; // Manual page Table 55, page 39 enum_from_primitive! { #[derive(Clone, Copy, PartialEq)] pub enum Lis3dshDataRate { Off = 0, DataRate3_125Hz = 1, DataRate6_26Hz = 2, DataRate12_5Hz = 3, DataRate25Hz = 4, DataRate50Hz = 5, DataRate100Hz = 6, DataRate400Hz = 7, DataRate800Hz = 8, DataRate1600Hz = 9, } } // Manual page 41 enum_from_primitive! { #[derive(Clone, Copy, PartialEq)] pub enum Lis3dshFilter { Filter800Hz = 0, Filter400Hz = 1, Filter200Hz = 2, Filter50Hz = 3, } } enum_from_primitive! { #[derive(Clone, Copy, PartialEq)] pub enum Lis3dshScale { Scale2G = 0, Scale4G = 1, Scale6G = 2, Scale8G = 3, Scale16G = 4 } } // Manual page 41 const SCALE_FACTOR: [u32; 5] = [60, 120, 180, 240, 730]; // ug/digit #[derive(Copy, Clone, PartialEq)] enum Lis3dshStatus { Idle, IsPresent, SetPowerMode, SetScaleAndFilter, ReadXYZ, ReadTemperature, ReadValue, } pub struct Lis3dshSpi<'a> { spi: &'a dyn spi::SpiMasterDevice, txbuffer: TakeCell<'static, [u8]>, rxbuffer: TakeCell<'static, [u8]>, status: Cell<Lis3dshStatus>, data_rate: Cell<Lis3dshDataRate>, scale: Cell<Lis3dshScale>, filter: Cell<Lis3dshFilter>, callback: OptionalCell<Callback>, nine_dof_client: OptionalCell<&'a dyn sensors::NineDofClient>, temperature_client: OptionalCell<&'a dyn sensors::TemperatureClient>, } impl<'a> Lis3dshSpi<'a> { pub fn new( spi: &'a dyn spi::SpiMasterDevice, txbuffer: &'static mut [u8; LIS3DSH_TX_SIZE], rxbuffer: &'static mut [u8; LIS3DSH_RX_SIZE], ) -> Lis3dshSpi<'a> { // setup and return struct Lis3dshSpi { spi: spi, txbuffer: TakeCell::new(txbuffer), rxbuffer: TakeCell::new(rxbuffer), status: Cell::new(Lis3dshStatus::Idle), data_rate: Cell::new(Lis3dshDataRate::DataRate100Hz), scale: Cell::new(Lis3dshScale::Scale2G), filter: Cell::new(Lis3dshFilter::Filter800Hz), callback: OptionalCell::empty(), nine_dof_client: OptionalCell::empty(), temperature_client: OptionalCell::empty(), } } pub fn configure( &self, data_rate: Lis3dshDataRate, scale: Lis3dshScale, filter: Lis3dshFilter, ) { if self.status.get() == Lis3dshStatus::Idle { self.data_rate.set(data_rate); self.scale.set(scale); self.filter.set(filter); self.spi.configure( spi::ClockPolarity::IdleHigh, spi::ClockPhase::SampleTrailing, 1_000_000, ); self.set_power_mode(data_rate); } } pub fn is_present(&self) { self.status.set(Lis3dshStatus::IsPresent); self.txbuffer.take().map(|buf| { buf[0] = LIS3DSH_REG_WHO_AM_I | 0x80; // 読み込み buf[1] = 0x00; self.spi.read_write_bytes(buf, self.rxbuffer.take(), 2); }); } pub fn set_power_mode(&self, data_rate: Lis3dshDataRate) { self.status.set(Lis3dshStatus::SetPowerMode); self.data_rate.set(data_rate); self.txbuffer.take().map(|buf| { buf[0] = LIS3DSH_REG_CTRL_REG4; buf[1] = (CTRL_REG4::ODR.val(data_rate as u8) + CTRL_REG4::BDU::CLEAR + CTRL_REG4::ZEN::SET + CTRL_REG4::YEN::SET + CTRL_REG4::XEN::SET) .value; self.spi.read_write_bytes(buf, None, 2); }); } fn set_scale_and_filter(&self, scale: Lis3dshScale, filter: Lis3dshFilter) { self.status.set(Lis3dshStatus::SetScaleAndFilter); self.scale.set(scale); self.filter.set(filter); self.txbuffer.take().map(|buf| { buf[0] = LIS3DSH_REG_CTRL_REG5; buf[1] = (CTRL_REG5::BW.val(filter as u8) + CTRL_REG5::FSCALE.val(scale as u8)) .value; self.spi.read_write_bytes(buf, None, 2); }); } fn read_xyz(&self) { self.status.set(Lis3dshStatus::ReadXYZ); self.txbuffer.take().map(|buf| { // 連続Read時にアドレスを自動加算 buf[0] = LIS3DSH_REG_OUT_X_L | 0x80; // CTRL_REG6[4] = 1 (Default) buf[1] = 0x00; buf[2] = 0x00; buf[3] = 0x00; buf[4] = 0x00; buf[5] = 0x00; buf[6] = 0x00; self.spi.read_write_bytes(buf, self.rxbuffer.take(), 7); }); } fn read_value(&self, offset: u8) { self.status.set(Lis3dshStatus::ReadValue); self.txbuffer.take().map(|buf| { buf[0] = (LIS3DSH_REG_OUT_X_L + offset) | 0x80; buf[1] = 0x00; self.spi.read_write_bytes(buf, self.rxbuffer.take(), 2); }); } fn read_temperature(&self) { self.status.set(Lis3dshStatus::ReadTemperature); self.txbuffer.take().map(|buf| { buf[0] = LIS3DSH_REG_OUT_T | 0x80; buf[1] = 0x00; self.spi.read_write_bytes(buf, self.rxbuffer.take(), 2); }); } } impl Driver for Lis3dshSpi<'_> { fn command(&self, command_num: usize, data1: usize, data2: usize, _: AppId) -> ReturnCode { match command_num { 0 => ReturnCode::SUCCESS, // センサが正しく接続されているかチェックする 1 => { if self.status.get() == Lis3dshStatus::Idle { self.is_present(); ReturnCode::SUCCESS } else { ReturnCode::EBUSY } } // 出力データレート設定 2 => { if self.status.get() == Lis3dshStatus::Idle { if let Some(data_rate) = Lis3dshDataRate::from_usize(data1) { self.set_power_mode(data_rate); ReturnCode::SUCCESS } else { ReturnCode::EINVAL } } else { ReturnCode::EBUSY } } // スケール, フィルター設定 3 => { if self.status.get() == Lis3dshStatus::Idle { let scale = Lis3dshScale::from_usize(data1); let filter = Lis3dshFilter::from_usize(data2); if scale.is_some() && filter.is_some() { self.set_scale_and_filter(scale.unwrap(), filter.unwrap()); ReturnCode::SUCCESS } else { ReturnCode::EINVAL } } else { ReturnCode::EBUSY } } // XYZ読み取り 4 => { if self.status.get() == Lis3dshStatus::Idle { self.read_xyz(); ReturnCode::SUCCESS } else { ReturnCode::EBUSY } } // 温度読み取り 5 => { if self.status.get() == Lis3dshStatus::Idle { self.read_temperature(); ReturnCode::SUCCESS } else { ReturnCode::EBUSY } } // 任意の軸の1バイトを読み取り 6 => { if self.status.get() == Lis3dshStatus::Idle { self.read_value(data1 as u8); ReturnCode::SUCCESS } else { ReturnCode::EBUSY } } // 未定義 _ => ReturnCode::ENOSUPPORT, } } fn subscribe( &self, subscribe_num: usize, callback: Option<Callback>, _app_id: AppId, ) -> ReturnCode { match subscribe_num { // ワンショットコールバックを設定 0 => { self.callback.insert(callback); ReturnCode::SUCCESS }, // 未定義 _ => ReturnCode::ENOSUPPORT, } } } impl spi::SpiMasterClient for Lis3dshSpi<'_> { fn read_write_done( &self, write_buffer: &'static mut [u8], read_buffer: Option<&'static mut [u8]>, len: usize, ) { self.status.set(match self.status.get() { Lis3dshStatus::IsPresent => { let id: usize; let present = if let Some(ref buf) = read_buffer { if buf[1] == LIS3DSH_WHO_AM_I { id = buf[1] as usize; true } else { id = (((buf[0] as u16) << 8) | (buf[1] as u16)) as usize; false } } else { id = 0; false }; self.callback.map(|callback| { callback.schedule(if present { 1 } else { 0 }, id, 0); }); Lis3dshStatus::Idle } Lis3dshStatus::SetPowerMode => { self.callback.map(|callback| { callback.schedule(0, 0, 0); }); Lis3dshStatus::Idle } Lis3dshStatus::SetScaleAndFilter => { self.callback.map(|callback| { callback.schedule(0, 0, 0); }); Lis3dshStatus::Idle } Lis3dshStatus::ReadXYZ => { let mut x: usize = 0; let mut y: usize = 0; let mut z: usize = 0; let values = if let Some(ref buf) = read_buffer { if len >= 7 { self.nine_dof_client.map(|client| { // 整数のみを使って計算(単位はmg) let scale_factor = self.scale.get() as usize; let x: usize = ((buf[1] as i16 | ((buf[2] as i16) << 8)) as i32 * (SCALE_FACTOR[scale_factor] as i32) / 1000) as usize; // unit = mg let y: usize = ((buf[3] as i16 | ((buf[4] as i16) << 8)) as i32 * (SCALE_FACTOR[scale_factor] as i32) / 1000) as usize; let z: usize = ((buf[5] as i16 | ((buf[6] as i16) << 8)) as i32 * (SCALE_FACTOR[scale_factor] as i32) / 1000) as usize; client.callback(x, y, z); }); x = (buf[1] as i16 | ((buf[2] as i16) << 8)) as usize; y = (buf[3] as i16 | ((buf[4] as i16) << 8)) as usize; z = (buf[5] as i16 | ((buf[6] as i16) << 8)) as usize; true } else { self.nine_dof_client.map(|client| { client.callback(0, 0, 0); }); false } } else { false }; if values { self.callback.map(|callback| { callback.schedule(x, y, z); }); } else { self.callback.map(|callback| { callback.schedule(0, 0, 0); }); } Lis3dshStatus::Idle } Lis3dshStatus::ReadTemperature => { let mut temperature: usize = 0; let value = if let Some(ref buf) = read_buffer { if len >= 2 { temperature = (buf[1] as i8) as usize; self.temperature_client.map(|client| { client.callback(temperature * 100); // divide 100 in sensors app }); true } else { self.temperature_client.map(|client| { client.callback(0); }); false } } else { false }; if value { self.callback.map(|callback| { callback.schedule(temperature, 0, 0); }); } else { self.callback.map(|callback| { callback.schedule(0, 0, 0); }); } Lis3dshStatus::Idle } Lis3dshStatus::ReadValue => { let mut v: usize = 0; if let Some(ref buf) = read_buffer { if len >= 2 { v = buf[1] as usize; } } self.callback.map(|callback| { callback.schedule(v, 0, 0); }); Lis3dshStatus::Idle } _ => { self.callback.map(|callback| { callback.schedule(0, 0, 0); }); Lis3dshStatus::Idle } }); self.txbuffer.replace(write_buffer); if let Some(buf) = read_buffer { self.rxbuffer.replace(buf); } } } impl<'a> sensors::NineDof<'a> for Lis3dshSpi<'a> { fn set_client(&self, nine_dof_client: &'a dyn sensors::NineDofClient) { self.nine_dof_client.replace(nine_dof_client); } fn read_accelerometer(&self) -> ReturnCode { if self.status.get() == Lis3dshStatus::Idle { self.read_xyz(); ReturnCode::SUCCESS } else { ReturnCode::EBUSY } } } impl<'a> sensors::TemperatureDriver<'a> for Lis3dshSpi<'a> { fn set_client(&self, temperature_client: &'a dyn sensors::TemperatureClient) { self.temperature_client.replace(temperature_client); } fn read_temperature(&self) -> ReturnCode { if self.status.get() == Lis3dshStatus::Idle { self.read_temperature(); ReturnCode::SUCCESS } else { ReturnCode::EBUSY } } }
/// Represents a token string #[derive(Clone, Debug, Eq, PartialEq)] pub enum SearchToken<'a> { Value(&'a str), StartsWith(&'a str), } enum SearchTokenizerState { StartWith, Char, Hunting, } #[derive(PartialEq, Debug, Clone)] enum SearchGroupState { None, Grouping, } pub fn search_tokenizer<'a>(value: &'a str) -> Vec<SearchToken<'a>> { let mut start_index = 0; let mut tokens = Vec::with_capacity(10); let mut current_state = SearchTokenizerState::Hunting; let mut group_state = SearchGroupState::None; for (p, c) in value.chars().enumerate() { match current_state { SearchTokenizerState::StartWith => { if !c.is_alphanumeric() { match group_state { SearchGroupState::Grouping => { if c == '"' { tokens.push(SearchToken::StartsWith(&value[start_index..p-1])); current_state = SearchTokenizerState::Hunting; group_state = SearchGroupState::None; } else { // Continue since not the end } } _ => { tokens.push(SearchToken::StartsWith(&value[start_index..p-1])); current_state = SearchTokenizerState::Hunting; } } } } SearchTokenizerState::Hunting => { if c == '"' { group_state = SearchGroupState::Grouping; } else if c.is_alphanumeric() { start_index = p; current_state = SearchTokenizerState::Char; } } SearchTokenizerState::Char => { if c == '*' { current_state = SearchTokenizerState::StartWith; } else if !c.is_alphanumeric() { match group_state { SearchGroupState::Grouping => { if c == '"' { group_state = SearchGroupState::None; tokens.push(SearchToken::Value(&value[start_index..p])); } else { // Keep going } } SearchGroupState::None => { tokens.push(SearchToken::Value(&value[start_index..p])); current_state = SearchTokenizerState::Hunting; } } } } } } match current_state { SearchTokenizerState::StartWith => { tokens.push(SearchToken::StartsWith(&value[start_index..value.len() - 1])); } SearchTokenizerState::Char => { tokens.push(SearchToken::Value(&value[start_index..value.len()])); } _ => {} } tokens } #[cfg(test)] mod tests { use super::*; #[test] pub fn token_tests() { let tokens = search_tokenizer("Hello World!"); assert_eq!(vec![SearchToken::Value("Hello"), SearchToken::Value("World")], tokens); } #[test] pub fn token_tests_no_end() { let tokens = search_tokenizer("Hello World"); assert_eq!(vec![SearchToken::Value("Hello"), SearchToken::Value("World")], tokens); } #[test] pub fn token_tests_no_numeric_start_no_end() { let tokens = search_tokenizer("*Hello World"); assert_eq!(vec![SearchToken::Value("Hello"), SearchToken::Value("World")], tokens); } #[test] pub fn token_tests_no_numeric_starts_with() { let tokens = search_tokenizer("Hello* World*"); assert_eq!(vec![SearchToken::StartsWith("Hello"), SearchToken::StartsWith("World")], tokens); } #[test] pub fn token_tests_no_numeric_starts_with_nums() { let tokens = search_tokenizer("Hello12* World*"); assert_eq!(vec![SearchToken::StartsWith("Hello12"), SearchToken::StartsWith("World")], tokens); } #[test] pub fn group_test_whole() { let tokens = search_tokenizer("\"Hello World*"); assert_eq!(vec![SearchToken::StartsWith("Hello World")], tokens); } #[test] pub fn group_test_whole_mix() { let tokens = search_tokenizer("\"Hello World*\" Something"); assert_eq!(vec![SearchToken::StartsWith("Hello World"), SearchToken::Value("Something")], tokens); } #[test] pub fn group_test_whole_mix_starts() { let tokens = search_tokenizer("\"Hello World*\" Something*"); assert_eq!(vec![SearchToken::StartsWith("Hello World"), SearchToken::StartsWith("Something")], tokens); } }
#![allow(dead_code)] #![allow(unused_variables)] #[allow(unused_imports)] use handlegraph::{ handle::{Direction, Handle, NodeId}, handlegraph::*, mutablehandlegraph::*, packed::*, pathhandlegraph::*, }; #[allow(unused_imports)] use handlegraph::packedgraph::PackedGraph; use crate::geometry::*; #[allow(unused_imports)] use anyhow::Result; pub struct LayoutQuadtree { // data: Vec<u32>, // node_offsets: Vec<u32>, data: Vec<Point>, // use u32 instead of NodeId to ease mapping to GPU tree_node_offsets: Vec<u32>, // same here w/ u32 vs usize elements: usize, leaf_capacity: usize, depth: usize, polynomial_t: usize, } impl LayoutQuadtree { pub fn truncated(nodes: &[Point], leaf_capacity: usize) -> Self { /* let depth = ((nodes.len() / leaf_capacity) as f64).log2().floor(); let depth = (depth as usize).max(1); let elements = nodes.len(); // no idea if this is even close to correct; should probably // take the node count & initial layout size into account here let polynomial_t = 1_000_000; let mut data: Vec<u32> = Vec::with_capacity(elements); let mut tree_node_offsets: Vec<u32> = Vec::with_capacity(elements); */ unimplemented!(); } fn map_coordinate( point: Point, min_p: Point, max_p: Point, poly_t: usize, node_count: usize, ) -> (usize, usize) { let offset_point = point - min_p; let x_f = offset_point.x / (max_p.x - min_p.x); let y_f = offset_point.y / (max_p.y - min_p.y); let coef = poly_t * node_count * node_count; let x = (x_f * (coef as f32)) as usize; let y = (y_f * (coef as f32)) as usize; (x, y) } }
// unihernandez22 // https://codeforces.com/contest/1324/problem/D // math, binary search use std::io; fn main() { let mut n = String::new(); io::stdin().read_line(&mut n).unwrap(); let n: i64 = n.trim().parse().unwrap(); let mut a = String::new(); io::stdin().read_line(&mut a).unwrap(); let a: Vec<i64> = a .split_whitespace() .map(|x| x.parse().unwrap()) .collect(); let mut b = String::new(); io::stdin().read_line(&mut b).unwrap(); let b: Vec<i64> = b .split_whitespace() .map(|x| x.parse().unwrap()) .collect(); let mut c = Vec::<i64>::new(); for i in 0..n as usize { c.push(a[i] - b[i]); } c.sort(); let mut answer = 0; for i in 0..n { let match_ = (-c[i as usize])+1; let mut min = i; let mut max = n; while max - min > 1 { let mid = (min + max) / 2; if c[mid as usize] < match_ { min = mid; } else { max = mid; } } answer += n - max; } println!("{}", answer); }
//! Compact block implementation. use crate::utils::NetworkPeerHandle; use crate::{ProtocolBackend, ProtocolClient, ProtocolServer, RelayError, Resolved, LOG_TARGET}; use async_trait::async_trait; use codec::{Decode, Encode}; use std::collections::BTreeMap; use std::num::NonZeroUsize; use std::sync::Arc; use tracing::{trace, warn}; /// If the encoded size of the protocol unit is less than the threshold, /// return the full protocol unit along with the protocol unit Id in the /// compact response. This catches the common cases like inherents with /// no segment headers. Since inherents are not gossiped, this causes /// a local miss/extra round trip. This threshold based scheme could be /// replaced by using the is_inherent() API if needed const PROTOCOL_UNIT_SIZE_THRESHOLD: NonZeroUsize = NonZeroUsize::new(32).expect("Not zero; qed"); /// Request messages #[derive(Encode, Decode)] pub(crate) enum CompactBlockRequest<DownloadUnitId, ProtocolUnitId> { /// Initial request Initial, /// Request for missing transactions MissingEntries(MissingEntriesRequest<DownloadUnitId, ProtocolUnitId>), } /// Response messages #[derive(Encode, Decode)] pub(crate) enum CompactBlockResponse<DownloadUnitId, ProtocolUnitId, ProtocolUnit> { /// Initial/compact response Initial(InitialResponse<DownloadUnitId, ProtocolUnitId, ProtocolUnit>), /// Response for missing transactions request MissingEntries(MissingEntriesResponse<ProtocolUnit>), } /// The protocol unit info carried in the compact response #[derive(Encode, Decode)] struct ProtocolUnitInfo<ProtocolUnitId, ProtocolUnit> { /// The protocol unit Id id: ProtocolUnitId, /// The server can optionally return the protocol unit /// as part of the initial response. No further /// action is needed on client side to resolve it unit: Option<ProtocolUnit>, } /// The compact response #[derive(Encode, Decode)] pub(crate) struct InitialResponse<DownloadUnitId, ProtocolUnitId, ProtocolUnit> { /// The download unit download_unit_id: DownloadUnitId, /// List of the protocol units Ids. protocol_units: Vec<ProtocolUnitInfo<ProtocolUnitId, ProtocolUnit>>, } /// Request for missing transactions #[derive(Encode, Decode)] pub(crate) struct MissingEntriesRequest<DownloadUnitId, ProtocolUnitId> { /// The download unit download_unit_id: DownloadUnitId, /// Map of missing entry Id -> protocol unit Id. /// The missing entry Id is an opaque identifier used by the client /// side. The server side just returns it as is with the response. protocol_unit_ids: BTreeMap<u64, ProtocolUnitId>, } /// Response for missing transactions #[derive(Encode, Decode)] pub(crate) struct MissingEntriesResponse<ProtocolUnit> { /// Map of missing entry Id -> protocol unit. protocol_units: BTreeMap<u64, ProtocolUnit>, } struct ResolveContext<ProtocolUnitId, ProtocolUnit> { resolved: BTreeMap<u64, Resolved<ProtocolUnitId, ProtocolUnit>>, local_miss: BTreeMap<u64, ProtocolUnitId>, } pub(crate) struct CompactBlockClient<DownloadUnitId, ProtocolUnitId, ProtocolUnit> { pub(crate) backend: Arc< dyn ProtocolBackend<DownloadUnitId, ProtocolUnitId, ProtocolUnit> + Send + Sync + 'static, >, } impl<DownloadUnitId, ProtocolUnitId, ProtocolUnit> CompactBlockClient<DownloadUnitId, ProtocolUnitId, ProtocolUnit> where DownloadUnitId: Send + Sync + Encode + Decode + Clone, ProtocolUnitId: Send + Sync + Encode + Decode + Clone, ProtocolUnit: Send + Sync + Encode + Decode + Clone, { /// Tries to resolve the entries in InitialResponse locally fn resolve_local( &self, compact_response: &InitialResponse<DownloadUnitId, ProtocolUnitId, ProtocolUnit>, ) -> Result<ResolveContext<ProtocolUnitId, ProtocolUnit>, RelayError> { let mut context = ResolveContext { resolved: BTreeMap::new(), local_miss: BTreeMap::new(), }; for (index, entry) in compact_response.protocol_units.iter().enumerate() { let ProtocolUnitInfo { id, unit } = entry; if let Some(unit) = unit { // The full protocol unit was returned context.resolved.insert( index as u64, Resolved { protocol_unit_id: id.clone(), protocol_unit: unit.clone(), locally_resolved: true, }, ); continue; } match self .backend .protocol_unit(&compact_response.download_unit_id, id) { Ok(Some(ret)) => { context.resolved.insert( index as u64, Resolved { protocol_unit_id: id.clone(), protocol_unit: ret, locally_resolved: true, }, ); } Ok(None) => { context.local_miss.insert(index as u64, id.clone()); } Err(err) => return Err(err), } } Ok(context) } /// Fetches the missing entries from the server async fn resolve_misses<Request>( &self, compact_response: InitialResponse<DownloadUnitId, ProtocolUnitId, ProtocolUnit>, context: ResolveContext<ProtocolUnitId, ProtocolUnit>, network_peer_handle: &NetworkPeerHandle, ) -> Result<Vec<Resolved<ProtocolUnitId, ProtocolUnit>>, RelayError> where Request: From<CompactBlockRequest<DownloadUnitId, ProtocolUnitId>> + Encode + Send + Sync, { let ResolveContext { mut resolved, local_miss, } = context; let missing = local_miss.len(); // Request the missing entries from the server let request = CompactBlockRequest::MissingEntries(MissingEntriesRequest { download_unit_id: compact_response.download_unit_id.clone(), protocol_unit_ids: local_miss.clone(), }); let response: CompactBlockResponse<DownloadUnitId, ProtocolUnitId, ProtocolUnit> = network_peer_handle.request(Request::from(request)).await?; let missing_entries_response = if let CompactBlockResponse::MissingEntries(response) = response { response } else { return Err(RelayError::UnexpectedProtocolRespone); }; if missing_entries_response.protocol_units.len() != missing { return Err(RelayError::ResolveMismatch { expected: missing, actual: missing_entries_response.protocol_units.len(), }); } // Merge the resolved entries from the server for (missing_key, protocol_unit_id) in local_miss.into_iter() { if let Some(protocol_unit) = missing_entries_response.protocol_units.get(&missing_key) { resolved.insert( missing_key, Resolved { protocol_unit_id, protocol_unit: protocol_unit.clone(), locally_resolved: false, }, ); } else { return Err(RelayError::ResolvedNotFound(missing)); } } Ok(resolved.into_values().collect()) } } #[async_trait] impl<DownloadUnitId, ProtocolUnitId, ProtocolUnit> ProtocolClient<DownloadUnitId, ProtocolUnitId, ProtocolUnit> for CompactBlockClient<DownloadUnitId, ProtocolUnitId, ProtocolUnit> where DownloadUnitId: Send + Sync + Encode + Decode + Clone + std::fmt::Debug + 'static, ProtocolUnitId: Send + Sync + Encode + Decode + Clone + 'static, ProtocolUnit: Send + Sync + Encode + Decode + Clone + 'static, { type Request = CompactBlockRequest<DownloadUnitId, ProtocolUnitId>; type Response = CompactBlockResponse<DownloadUnitId, ProtocolUnitId, ProtocolUnit>; fn build_initial_request(&self) -> Self::Request { CompactBlockRequest::Initial } async fn resolve_initial_response<Request>( &self, response: Self::Response, network_peer_handle: &NetworkPeerHandle, ) -> Result<(DownloadUnitId, Vec<Resolved<ProtocolUnitId, ProtocolUnit>>), RelayError> where Request: From<Self::Request> + Encode + Send + Sync, { let compact_response = match response { CompactBlockResponse::Initial(compact_response) => compact_response, _ => return Err(RelayError::UnexpectedInitialResponse), }; // Try to resolve the hashes locally first. let context = self.resolve_local(&compact_response)?; if context.resolved.len() == compact_response.protocol_units.len() { trace!( target: LOG_TARGET, "relay::resolve: {:?}: resolved locally[{}]", compact_response.download_unit_id, compact_response.protocol_units.len() ); return Ok(( compact_response.download_unit_id, context.resolved.into_values().collect(), )); } // Resolve the misses from the server let misses = context.local_miss.len(); let download_unit_id = compact_response.download_unit_id.clone(); let resolved = self .resolve_misses::<Request>(compact_response, context, network_peer_handle) .await?; trace!( target: LOG_TARGET, "relay::resolve: {:?}: resolved by server[{},{}]", download_unit_id, resolved.len(), misses, ); Ok((download_unit_id, resolved)) } } pub(crate) struct CompactBlockServer<DownloadUnitId, ProtocolUnitId, ProtocolUnit> { pub(crate) backend: Arc< dyn ProtocolBackend<DownloadUnitId, ProtocolUnitId, ProtocolUnit> + Send + Sync + 'static, >, } #[async_trait] impl<DownloadUnitId, ProtocolUnitId, ProtocolUnit> ProtocolServer<DownloadUnitId> for CompactBlockServer<DownloadUnitId, ProtocolUnitId, ProtocolUnit> where DownloadUnitId: Encode + Decode + Clone, ProtocolUnitId: Encode + Decode + Clone, ProtocolUnit: Encode + Decode, { type Request = CompactBlockRequest<DownloadUnitId, ProtocolUnitId>; type Response = CompactBlockResponse<DownloadUnitId, ProtocolUnitId, ProtocolUnit>; fn build_initial_response( &self, download_unit_id: &DownloadUnitId, initial_request: Self::Request, ) -> Result<Self::Response, RelayError> { if !matches!(initial_request, CompactBlockRequest::Initial) { return Err(RelayError::UnexpectedInitialRequest); } // Return the hash of the members in the download unit. let members = self.backend.download_unit_members(download_unit_id)?; let response = InitialResponse { download_unit_id: download_unit_id.clone(), protocol_units: members .into_iter() .map(|(id, unit)| { let unit = if unit.encoded_size() <= PROTOCOL_UNIT_SIZE_THRESHOLD.get() { Some(unit) } else { None }; ProtocolUnitInfo { id, unit } }) .collect(), }; Ok(CompactBlockResponse::Initial(response)) } fn on_request(&self, request: Self::Request) -> Result<Self::Response, RelayError> { let request = match request { CompactBlockRequest::MissingEntries(req) => req, _ => return Err(RelayError::UnexpectedProtocolRequest), }; let mut protocol_units = BTreeMap::new(); let total_len = request.protocol_unit_ids.len(); for (missing_id, protocol_unit_id) in request.protocol_unit_ids { if let Some(protocol_unit) = self .backend .protocol_unit(&request.download_unit_id, &protocol_unit_id)? { protocol_units.insert(missing_id, protocol_unit); } else { warn!( target: LOG_TARGET, "relay::on_request: missing entry not found" ); } } if total_len != protocol_units.len() { warn!( target: LOG_TARGET, "relay::compact_blocks::on_request: could not resolve all entries: {total_len}/{}", protocol_units.len() ); } Ok(CompactBlockResponse::MissingEntries( MissingEntriesResponse { protocol_units }, )) } }
//! `package cannyls_rpc.protobuf;` //! //! メッセージ定義は[cannyls_rpc.proto]を参照のこと. //! //! [cannyls_rpc.proto]: https://github.com/frugalos/cannyls_rpc/blob/master/protobuf/cannyls_rpc.proto #![cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))] use ::trackable::error::{ErrorKindExt, TrackableError}; use bytecodec::bytes::BytesDecoder as BytecodecBytesDecoder; use bytecodec::combinator::{Peekable, PreEncode}; use bytecodec::{self, ByteCount, Decode, Encode, Eos, ErrorKind, Result, SizedEncode}; use cannyls::block::BlockSize; use cannyls::deadline::Deadline; use cannyls::device::DeviceHandle; use cannyls::lump::{LumpData, LumpHeader, LumpId}; use cannyls::storage::StorageUsage; use factory::Factory; use protobuf_codec::field::branch::Branch2; use protobuf_codec::field::num::{F1, F2, F3, F4}; use protobuf_codec::field::{ FieldDecode, FieldDecoder, FieldEncoder, Fields, MaybeDefault, MessageFieldDecoder, MessageFieldEncoder, Oneof, Optional, Repeated, }; use protobuf_codec::message::{MessageDecode, MessageDecoder, MessageEncode, MessageEncoder}; use protobuf_codec::scalar::{ BoolDecoder, BoolEncoder, BytesDecoder, BytesEncoder, CustomBytesDecoder, Fixed64Decoder, Fixed64Encoder, StringDecoder, StringEncoder, Uint32Decoder, Uint32Encoder, Uint64Decoder, Uint64Encoder, }; use protobuf_codec::wellknown::google::protobuf::{StdDurationDecoder, StdDurationEncoder}; use protobuf_codec::wellknown::protobuf_codec::protobuf::trackable; use protobuf_codec::wire::Tag; use std::ops::Range; use std::str::FromStr; use crate::rpc::{ DeviceRequest, LumpRequest, PutLumpRequest, RangeLumpRequest, RequestOptions, UsageRangeRequest, }; use crate::{DeviceId, DeviceRegistryHandle}; macro_rules! impl_message_decode { ($decoder:ty, $item:ty, $map:expr) => { impl Decode for $decoder { type Item = $item; fn decode(&mut self, buf: &[u8], eos: Eos) -> Result<usize> { track!(self.inner.decode(buf, eos)) } fn finish_decoding(&mut self) -> Result<Self::Item> { let item = track!(self.inner.finish_decoding())?; $map(item) } fn is_idle(&self) -> bool { self.inner.is_idle() } fn requiring_bytes(&self) -> ByteCount { self.inner.requiring_bytes() } } impl MessageDecode for $decoder {} }; } macro_rules! impl_message_encode { ($encoder:ty, $item:ty, $map:expr) => { impl Encode for $encoder { type Item = $item; fn encode(&mut self, buf: &mut [u8], eos: Eos) -> Result<usize> { track!(self.inner.encode(buf, eos)) } fn start_encoding(&mut self, item: Self::Item) -> Result<()> { track!(self.inner.start_encoding($map(item))) } fn is_idle(&self) -> bool { self.inner.is_idle() } fn requiring_bytes(&self) -> ByteCount { self.inner.requiring_bytes() } } impl MessageEncode for $encoder {} }; } macro_rules! impl_sized_message_encode { ($encoder:ty, $item:ty, $map:expr) => { impl_message_encode!($encoder, $item, $map); impl SizedEncode for $encoder { fn exact_requiring_bytes(&self) -> u64 { self.inner.exact_requiring_bytes() } } }; } #[derive(Debug, Default)] pub struct LumpIdDecoder { inner: MessageDecoder< Fields<( FieldDecoder<F1, Fixed64Decoder>, FieldDecoder<F2, Fixed64Decoder>, )>, >, } impl_message_decode!(LumpIdDecoder, LumpId, |(high, low)| Ok(LumpId::new( (u128::from(high) << 64) | u128::from(low) ))); #[derive(Debug, Default)] pub struct LumpIdEncoder { inner: MessageEncoder< Fields<( FieldEncoder<F1, Fixed64Encoder>, FieldEncoder<F2, Fixed64Encoder>, )>, >, } impl_sized_message_encode!(LumpIdEncoder, LumpId, |item: Self::Item| { let id = item.as_u128(); let high = (id >> 64) as u64; let low = id as u64; (high, low) }); #[derive(Debug, Default)] pub struct DeadlineDecoder { inner: MessageDecoder< Fields<( MaybeDefault<FieldDecoder<F1, Uint32Decoder>>, MaybeDefault<MessageFieldDecoder<F2, StdDurationDecoder>>, )>, >, } impl_message_decode!(DeadlineDecoder, Deadline, |(kind, duration)| Ok( match kind { 0 => Deadline::Infinity, 1 => Deadline::Within(duration), 2 => Deadline::Immediate, _ => track_panic!(ErrorKind::InvalidInput, "Unknown deadline type: {}", kind), } )); #[derive(Debug, Default)] pub struct DeadlineEncoder { inner: MessageEncoder< Fields<( FieldEncoder<F1, Uint32Encoder>, Optional<MessageFieldEncoder<F2, StdDurationEncoder>>, )>, >, } impl_sized_message_encode!(DeadlineEncoder, Deadline, |item: Self::Item| match item { Deadline::Infinity => (0, None), Deadline::Within(d) => (1, Some(d)), Deadline::Immediate => (2, None), }); #[derive(Debug, Default)] pub struct StorageUsageDecoder { inner: MessageDecoder< Fields<( MaybeDefault<FieldDecoder<F1, Uint64Decoder>>, MaybeDefault<FieldDecoder<F2, Uint64Decoder>>, )>, >, } impl_message_decode!(StorageUsageDecoder, StorageUsage, |(kind, usage)| Ok( match kind { 0 => StorageUsage::Unknown, 1 => StorageUsage::Approximate(usage), _ => track_panic!( ErrorKind::InvalidInput, "Unknown storage usage type: {}", kind ), } )); #[derive(Debug, Default)] pub struct StorageUsageEncoder { inner: MessageEncoder< Fields<( FieldEncoder<F1, Uint64Encoder>, MaybeDefault<FieldEncoder<F2, Uint64Encoder>>, )>, >, } impl_sized_message_encode!( StorageUsageEncoder, StorageUsage, |item: Self::Item| match item { StorageUsage::Unknown => (0, Default::default()), StorageUsage::Approximate(n) => (1, n), } ); #[derive(Debug, Default)] pub struct RequestOptionsDecoder { inner: MessageDecoder< Fields<( MaybeDefault<MessageFieldDecoder<F1, DeadlineDecoder>>, MaybeDefault<FieldDecoder<F2, Uint32Decoder>>, MaybeDefault<FieldDecoder<F3, BoolDecoder>>, )>, >, } impl_message_decode!(RequestOptionsDecoder, RequestOptions, |( deadline, queue_size_limit, prioritized, )| { let max_queue_len = if queue_size_limit == 0 { None } else { Some(queue_size_limit as usize - 1) }; Ok(RequestOptions { deadline, max_queue_len, prioritized, }) }); #[derive(Debug, Default)] pub struct RequestOptionsEncoder { inner: MessageEncoder< Fields<( MessageFieldEncoder<F1, DeadlineEncoder>, MaybeDefault<FieldEncoder<F2, Uint32Encoder>>, MaybeDefault<FieldEncoder<F3, BoolEncoder>>, )>, >, } impl_sized_message_encode!(RequestOptionsEncoder, RequestOptions, |item: Self::Item| { let queue_size_limit = item.max_queue_len.map_or(0, |n| n + 1); (item.deadline, queue_size_limit as u32, item.prioritized) }); #[derive(Debug, Default)] pub struct LumpRequestDecoder { inner: MessageDecoder< Fields<( FieldDecoder<F1, StringDecoder>, MessageFieldDecoder<F2, LumpIdDecoder>, MessageFieldDecoder<F3, RequestOptionsDecoder>, )>, >, } impl_message_decode!(LumpRequestDecoder, LumpRequest, |( device_id, lump_id, options, )| Ok(LumpRequest { device_id: DeviceId::new(device_id), lump_id, options, })); #[derive(Debug, Default)] pub struct LumpRequestEncoder { inner: MessageEncoder< Fields<( FieldEncoder<F1, StringEncoder>, MessageFieldEncoder<F2, LumpIdEncoder>, MessageFieldEncoder<F3, RequestOptionsEncoder>, )>, >, } impl_sized_message_encode!(LumpRequestEncoder, LumpRequest, |item: Self::Item| ( item.device_id.into_string(), item.lump_id, item.options )); #[derive(Debug)] pub struct PutLumpRequestDecoderFactory { registry: DeviceRegistryHandle, } impl PutLumpRequestDecoderFactory { pub fn new(registry: DeviceRegistryHandle) -> Self { PutLumpRequestDecoderFactory { registry } } } impl Factory for PutLumpRequestDecoderFactory { type Item = PutLumpRequestDecoder; fn create(&self) -> Self::Item { PutLumpRequestDecoder::new(self.registry.clone()) } } #[derive(Debug)] pub struct PutLumpRequestDecoder { inner: MessageDecoder<PutLumpRequestFieldsDecoder>, } impl PutLumpRequestDecoder { fn new(registry: DeviceRegistryHandle) -> Self { PutLumpRequestDecoder { inner: MessageDecoder::new(PutLumpRequestFieldsDecoder::new(registry)), } } } impl_message_decode!(PutLumpRequestDecoder, PutLumpRequest, Ok); #[derive(Debug)] struct PutLumpRequestFieldsDecoder { device_id: FieldDecoder<F1, Peekable<StringDecoder>>, lump_id: MessageFieldDecoder<F2, LumpIdDecoder>, lump_data: FieldDecoder<F3, CustomBytesDecoder<LumpDataDecoder>>, options: MessageFieldDecoder<F4, RequestOptionsDecoder>, index: usize, } impl PutLumpRequestFieldsDecoder { fn new(registry: DeviceRegistryHandle) -> Self { PutLumpRequestFieldsDecoder { device_id: Default::default(), lump_id: Default::default(), lump_data: FieldDecoder::new( F3, CustomBytesDecoder::new(LumpDataDecoder::new(registry)), ), options: Default::default(), index: 0, } } } impl Decode for PutLumpRequestFieldsDecoder { type Item = PutLumpRequest; fn decode(&mut self, buf: &[u8], eos: Eos) -> Result<usize> { match self.index { 0 => Ok(0), 1 => { let size = track!(self.device_id.decode(buf, eos))?; if let Some(device_id) = self.device_id.value_decoder_ref().peek() { if self.device_id.is_idle() { self.lump_data .value_decoder_mut() .inner_mut() .device_hint(device_id); } } Ok(size) } 2 => track!(self.lump_id.decode(buf, eos)), 3 => track!(self.lump_data.decode(buf, eos)), 4 => track!(self.options.decode(buf, eos)), _ => unreachable!(), } } fn finish_decoding(&mut self) -> Result<Self::Item> { self.index = 0; let device_id = track!(self.device_id.finish_decoding())?; let lump_id = track!(self.lump_id.finish_decoding())?; let lump_data = track!(self.lump_data.finish_decoding())?; let options = track!(self.options.finish_decoding())?; Ok(PutLumpRequest { device_id: DeviceId::new(device_id), lump_id, lump_data, options, }) } fn is_idle(&self) -> bool { match self.index { 0 => true, 1 => self.device_id.is_idle(), 2 => self.lump_id.is_idle(), 3 => self.lump_data.is_idle(), 4 => self.options.is_idle(), _ => unreachable!(), } } fn requiring_bytes(&self) -> ByteCount { match self.index { 0 => ByteCount::Finite(0), 1 => self.device_id.requiring_bytes(), 2 => self.lump_id.requiring_bytes(), 3 => self.lump_data.requiring_bytes(), 4 => self.options.requiring_bytes(), _ => unreachable!(), } } } impl FieldDecode for PutLumpRequestFieldsDecoder { fn start_decoding(&mut self, tag: Tag) -> Result<bool> { let started = track!(self.device_id.start_decoding(tag))?; if started { self.index = 1; return Ok(true); } let started = track!(self.lump_id.start_decoding(tag))?; if started { self.index = 2; return Ok(true); } let started = track!(self.lump_data.start_decoding(tag))?; if started { self.index = 3; return Ok(true); } let started = track!(self.options.start_decoding(tag))?; if started { self.index = 4; return Ok(true); } Ok(false) } } #[derive(Debug, Default)] pub struct PutLumpRequestEncoder { inner: MessageEncoder< Fields<( FieldEncoder<F1, StringEncoder>, MessageFieldEncoder<F2, LumpIdEncoder>, FieldEncoder<F3, BytesEncoder<LumpData>>, MessageFieldEncoder<F4, RequestOptionsEncoder>, )>, >, } impl_sized_message_encode!(PutLumpRequestEncoder, PutLumpRequest, |item: Self::Item| ( item.device_id.into_string(), item.lump_id, item.lump_data, item.options, )); #[derive(Debug)] struct LumpDataDecoder { is_first: bool, bytes: BytecodecBytesDecoder<LumpData>, registry: DeviceRegistryHandle, device_hint: Option<DeviceHandle>, } impl LumpDataDecoder { fn new(registry: DeviceRegistryHandle) -> Self { let empty = LumpData::new_embedded(Vec::new()).expect("never fails"); LumpDataDecoder { is_first: true, bytes: BytecodecBytesDecoder::new(empty), registry, device_hint: None, } } fn is_data_to_be_embedded(&self, data_size: usize) -> bool { let block_size = self .device_hint .as_ref() .and_then(|device| device.metrics().storage().map(|s| s.header().block_size)) .unwrap_or_else(BlockSize::min); data_size <= block_size.as_u16() as usize } fn device_hint(&mut self, device_id: &str) { self.device_hint = self.registry.get_device(device_id).ok(); } } impl Decode for LumpDataDecoder { type Item = LumpData; fn decode(&mut self, buf: &[u8], eos: Eos) -> Result<usize> { if self.is_first { self.is_first = false; let remaining_bytes = track_assert_some!(eos.remaining_bytes().to_u64(), ErrorKind::InvalidInput); track_assert!(remaining_bytes <= 0xFFFF_FFFF, ErrorKind::InvalidInput; remaining_bytes); let data_size = buf.len() + remaining_bytes as usize; let data = if self.is_data_to_be_embedded(data_size) { track!(LumpData::new_embedded(vec![0; data_size])) } else if let Some(ref device) = self.device_hint { track!(device.allocate_lump_data(data_size)) } else { track!(LumpData::new(vec![0; data_size])) } .map_err(|e| ErrorKind::InvalidInput.takes_over(e))?; self.bytes = BytecodecBytesDecoder::new(data); } track!(self.bytes.decode(buf, eos)) } fn finish_decoding(&mut self) -> Result<Self::Item> { self.device_hint = None; track_assert!(!self.is_first, ErrorKind::IncompleteDecoding); track!(self.bytes.finish_decoding()) } fn requiring_bytes(&self) -> ByteCount { if self.is_first { ByteCount::Unknown } else { self.bytes.requiring_bytes() } } fn is_idle(&self) -> bool { if self.is_first { false } else { self.bytes.is_idle() } } } #[derive(Debug, Default)] pub struct ErrorDecoder { inner: MessageDecoder<MessageFieldDecoder<F1, trackable::ErrorDecoder>>, } impl_message_decode!(ErrorDecoder, cannyls::Error, |e: TrackableError<String>| { let kind = match cannyls::ErrorKind::from_str(e.kind().as_str()) { Ok(kind) => kind, Err(()) => cannyls::ErrorKind::Other, }; Ok(kind.takes_over(e).into()) }); #[derive(Debug, Default)] pub struct ErrorEncoder { inner: MessageEncoder<MessageFieldEncoder<F1, PreEncode<trackable::ErrorEncoder>>>, } impl_sized_message_encode!(ErrorEncoder, cannyls::Error, |item: Self::Item| { let kind = item.kind().to_string(); kind.takes_over(item) }); #[derive(Debug, Default)] pub struct PutLumpResponseDecoder { inner: MessageDecoder< Oneof<( FieldDecoder<F1, BoolDecoder>, MessageFieldDecoder<F2, ErrorDecoder>, )>, >, } impl_message_decode!(PutLumpResponseDecoder, cannyls::Result<bool>, |item| Ok( branch_into_result(item) )); #[derive(Debug, Default)] pub struct PutLumpResponseEncoder { inner: MessageEncoder< Oneof<( FieldEncoder<F1, BoolEncoder>, MessageFieldEncoder<F2, ErrorEncoder>, )>, >, } impl_sized_message_encode!( PutLumpResponseEncoder, cannyls::Result<bool>, |item: Self::Item| result_into_branch(item) ); pub type DeleteLumpRequestDecoder = PutLumpResponseDecoder; pub type DeleteLumpRequestEncoder = PutLumpResponseEncoder; #[derive(Debug, Default)] pub struct HeadLumpResponseDecoder { inner: MessageDecoder< Optional< Oneof<( FieldDecoder<F1, Uint32Decoder>, MessageFieldDecoder<F2, ErrorDecoder>, )>, >, >, } impl_message_decode!( HeadLumpResponseDecoder, cannyls::Result<Option<LumpHeader>>, |item| { let item = branch_into_optional_result(item); Ok(item.map(|v| { v.map(|n| LumpHeader { approximate_data_size: n, }) })) } ); #[derive(Debug, Default)] pub struct HeadLumpResponseEncoder { inner: MessageEncoder< Optional< Oneof<( FieldEncoder<F1, Uint32Encoder>, MessageFieldEncoder<F2, ErrorEncoder>, )>, >, >, } impl_sized_message_encode!( HeadLumpResponseEncoder, cannyls::Result<Option<LumpHeader>>, |item: Self::Item| optional_result_into_branch( item.map(|h| h.map(|h| h.approximate_data_size)) ) ); #[derive(Debug, Default)] pub struct GetLumpResponseDecoder { inner: MessageDecoder< Optional< Oneof<( FieldDecoder<F1, BytesDecoder>, MessageFieldDecoder<F2, ErrorDecoder>, )>, >, >, } impl_message_decode!( GetLumpResponseDecoder, cannyls::Result<Option<LumpData>>, |item| { let item = branch_into_optional_result(item); match item { Ok(Some(data)) => { let data = track!(LumpData::new(data)) .map_err(|e| bytecodec::ErrorKind::InvalidInput.takes_over(e))?; Ok(Ok(Some(data))) } Ok(None) => Ok(Ok(None)), Err(e) => Ok(Err(e)), } } ); #[derive(Debug, Default)] pub struct GetLumpResponseEncoder { inner: MessageEncoder< Optional< Oneof<( FieldEncoder<F1, BytesEncoder<LumpData>>, MessageFieldEncoder<F2, ErrorEncoder>, )>, >, >, } impl_sized_message_encode!( GetLumpResponseEncoder, cannyls::Result<Option<LumpData>>, |item: Self::Item| optional_result_into_branch(item) ); #[derive(Debug, Default)] pub struct DeviceRequestDecoder { inner: MessageDecoder< Fields<( FieldDecoder<F1, StringDecoder>, MessageFieldDecoder<F2, RequestOptionsDecoder>, )>, >, } impl_message_decode!(DeviceRequestDecoder, DeviceRequest, |( device_id, options, )| Ok(DeviceRequest { device_id: DeviceId::new(device_id), options, })); #[derive(Debug, Default)] pub struct DeviceRequestEncoder { inner: MessageEncoder< Fields<( FieldEncoder<F1, StringEncoder>, MessageFieldEncoder<F2, RequestOptionsEncoder>, )>, >, } impl_sized_message_encode!(DeviceRequestEncoder, DeviceRequest, |item: Self::Item| ( item.device_id.into_string(), item.options )); #[derive(Debug, Default)] pub struct UsageRangeRequestDecoder { inner: MessageDecoder< Fields<( MaybeDefault<FieldDecoder<F1, StringDecoder>>, MessageFieldDecoder<F2, LumpIdDecoder>, MessageFieldDecoder<F3, LumpIdDecoder>, MessageFieldDecoder<F4, RequestOptionsDecoder>, )>, >, } impl_message_decode!(UsageRangeRequestDecoder, UsageRangeRequest, |( device_id, start, end, options, )| Ok( UsageRangeRequest { device_id: DeviceId::new(device_id), range: Range { start, end }, options, } )); #[derive(Debug, Default)] pub struct UsageRangeRequestEncoder { inner: MessageEncoder< Fields<( MaybeDefault<FieldEncoder<F1, StringEncoder>>, MessageFieldEncoder<F2, LumpIdEncoder>, MessageFieldEncoder<F3, LumpIdEncoder>, MessageFieldEncoder<F4, RequestOptionsEncoder>, )>, >, } impl_sized_message_encode!( UsageRangeRequestEncoder, UsageRangeRequest, |item: Self::Item| ( item.device_id.into_string(), item.range.start, item.range.end, item.options, ) ); #[derive(Debug, Default)] pub struct ListLumpResponseDecoder { inner: MessageDecoder< Fields<( Repeated<MessageFieldDecoder<F1, LumpIdDecoder>, Vec<LumpId>>, Optional<MessageFieldDecoder<F2, ErrorDecoder>>, )>, >, } impl_message_decode!(ListLumpResponseDecoder, cannyls::Result<Vec<LumpId>>, |( ids, error, )| if let Some(error) = error { Ok(Err(error)) } else { Ok(Ok(ids)) }); #[derive(Debug, Default)] pub struct ListLumpResponseEncoder { inner: MessageEncoder< Fields<( Repeated<MessageFieldEncoder<F1, LumpIdEncoder>, Vec<LumpId>>, Optional<MessageFieldEncoder<F2, ErrorEncoder>>, )>, >, } impl_message_encode!( ListLumpResponseEncoder, cannyls::Result<Vec<LumpId>>, |item: Self::Item| match item { Err(e) => (Vec::new(), Some(e)), Ok(ids) => (ids, None), } ); #[derive(Debug, Default)] pub struct UsageRangeResponseDecoder { inner: MessageDecoder< Fields<( MaybeDefault<MessageFieldDecoder<F1, StorageUsageDecoder>>, Optional<MessageFieldDecoder<F2, ErrorDecoder>>, )>, >, } impl_message_decode!( UsageRangeResponseDecoder, cannyls::Result<StorageUsage>, |(usage, error)| if let Some(error) = error { Ok(Err(error)) } else { Ok(Ok(usage)) } ); #[derive(Debug, Default)] pub struct UsageRangeResponseEncoder { inner: MessageEncoder< Fields<( MessageFieldEncoder<F1, StorageUsageEncoder>, Optional<MessageFieldEncoder<F2, ErrorEncoder>>, )>, >, } impl_sized_message_encode!( UsageRangeResponseEncoder, cannyls::Result<StorageUsage>, |item: Self::Item| match item { Err(e) => (Default::default(), Some(e)), Ok(usage) => (usage, None), } ); #[derive(Debug, Default)] pub struct RangeLumpRequestDecoder { inner: MessageDecoder< Fields<( MaybeDefault<FieldDecoder<F1, StringDecoder>>, MessageFieldDecoder<F2, LumpIdDecoder>, MessageFieldDecoder<F3, LumpIdDecoder>, MessageFieldDecoder<F4, RequestOptionsDecoder>, )>, >, } impl_message_decode!(RangeLumpRequestDecoder, RangeLumpRequest, |( device_id, start, end, options, )| Ok( RangeLumpRequest { device_id: DeviceId::new(device_id), range: Range { start, end }, options } )); #[derive(Debug, Default)] pub struct RangeLumpRequestEncoder { inner: MessageEncoder< Fields<( MaybeDefault<FieldEncoder<F1, StringEncoder>>, MessageFieldEncoder<F2, LumpIdEncoder>, MessageFieldEncoder<F3, LumpIdEncoder>, MessageFieldEncoder<F4, RequestOptionsEncoder>, )>, >, } impl_sized_message_encode!( RangeLumpRequestEncoder, RangeLumpRequest, |item: Self::Item| ( item.device_id.into_string(), item.range.start, item.range.end, item.options, ) ); pub type DeleteRangeResponseDecoder = ListLumpResponseDecoder; pub type DeleteRangeResponseEncoder = ListLumpResponseEncoder; fn result_into_branch<T, E>(result: std::result::Result<T, E>) -> Branch2<T, E> { match result { Ok(a) => Branch2::A(a), Err(b) => Branch2::B(b), } } fn optional_result_into_branch<T, E>( result: std::result::Result<Option<T>, E>, ) -> Option<Branch2<T, E>> { match result { Ok(Some(a)) => Some(Branch2::A(a)), Ok(None) => None, Err(b) => Some(Branch2::B(b)), } } fn branch_into_result<T, E>(branch: Branch2<T, E>) -> std::result::Result<T, E> { match branch { Branch2::A(a) => Ok(a), Branch2::B(b) => Err(b), } } fn branch_into_optional_result<T, E>( branch: Option<Branch2<T, E>>, ) -> std::result::Result<Option<T>, E> { match branch { None => Ok(None), Some(Branch2::A(a)) => Ok(Some(a)), Some(Branch2::B(b)) => Err(b), } } #[cfg(test)] mod tests { use bytecodec::{DecodeExt, EncodeExt}; use cannyls::deadline::Deadline; use std::time::Duration; use super::*; macro_rules! assert_encdec { ($encoder:ty, $decoder:ty, $value:expr) => { let mut encoder: $encoder = Default::default(); let mut decoder: $decoder = Default::default(); let bytes = track_try_unwrap!(encoder.encode_into_bytes($value())); let decoded = track_try_unwrap!(track!(decoder.decode_from_bytes(&bytes); bytes)); assert_eq!(decoded, $value()); }; } #[test] fn lump_id_encdec_works() { assert_encdec!(LumpIdEncoder, LumpIdDecoder, || LumpId::new(0)); assert_encdec!(LumpIdEncoder, LumpIdDecoder, || LumpId::new( (123 << 64) | 345 )); } #[test] fn deadline_encdec_works() { assert_encdec!(DeadlineEncoder, DeadlineDecoder, || Deadline::Immediate); assert_encdec!(DeadlineEncoder, DeadlineDecoder, || Deadline::Infinity); assert_encdec!(DeadlineEncoder, DeadlineDecoder, || Deadline::Within( Duration::from_secs(0) )); assert_encdec!(DeadlineEncoder, DeadlineDecoder, || Deadline::Within( Duration::from_millis(123) )); } #[test] fn request_options_encdec_works() { assert_encdec!(RequestOptionsEncoder, RequestOptionsDecoder, || { RequestOptions { deadline: Deadline::Immediate, max_queue_len: None, prioritized: false, } }); assert_encdec!(RequestOptionsEncoder, RequestOptionsDecoder, || { RequestOptions { deadline: Deadline::Infinity, max_queue_len: Some(0), prioritized: false, } }); assert_encdec!(RequestOptionsEncoder, RequestOptionsDecoder, || { RequestOptions { deadline: Deadline::Infinity, max_queue_len: Some(123), prioritized: true, } }); } #[test] fn usage_range_request_encdec_works() { let request = UsageRangeRequest { device_id: DeviceId::new("device"), range: Range { start: LumpId::new(1), end: LumpId::new(3), }, options: RequestOptions { deadline: Deadline::Infinity, max_queue_len: Some(123), prioritized: false, }, }; assert_encdec!(UsageRangeRequestEncoder, UsageRangeRequestDecoder, || { request.clone() }); } #[test] fn range_lump_request_encdec_works() { let request = RangeLumpRequest { device_id: DeviceId::new("device"), range: Range { start: LumpId::new(1), end: LumpId::new(3), }, options: RequestOptions { deadline: Deadline::Infinity, max_queue_len: Some(123), prioritized: false, }, }; assert_encdec!(RangeLumpRequestEncoder, RangeLumpRequestDecoder, || { request.clone() }); } }
mod server; extern crate log; extern crate pretty_env_logger; #[tokio::main] async fn main() { // Init logger pretty_env_logger::init(); // Start the API server to handle requests. server::start(([127, 0, 0, 1], 3030)).await; }
use std::sync::{mpsc, Arc, Barrier}; use std::time::Duration; use std::collections::HashMap; use std::thread; use super::common::{Instruction, Value}; fn get_value(map: &HashMap<char, isize>, value: &Value) -> isize { match value { &Value::Raw(ref val) => *val, &Value::Register(register) => *map.get(&register).unwrap_or(&0), } } #[derive(Debug)] enum Message { Stop, Value(isize), } fn run(program: isize, tx: mpsc::Sender<Message>, rx: mpsc::Receiver<Message>, instructions: Vec<Instruction>) -> (isize, usize) { let mut map: HashMap<char, isize> = "abcdefghijklmnopqrstuvwxyz".chars() .map(|chr| (chr, 0)).collect(); map.insert('p', program); let mut idx = 0; let mut sends = 0usize; loop { if idx > instructions.len() { tx.send(Message::Stop).unwrap(); break; } match instructions[idx] { Instruction::Add(source, ref value) => { let val = get_value(&map, &value); let register = match source { Value::Register(reg) => reg, _ => unreachable!(), }; let entry = map.entry(register).or_insert(0); (*entry) += val; idx += 1; } Instruction::Mul(source, ref value) => { let val = get_value(&map, &value); let register = match source { Value::Register(reg) => reg, _ => unreachable!(), }; let entry = map.entry(register).or_insert(0); (*entry) *= val; idx += 1; }, Instruction::Mod(source, ref value) => { let val = get_value(&map, &value); let register = match source { Value::Register(reg) => reg, _ => unreachable!(), }; let entry = map.entry(register).or_insert(0); (*entry) = (*entry % val + val) % val; idx += 1; }, Instruction::Set(source, ref value) => { let val = get_value(&map, &value); let register = match source { Value::Register(reg) => reg, _ => unreachable!(), }; let entry = map.entry(register).or_insert(0); (*entry) = val; idx += 1; }, Instruction::Jgz(ref register, ref value) => { let cmp = match register { &Value::Raw(val) => val, &Value::Register(name) => *map.get(&name).unwrap(), }; if cmp > 0 { let val = get_value(&map, &value); if val > 0 { idx += val as usize; } else { idx -= val.abs() as usize; } } else { idx += 1; } }, Instruction::Snd(source) => { let value = match source { Value::Register(reg) => *map.get(&reg).unwrap(), Value::Raw(val) => val, }; tx.send(Message::Value(value)).unwrap(); sends += 1; idx += 1; }, Instruction::Rcv(source) => { let register = match source { Value::Register(reg) => reg, _ => unreachable!(), }; match rx.recv_timeout(Duration::new(3, 0)) { Ok(Message::Value(value)) => { let entry = map.entry(register).or_insert(0); (*entry) = value; }, _ => break, } idx += 1; }, } } (program, sends) } pub fn parse(data: &str) -> usize { let instructions: Vec<_> = data.lines() .map(|line| line.parse::<Instruction>().unwrap()) .collect(); let (tx1, rx1) = mpsc::channel(); let (tx2, rx2) = mpsc::channel(); let barrier = Arc::new(Barrier::new(2)); let instructions2 = instructions.clone(); let b1 = barrier.clone(); let thread1 = thread::spawn(move || { b1.wait(); run(0, tx1, rx2, instructions) }); let b2 = barrier.clone(); let thread2 = thread::spawn(move || { b2.wait(); run(1, tx2, rx1, instructions2) }); thread1.join().unwrap(); let (_, sends) = thread2.join().unwrap(); sends } #[cfg(test)] mod tests { use super::parse; #[test] fn day18_part2_test1() { let input = "snd 1 snd 2 snd p rcv a rcv b rcv c rcv d"; assert_eq!(3, parse(input)); } }
use crate::segment::SegmentType; use alloc::collections::VecDeque; use alloc::string::ToString; use alloc::vec; use core::cmp::min; use core::mem; use memchr::memrchr; use seshat::unicode::Segmentation; pub const MAX_BLOCK_SIZE: usize = 1024; pub const MIN_BLOCK_SIZE: usize = 512; pub struct Splitter<'a> { buffer: &'a str, segments: VecDeque<SegmentType>, } impl<'a> Splitter<'a> { pub fn new(buffer: &'a str) -> Splitter<'a> { Splitter { buffer, segments: VecDeque::new(), } } } impl<'a> Splitter<'a> { pub fn make_segments(&mut self, split_point: usize) -> Option<SegmentType> { let str = &self.buffer[..split_point]; self.buffer = &self.buffer[split_point..]; let mut current_seq = SegmentType::Ascii(vec![]); for seq in str.break_graphemes() { if seq.is_ascii() { if let SegmentType::Ascii(ascii_seq) = &mut current_seq { ascii_seq.extend_from_slice(seq.as_bytes()); } else { if let SegmentType::Utf8(vars) = &mut current_seq { let is_alphabetic = seq.as_bytes().iter().any(|b| b.is_ascii_alphabetic()); if !is_alphabetic { vars.extend(seq.chars()); continue; } } let is_current_empty = current_seq.is_empty(); let prev = mem::replace( &mut current_seq, SegmentType::Ascii(seq.as_bytes().to_vec()), ); if !is_current_empty { self.segments.push_front(prev) } } } else if seq.len() > 2 { if let SegmentType::Unicode(unicode_seq) = &mut current_seq { unicode_seq.push(seq.to_string()); } else { let is_current_empty = current_seq.is_empty(); let prev = mem::replace( &mut current_seq, SegmentType::Unicode(vec![seq.to_string()]), ); if !is_current_empty { self.segments.push_front(prev) } } } else if let SegmentType::Utf8(char_seq) = &mut current_seq { char_seq.extend(seq.chars()); } else { let is_current_empty = current_seq.is_empty(); let prev = mem::replace(&mut current_seq, SegmentType::Utf8(seq.chars().collect())); if !is_current_empty { self.segments.push_front(prev) } } } if !current_seq.is_empty() { self.segments .push_front(mem::replace(&mut current_seq, SegmentType::Ascii(vec![]))); } self.segments.pop_back() } } impl<'a> Iterator for Splitter<'a> { type Item = SegmentType; fn next(&mut self) -> Option<Self::Item> { if self.buffer.is_empty() && self.segments.is_empty() { return None; } if self.segments.is_empty() { if self.buffer.len() <= MAX_BLOCK_SIZE { return self.make_segments(self.buffer.len()); } let mut split_point = min(MAX_BLOCK_SIZE, self.buffer.len() - MIN_BLOCK_SIZE); match memrchr( b'\n', &self.buffer.as_bytes()[MIN_BLOCK_SIZE - 1..split_point], ) { Some(pos) => self.make_segments(MIN_BLOCK_SIZE + pos), None => { while !self.buffer.is_char_boundary(split_point) { split_point -= 1; } self.make_segments(split_point) } } } else { self.segments.remove(self.segments.len() - 1) } } } #[cfg(test)] mod tests { use crate::segment::SegmentType; use crate::splitter::Splitter; use alloc::string::{String, ToString}; use alloc::vec; use alloc::vec::Vec; fn split_check(partition: &[&str]) { let text: String = partition.iter().map(|p| p.to_string()).collect(); let actual: Vec<_> = Splitter::new(&text).map(|s| s.to_string()).collect(); assert_eq!(partition, &actual); } #[test] fn test_splitter() { split_check(&[ "\ Too show friend entrance first body sometimes disposed. Oh sell this so relied cordial scale mirth sometimes round change never dispatched stand jennings. \ Hills lose terminated exeter oppose everything chicken noisier tended answered ignorant absolute stand branch cousins shy. \ Enjoy not enjoyed sufficient adapted returned size unpleasant suffering commanded improving. \ Repair village towards humoured consider them. \ Finished needed nature would world went proceed possible feelings wishes worthy. \ Ladyship these jointure several shed they forming warmly folly. \ Servants consider fat his cannot winding who brother greatly certainty precaution deal dashwoods. \ Admitting left attention remarkably spoil woody disposed change exercise matter period females weddings world found. \ Moderate age enabled remainder justice sentiments hastily eyes rest provision perfectly. \ Favour barton anxious give everything parish keeps ", "", "no offer use deficient expression prosperous hastened. \ Call forth speaking busy week denoting. Saved ve", "ry period address. \ Often wandered sent money manners sooner exercise roof increasing seeing common furnished show society unreserved enjoyed brought. \ Uneasy declared endeavor found. Prospect set match within existence john passage although. \ Married been purse prepared taste. Enabled depending more home building place provided under dearest pleasure goodness perhaps prepared society supported. \ Nearer cannot improve invited securing offence settled can tolerably delay savings hung about denoting views. Death believed entirely thing seeing northward that. "] ); } #[test] fn test_ascii_segments() { let text = "Too show friend entrance first body sometimes disposed. Oh sell this so relied cordial scale mirth sometimes round change never dispatched stand jennings. \ Hills lose terminated exeter oppose everything chicken noisier tended answered ignorant absolute stand branch cousins shy. \ Enjoy not enjoyed sufficient adapted returned size unpleasant suffering commanded improving. \ Repair village towards humoured consider them.\n\ Finished needed nature would world went proceed possible feelings wishes worthy. \ Ladyship these jointure several shed they forming warmly folly. \ Servants consider fat his cannot winding who brother greatly certainty precaution deal dashwoods. \ Admitting left attention remarkably spoil woody disposed change exercise matter period females weddings world found. \ "; let partition = Splitter::new(text).next().unwrap(); if let SegmentType::Ascii(ascii) = partition { assert_eq!(text, String::from_utf8_lossy(&ascii).as_ref()); } else { panic!("Expected ascii segment"); } } #[test] fn test_utf8_segments() { let text = "Не следует, однако забывать, что дальнейшее развитие различных форм деятельности способствует подготовки и реализации форм развития. \ Равным образом постоянный количественный рост и сфера нашей активности играет важную роль в формировании системы обучения кадров, соответствует насущным потребностям."; let partition = Splitter::new(text).next().unwrap(); if let SegmentType::Utf8(ascii) = partition { assert_eq!(text, &ascii.into_iter().collect::<String>()); } else { panic!("Expected utf8 segment"); } } fn ascii(str: &str) -> SegmentType { SegmentType::Ascii(str.as_bytes().to_vec()) } #[test] fn test_complex() { let text = "Таким образом реализация намеченных плановых заданий позволяет оценить значение новых предложений😈. \ //Too show friend entrance first body sometimes disposed.\ 😈 🌋 🏔 🗻 🏕 ⛺️ 🛖 🏠 🏡 🏘\ 👨‍👩‍👧‍👦\ формировании системы обучения кадров.\ "; let partition = Splitter::new(text).collect::<Vec<_>>(); assert_eq!(partition, vec![ SegmentType::Utf8("Таким образом реализация намеченных плановых заданий позволяет оценить значение новых предложений".chars().collect()), SegmentType::Unicode(vec!["😈".to_string()]), ascii(". //Too show friend entrance first body sometimes disposed."), SegmentType::Unicode(vec!["😈".to_string()]), ascii(" "), SegmentType::Unicode(vec!["🌋".to_string()]), ascii(" "), SegmentType::Unicode(vec!["🏔".to_string()]), ascii(" "), SegmentType::Unicode(vec!["🗻".to_string()]), ascii(" "), SegmentType::Unicode(vec!["🏕".to_string()]), ascii(" "), SegmentType::Unicode(vec!["⛺️".to_string()]), ascii(" "), SegmentType::Unicode(vec!["🛖".to_string()]), ascii(" "), SegmentType::Unicode(vec!["🏠".to_string()]), ascii(" "), SegmentType::Unicode(vec!["🏡".to_string()]), ascii(" "), SegmentType::Unicode(vec!["🏘".to_string(), "👨‍👩‍👧‍👦".to_string()]), SegmentType::Utf8("формировании системы обучения кадров.".chars().collect()), ] ) } }
struct Data { name:String, no1:u32, no2:u32, } fn main() { let Data = Data{ name : String::from("Mike"), no1 : 55, no2 : 55, }; let result:u32 = add(&Data); println!("The name is :: {}",Data.name); println!("the result is :: {}",result); }// main ends here fn add(Data : &Data)->u32{ Data.no1+ Data.no2 }
pub mod game_state; pub mod user_state; pub use game_state::GameState; pub use user_state::{UserState, UserStateDb};
pub(crate) fn parse_uds_addr(addr: impl AsRef<str>) -> String { let addr = addr.as_ref(); if addr.starts_with("unix://") || addr.starts_with("UNIX://") { addr.chars().skip(7).collect::<String>() } else { addr.to_owned() } } pub(crate) fn parse_tcp_addr(addr: impl AsRef<str>) -> String { let addr = addr.as_ref(); if addr.starts_with("tcp://") || addr.starts_with("TCP://") { addr.chars().skip(6).collect::<String>() } else { addr.to_owned() } }
//! Renders selected features from the input archive as svg. //! //! For supported features check `Category` enum and `classify` function. //! //! For each feature, we retrieve the coordinates lazily from osm nodes, and //! then produce polylines styled based on the category, cf. `render_svg` //! function. The coordinates are in lon, lat. //! //! Inside of svg we just use the coordinates as is (except for swapped x/y //! axes), plus we apply a transformation to adjust the coordinates to the //! viewport. Obviously, it is slower the render such svg on the screen. //! However, the final svg contains already so many polyline, that having alrady //! transformed coordinates does not change much. If you need speed when showing //! the svg, feel free to apply simplifications in this program. //! //! LICENSE //! //! The code in this example file is released into the Public Domain. use clap::Parser; use osmflat::{iter_tags, FileResourceStorage, Node, Osm, Relation, RelationMembersRef, Way}; use smallvec::{smallvec, SmallVec}; use svg::{ node::{self, element}, Document, }; use std::f64; use std::fmt::Write; use std::io; use std::ops::Range; use std::path::PathBuf; use std::str; /// Geographic coordinates represented by (latitude, longitude). #[derive(Debug, Clone, Copy, Default, PartialEq, PartialOrd)] struct GeoCoord { lat: f64, lon: f64, } impl GeoCoord { fn min(self, other: Self) -> Self { Self { lat: self.lat.min(other.lat), lon: self.lon.min(other.lon), } } fn max(self, other: Self) -> Self { Self { lat: self.lat.max(other.lat), lon: self.lon.max(other.lon), } } } /// Convert osmflat Node into GeoCoord. impl GeoCoord { fn from_node(node: &Node, coord_scale: i32) -> Self { Self { lat: node.lat() as f64 / coord_scale as f64, lon: node.lon() as f64 / coord_scale as f64, } } } /// Polyline which can be transformed into an iterator over `GeoCoord`'s. struct Polyline { inner: SmallVec<[Range<u64>; 4]>, } impl From<Range<u64>> for Polyline { fn from(range: Range<u64>) -> Self { Self { inner: smallvec![range], } } } impl Polyline { #[allow(clippy::iter_overeager_cloned)] fn into_iter(self, archive: &Osm) -> Option<impl Iterator<Item = GeoCoord> + '_> { let nodes_index = archive.nodes_index(); let nodes = archive.nodes(); let mut indices = self.inner.iter().cloned().flatten(); let scale = archive.header().coord_scale(); if indices.any(|idx| nodes_index[idx as usize].value().is_none()) { None } else { let indices = self.inner.into_iter().flatten(); Some(indices.map(move |idx| { GeoCoord::from_node( &nodes[nodes_index[idx as usize].value().unwrap() as usize], scale, ) })) } } } /// Categories of features we support in this renderer. #[derive(Debug, Clone, Copy)] enum Category { Road, Park, River(u32), // River with width Water, } /// Feature in osmflat. /// /// Idx points either into ways or relations, depending on the `Category`. struct Feature { idx: usize, cat: Category, } impl Feature { fn into_polyline(self, archive: &Osm) -> Option<Polyline> { match self.cat { Category::Road | Category::River(_) => { Some(way_into_polyline(&archive.ways()[self.idx])) } Category::Park | Category::Water => multipolygon_into_polyline(archive, self.idx), } } } fn way_into_polyline(way: &Way) -> Polyline { Polyline { inner: smallvec![way.refs()], } } fn multipolygon_into_polyline(archive: &Osm, idx: usize) -> Option<Polyline> { let members = archive.relation_members().at(idx); let strings = archive.stringtable(); let ways = archive.ways(); let inner: Option<SmallVec<[Range<u64>; 4]>> = members .filter_map(|m| match m { RelationMembersRef::WayMember(way_member) if strings.substring(way_member.role_idx() as usize) == Ok("outer") => { Some(way_member.way_idx().map(|idx| ways[idx as usize].refs())) } _ => None, }) .collect(); inner.map(|inner| Polyline { inner }) } /// Classifies all features from osmflat we want to render. fn classify(archive: &Osm) -> impl Iterator<Item = Feature> + '_ { let ways = archive.ways().iter().enumerate(); let ways = ways .filter_map(move |(idx, way)| classify_way(archive, way).map(|cat| Feature { idx, cat })); let rels = archive.relations().iter().enumerate(); let rels = rels.filter_map(move |(idx, rel)| { classify_relation(archive, rel).map(|cat| Feature { idx, cat }) }); ways.chain(rels) } fn classify_way(archive: &Osm, way: &Way) -> Option<Category> { // Filter all ways that have less than 2 nodes. if way.refs().end <= way.refs().start + 2 { return None; } const UNWANTED_HIGHWAY_TYPES: [&[u8]; 9] = [ b"pedestrian", b"steps", b"footway", b"construction", b"bic", b"cycleway", b"layby", b"bridleway", b"path", ]; // Filter all ways that do not have a highway tag. Also check for specific // values. for (key, val) in iter_tags(archive, way.tags()) { if key == b"highway" { if UNWANTED_HIGHWAY_TYPES.contains(&val) { return None; } return Some(Category::Road); } else if key == b"waterway" { for (key, val) in iter_tags(archive, way.tags()) { if key == b"width" || key == b"maxwidth" { let width: u32 = str::from_utf8(val).ok()?.parse().ok()?; return Some(Category::River(width)); } } return Some(Category::River(1)); } } None } fn classify_relation(archive: &Osm, relation: &Relation) -> Option<Category> { let mut is_multipolygon = false; let mut is_park = false; let mut is_lake = false; for (key, val) in iter_tags(archive, relation.tags()) { if key == b"type" && val == b"multipolygon" { if is_park { return Some(Category::Park); } if is_lake { return Some(Category::Water); } is_multipolygon = true; } if (key == b"leisure" && val == b"park") || (key == b"landuse" && (val == b"recreation_ground" || val == b"forest")) { if is_multipolygon { return Some(Category::Park); } is_park = true; } if key == b"water" && val == b"lake" { if is_multipolygon { return Some(Category::Water); } is_lake = true; } } None } /// Renders svg from classified polylines. fn render_svg<P>( archive: &Osm, classified_polylines: P, output: PathBuf, width: u32, height: u32, ) -> Result<(), io::Error> where P: Iterator<Item = (Polyline, Category)>, { let mut document = Document::new().set("viewBox", (0, 0, width, height)); let mut road_group = element::Group::new() .set("stroke", "#001F3F") .set("stroke-width", "0.3") .set("fill", "none"); let mut park_group = element::Group::new() .set("stroke", "#3D9970") .set("fill", "#3D9970") .set("fill-opacity", 0.3); let mut river_group = element::Group::new() .set("stroke", "#0074D9") .set("fill", "none") .set("stroke-opacity", 0.8); let mut lake_group = element::Group::new() .set("stroke", "#0074D9") .set("fill", "#0074D9") .set("fill-opacity", 0.3); let mut min_coord = GeoCoord { lat: f64::MAX, lon: f64::MAX, }; let mut max_coord = GeoCoord { lat: f64::MIN, lon: f64::MIN, }; let mut points = String::new(); // reuse string buffer inside the for-loop for (poly, cat) in classified_polylines { points.clear(); let poly_iter = match poly.into_iter(archive) { Some(x) => x, None => continue, }; for coord in poly_iter { // collect extent min_coord = min_coord.min(coord); max_coord = max_coord.max(coord); // accumulate polyline points write!(&mut points, "{:.5},{:.5} ", coord.lon, coord.lat) .expect("failed to write coordinates"); } let polyline = element::Polyline::new().set("points", &points[..]); match cat { Category::Road => { road_group = road_group.add(polyline); } Category::River(width) => { river_group = river_group.add(polyline).set("stroke-width", width); } Category::Park => { park_group = park_group.add(polyline); } Category::Water => { lake_group = lake_group.add(polyline); } } } let mut transform = element::Group::new().set( "transform", format!( "scale({:.5} {:.5}) translate({:.5} {:.5})", /* Note: svg transformations are * applied from right to left */ f64::from(width) / (max_coord.lon - min_coord.lon), f64::from(height) / (min_coord.lat - max_coord.lat), // invert y-axis -min_coord.lon, -max_coord.lat, ), ); transform = transform .add(road_group) .add(river_group) .add(lake_group) .add(park_group); let style = element::Style::new( r#" text { font-family: arial; font-size: 8px; color: #001F3F; opacity: 0.3; } polyline { vector-effect: non-scaling-stroke; } "#, ); let notice = element::Text::new() .set("x", width.saturating_sub(10)) .set("y", height.saturating_sub(10)) .set("text-anchor", "end") .add(node::Text::new("© OpenStreetMap Contributors")); document = document.add(style).add(transform).add(notice); svg::save(output, &document) } /// render map features as a SVG #[derive(Debug, Parser)] #[clap(name = "render-features")] struct Args { /// osmflat archive osmflat_archive: PathBuf, /// SVG filename to output #[clap(long, short = 'o')] output: PathBuf, /// width of the image #[clap(long, short = 'w', default_value = "800")] width: u32, /// height of the image #[clap(long, short = 'h', default_value = "600")] height: u32, } fn main() -> Result<(), Box<dyn std::error::Error>> { let args = Args::parse(); let storage = FileResourceStorage::new(args.osmflat_archive); let archive = Osm::open(storage)?; let features = classify(&archive); let archive_inner = archive.clone(); let classified_polylines = features.filter_map(move |f| { let cat = f.cat; f.into_polyline(&archive_inner).map(|p| (p, cat)) }); render_svg( &archive, classified_polylines, args.output, args.width, args.height, )?; Ok(()) }
#[doc = "Reader of register HWCFGR12"] pub type R = crate::R<u32, super::HWCFGR12>; #[doc = "Reader of field `TZ`"] pub type TZ_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - TZ"] #[inline(always)] pub fn tz(&self) -> TZ_R { TZ_R::new((self.bits & 0xffff_ffff) as u32) } }
#[allow(unused_macros)] macro_rules! gen_all_symbols { () => { let market_types = get_market_types(EXCHANGE_NAME); assert!(!market_types.is_empty()); for market_type in market_types .into_iter() .filter(|m| m != &MarketType::Unknown) { let symbols = fetch_symbols(EXCHANGE_NAME, market_type).unwrap(); assert!(!symbols.is_empty()); } }; }
use crate::egml::{Component, Node, Comp}; use super::InputEvent; pub struct MouseInput { last_mouse_pos: Option<(f64, f64)>, last_offset: Option<(f64, f64)>, } #[derive(Default, Debug, Clone, Copy, PartialEq)] pub struct MousePos { pub x: f32, pub y: f32, } impl MouseInput { pub fn new() -> Self { MouseInput { last_mouse_pos: None, last_offset: None, } } pub fn update_pos(&mut self, x_pos: f64, y_pos: f64) { if self.last_mouse_pos.is_none() { self.last_mouse_pos = Some((x_pos, y_pos)); } let (x_last, y_last) = self.last_mouse_pos.unwrap(); let x_offset = x_pos - x_last; let y_offset = y_last - y_pos; // reversed since y-coordinates go from bottom to top self.last_mouse_pos = Some((x_pos, y_pos)); self.last_offset = Some((x_offset, y_offset)); } pub fn last_pos(&self) -> MousePos { if let Some((x, y)) = self.last_mouse_pos { MousePos { x: x as f32, y: y as f32 } } else { MousePos { x: 0.0, y: 0.0 } } } pub fn left_pressed_comp(&self, comp: &mut Comp) { let pos = self.last_pos(); comp.input(InputEvent::MousePress(pos), None) } pub fn left_pressed_node<M: Component>(&self, node: &mut Node<M>) -> Vec<M::Message> { let pos = self.last_pos(); let mut msgs = Vec::new(); node.input(InputEvent::MousePress(pos), &mut msgs); msgs } }