{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n \n \"#;\n }\n\n #[test]\n fn activate() {\n let s: &str = &super::KEY_LOC;\n\n super::activate();\n super::activate_from_str(s);\n super::activate_from_cstr(CString::new(s).unwrap());\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2935,"cells":{"blob_id":{"kind":"string","value":"5eb7cb64fc6ada724c5cb5ad419eb06d0161abad"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"chinatsu/oo-workshop"},"path":{"kind":"string","value":"/src/chance/chance_test.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2401,"string":"2,401"},"score":{"kind":"number","value":3.09375,"string":"3.09375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use super::{Chance, ChanceError};\n\nlazy_static! {\n static ref CERTAIN: Chance = Chance::new(super::CERTAIN).unwrap();\n static ref LIKELY: Chance = Chance::new(0.75).unwrap();\n static ref FIFTY_NINE: Chance = Chance::new(0.59).unwrap();\n static ref EQUALLY_LIKELY: Chance = Chance::new(0.5).unwrap();\n static ref FORTY_ONE: Chance = Chance::new(0.41).unwrap();\n static ref UNLIKELY: Chance = Chance::new(0.25).unwrap();\n static ref IMPOSSIBLE: Chance = Chance::new(0.0).unwrap();\n\n}\n\n#[test]\nfn the_chance_of_25_should_be_ok() {\n assert!(Chance::new(0.25).is_ok());\n}\n\n#[test]\nfn the_chance_of_130_should_be_out_of_bounds() {\n assert_eq!(Err(ChanceError::OutOfBounds), Chance::new(1.30));\n}\n\n#[test]\nfn the_chance_of_minus_10_should_be_out_of_bounds() {\n assert_eq!(Err(ChanceError::OutOfBounds), Chance::new(-0.1));\n}\n\n#[test]\nfn the_chance_of_75_should_equal_likely() -> Result<(), ChanceError> {\n assert_eq!(*LIKELY, Chance::new(0.75)?);\n Ok(())\n}\n\n#[test]\nfn the_chance_of_75_should_not_equal_the_chance_of_25() {\n assert_ne!(*UNLIKELY, *LIKELY);\n}\n\n#[test]\nfn the_opposite_of_100_should_be_0() {\n assert_eq!(*IMPOSSIBLE, !*CERTAIN);\n}\n\n#[test]\nfn the_opposite_of_75_should_be_25() {\n assert_eq!(*UNLIKELY, !*LIKELY);\n}\n\n#[test]\nfn the_opposite_of_the_opposite_of_41_should_be_41() {\n assert_eq!(*FORTY_ONE, !!*FORTY_ONE);\n}\n\n#[test]\nfn the_opposite_of_the_opposite_of_the_opposite_of_41_should_be_59() {\n assert_eq!(*FIFTY_NINE, !!!*FORTY_ONE);\n}\n\n#[test]\nfn chances_with_values_41_and_50_together_should_be_20_5() {\n assert_eq!(Chance::new(0.205).unwrap(), *FORTY_ONE & *EQUALLY_LIKELY);\n}\n\n#[test]\nfn chances_with_values_13_and_0_together_should_be_0() {\n assert_eq!(*IMPOSSIBLE, *FIFTY_NINE & *IMPOSSIBLE);\n}\n\n#[test]\nfn chances_with_values_100_and_75_and_50_together_should_be_3_75() -> Result<(), ChanceError> {\n assert_eq!(Chance::new(0.375)?, *CERTAIN & *LIKELY & *EQUALLY_LIKELY);\n Ok(())\n}\n\n#[test]\nfn chances_of_75_or_75_should_be_93_75() -> Result<(), ChanceError> {\n assert_eq!(Chance::new(0.9375)?, *LIKELY | *LIKELY);\n Ok(())\n}\n\n#[test]\nfn sequence_of_4_chances_of_75_should_be_99_609375() -> Result<(), ChanceError> {\n assert_eq!(Chance::new(0.99609375)?, *LIKELY | *LIKELY | *LIKELY | *LIKELY);\n Ok(())\n}\n\n#[test]\nfn chances_of_100_or_75_should_be_100() {\n assert_eq!(*CERTAIN, *CERTAIN | *UNLIKELY);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2936,"cells":{"blob_id":{"kind":"string","value":"c39148bf9a189c3f29f336de12cf1d4b50c29ccc"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"rk9109/sandbox-api"},"path":{"kind":"string","value":"/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":494,"string":"494"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// TODO convert to REST API\n\nmod command;\nmod sandbox;\n\nuse command::Language;\nuse sandbox::Sandbox;\n\nconst TEST_C_CODE: &'static str = r#\"\n#include \nint main() {\n for (int i = 0; i < 10; i++) {\n printf(\"%d\\n\", i);\n }\n return 0;\n}\n\"#;\n\nfn main() {\n let output = Sandbox::new(TEST_C_CODE, Language::C)\n .expect(\"Failed to construct sandbox\")\n .output()\n .expect(\"Failed to execute\");\n\n println!(\"STDOUT:\\n{}\", output.execute_output.stdout);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2937,"cells":{"blob_id":{"kind":"string","value":"ac35012aa407d9854482267fa63f9b93b3688bba"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"akovaski/AdventOfCode"},"path":{"kind":"string","value":"/2018/src/year2018/d10p1.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3215,"string":"3,215"},"score":{"kind":"number","value":3.03125,"string":"3.03125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use regex::Regex;\nuse std::cmp;\nuse std::collections::{HashSet, VecDeque};\nuse std::fs::File;\nuse std::io;\nuse std::io::prelude::*;\nuse std::io::BufReader;\n\npub struct Light {\n pub pos: Vector,\n pub vel: Vector,\n}\n\n#[derive(Clone, Copy, Eq, PartialEq, Hash)]\npub struct Vector {\n pub x: i32,\n pub y: i32,\n}\n\npub fn main() -> io::Result<()> {\n let f = File::open(\"./input/day10.txt\")?;\n let mut reader = BufReader::new(f);\n\n let re =\n Regex::new(r\"^position=< ?(-?\\d+), ?(-?\\d+)> velocity=< ?(-?\\d+), ?(-?\\d+)>$\").unwrap();\n let lights: Vec<_> = reader\n .by_ref()\n .lines()\n .map(|l| {\n let line = l.unwrap();\n let line_ref = line.trim().as_ref();\n let cap = re.captures(line_ref).unwrap();\n\n let x_pos: i32 = cap[1].parse().unwrap();\n let y_pos: i32 = cap[2].parse().unwrap();\n let x_vel: i32 = cap[3].parse().unwrap();\n let y_vel: i32 = cap[4].parse().unwrap();\n\n Light {\n pos: Vector { x: x_pos, y: y_pos },\n vel: Vector { x: x_vel, y: y_vel },\n }\n })\n .collect();\n\n let mut prev_dev = VecDeque::new();\n\n for t in 0.. {\n let sim = simulate_movement(&lights, t);\n let y_avg: i32 = sim.iter().map(|l| l.pos.y).sum::() / sim.len() as i32;\n let y_dev = sim\n .iter()\n .map(|l| {\n let dev = y_avg - l.pos.y;\n dev.abs()\n })\n .sum::();\n\n if prev_dev.len() > 6 {\n prev_dev.pop_front();\n let rolling_dev =\n prev_dev.iter().map(|av: &(i32, i32)| av.1).sum::() / prev_dev.len() as i32;\n if y_dev > rolling_dev {\n break;\n }\n }\n prev_dev.push_back((t, y_dev));\n }\n\n let min_dev = prev_dev.iter().min_by_key(|(_, dev)| dev).unwrap();\n let sim = simulate_movement(&lights, min_dev.0);\n\n print_lights(&sim);\n\n Ok(())\n}\n\nfn print_lights(lights: &Vec) {\n let (min, max) = lights\n .iter()\n .fold((lights[0].pos, lights[0].pos), |(mut min, mut max), l| {\n //let (min, max) = (min, max);\n min.x = cmp::min(min.x, l.pos.x);\n min.y = cmp::min(min.y, l.pos.y);\n max.x = cmp::max(max.x, l.pos.x);\n max.y = cmp::max(max.y, l.pos.y);\n (min, max)\n });\n\n let mut light_set = HashSet::new();\n for l in lights {\n light_set.insert(l.pos);\n }\n\n for y in min.y..=max.y {\n for x in min.x..=max.x {\n let disp_char = match light_set.get(&Vector { x, y }) {\n Some(_) => '#',\n None => '.',\n };\n print!(\"{}\", disp_char);\n }\n println!();\n }\n}\n\npub fn simulate_movement(lights: &Vec, time: i32) -> Vec {\n lights\n .iter()\n .map(|l| Light {\n pos: Vector {\n x: l.pos.x + l.vel.x * time,\n y: l.pos.y + l.vel.y * time,\n },\n vel: Vector {\n x: l.vel.x,\n y: l.vel.y,\n },\n })\n .collect()\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2938,"cells":{"blob_id":{"kind":"string","value":"97da531d9ce4814033a7e71857f6c08bc0d22b83"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Indy2222/introns"},"path":{"kind":"string","value":"/preprocess/src/samples/io.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6475,"string":"6,475"},"score":{"kind":"number","value":2.75,"string":"2.75"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use crate::features::FeatureId;\nuse anyhow::{Context, Error, Result};\nuse ncrs::data::Symbol;\nuse ndarray::{arr0, Array, Array2};\nuse ndarray_npy::NpzWriter;\nuse std::convert::TryFrom;\nuse std::fs::{self, File, OpenOptions};\nuse std::path::{Path, PathBuf};\n\npub struct OrganismWriter {\n target_dir: PathBuf,\n counter: u64,\n path_writer: csv::Writer,\n}\n\nimpl OrganismWriter {\n pub fn with_target_dir>(target_dir: P, organism_id: &str) -> Result {\n let mut target_dir = target_dir.as_ref().to_path_buf();\n target_dir.push(organism_id);\n\n if !target_dir.exists() {\n fs::create_dir(&target_dir).context(format!(\n \"Failed to create directory for samples of organism {}\",\n organism_id\n ))?;\n }\n\n let path_writer = {\n let mut csv_path = target_dir.clone();\n csv_path.push(\"samples.csv\");\n\n let create_file = !csv_path.exists();\n let file = OpenOptions::new()\n .create(create_file)\n .append(true)\n .open(&csv_path)\n .with_context(|| {\n format!(\"Failed to create samples CSV file {}\", csv_path.display())\n })?;\n\n let mut path_writer = csv::WriterBuilder::new().from_writer(file);\n\n if create_file {\n path_writer.serialize((\n \"path\",\n \"is_positive\",\n \"sample_type_name\",\n \"feature_id\",\n \"absolute_position\",\n \"scaffold_name\",\n ))?;\n }\n\n path_writer\n };\n\n Ok(Self {\n target_dir,\n path_writer,\n counter: 0,\n })\n }\n\n /// Store a new sample to disk.\n ///\n /// # Arguments\n ///\n /// * `sequence` - input sequence to be stored in the sample.\n ///\n /// * `relative_position` - 0-based position of splice-site within the sequence.\n pub fn write(\n &mut self,\n sequence: &[Symbol],\n is_positive: bool,\n sample_type_name: &str,\n relative_position: usize,\n absolute_position: usize,\n feature_id: Option,\n scaffold_name: &str,\n ) -> Result<()> {\n let relative_sample_path = self.relative_sample_path(is_positive, sample_type_name);\n let mut target_file_path = self.target_dir.clone();\n target_file_path.push(&relative_sample_path);\n\n {\n let target_sub_dir = target_file_path.parent().unwrap();\n fs::create_dir_all(&target_sub_dir).with_context(|| {\n format!(\n \"Failed to create samples directory {}\",\n target_sub_dir.display()\n )\n })?;\n }\n\n let input = sequence_to_one_hot(&sequence);\n let output = arr0(if is_positive { 1.0 } else { 0.0 });\n\n {\n let file = File::create(&target_file_path).context(\"Failed to store a sample\")?;\n let mut npz_writer = NpzWriter::new_compressed(file);\n\n let error_context = || {\n format!(\n \"Error while writing to target file {}\",\n target_file_path.display()\n )\n };\n\n if relative_position > sequence.len() {\n panic!(\"Relative splice-site position out of sequence bounds.\");\n }\n let relative_position = arr0(\n u64::try_from(relative_position)\n .context(\"Splice-site position cannot be serialized\")?,\n );\n\n npz_writer\n .add_array(\"position\", &relative_position)\n .with_context(error_context)?;\n\n npz_writer\n .add_array(\"input\", &input)\n .with_context(error_context)?;\n npz_writer\n .add_array(\"output\", &output)\n .with_context(error_context)?;\n }\n\n self.write_path(\n &relative_sample_path,\n is_positive,\n sample_type_name,\n feature_id,\n absolute_position,\n scaffold_name,\n )?;\n\n self.counter += 1;\n Ok(())\n }\n\n fn write_path(\n &mut self,\n relative_path: &Path,\n is_positive: bool,\n sample_type_name: &str,\n feature_id: Option,\n absolute_position: usize,\n scaffold_name: &str,\n ) -> Result<()> {\n if relative_path.is_absolute() {\n panic!(\n \"Relative sample path expected, got absolute path: {}\",\n relative_path.display()\n );\n }\n\n let feature_id = match feature_id {\n Some(feature_id) => feature_id.to_hex(),\n None => String::new(),\n };\n\n let absolute_position = format!(\"{}\", absolute_position);\n\n self.path_writer\n .serialize((\n relative_path\n .to_str()\n .expect(\"Failed to serialize sample path as a UTF-8 string.\"),\n format!(\"{}\", is_positive),\n sample_type_name,\n feature_id,\n absolute_position,\n scaffold_name,\n ))\n .map_err(Error::new)\n }\n\n fn relative_sample_path(&self, is_positive: bool, sample_type_name: &str) -> PathBuf {\n let mut relative_path = PathBuf::new();\n\n relative_path.push(format!(\"{:04}\", self.counter >> 16));\n relative_path.push(format!(\"{:03}\", (self.counter >> 8) & 0xff));\n\n let mut file_name = String::new();\n if is_positive {\n file_name.push_str(\"positive_\");\n } else {\n file_name.push_str(\"negative_\");\n }\n file_name.push_str(sample_type_name);\n file_name.push_str(&format!(\"_{:03}.npz\", self.counter & 0xff));\n\n relative_path.push(file_name);\n\n relative_path\n }\n}\n\n/// Create a one-hot-encoded 2D array of a sequence. First dimension\n/// represents individual sequence positions and second dimension represents\n/// one-hot-encoding.\nfn sequence_to_one_hot(sequence: &[Symbol]) -> Array2 {\n let mut input = Array::zeros((sequence.len(), 5));\n\n for (i, symbol) in sequence.iter().enumerate() {\n let pos: usize = (*symbol).into();\n input[(i, pos)] = 1.;\n }\n\n input\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2939,"cells":{"blob_id":{"kind":"string","value":"bd343b0c2338bee0b60f4e0baa7c43e2e41e35db"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"NyxTo/Advent-of-Code"},"path":{"kind":"string","value":"/2019/Code/day_10_asteroid.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1473,"string":"1,473"},"score":{"kind":"number","value":2.921875,"string":"2.921875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::fs::File;\r\nuse std::io::{BufRead, BufReader};\r\nuse std::cmp::{min, max};\r\n\r\nfn gcd(mut a: usize, mut b: usize) -> usize {\r\n\twhile b > 0 {\r\n\t\tlet rem = a % b;\r\n\t\ta = b;\r\n\t\tb = rem;\r\n\t}\r\n\ta\r\n}\r\n\r\nfn main() {\r\n\tlet grid = BufReader::new(File::open(\"in_10.txt\").unwrap()).lines().map(|row| row.unwrap().chars().collect::>()).collect::>();\r\n\tlet (hgt, wid, mut max_det, mut vapour) = (grid.len(), grid[0].len(), 0, (0, 0));\r\n\tfor sy in 0..hgt {\r\n\tfor sx in 0..wid {\r\n\tif grid[sy][sx] == '#' {\r\n\t\tlet (mut detect, mut btwn, mut aster, mut ang) = (0, vec![vec![0; wid]; hgt], vec![], vec![vec![0.; wid]; hgt]);\r\n\t\tfor ey in 0..hgt {\r\n\t\tfor ex in 0..wid {\r\n\t\tif grid[ey][ex] == '#' {\r\n\t\t\tif ex == sx && ey == sy { continue; }\r\n\t\t\tlet num = gcd(max(sx, ex) - min(sx, ex), max(sy, ey) - min(sy, ey));\r\n\t\t\tbtwn[ey][ex] = (1..num).filter(|i| {\r\n\t\t\t\tlet (bx, by) = ((sx * (num - i) + ex * i) / num, (sy * (num - i) + ey * i) / num);\r\n\t\t\t\tgrid[by][bx] == '#'\r\n\t\t\t}).count();\r\n\t\t\tif btwn[ey][ex] == 0 { detect += 1; }\r\n\t\t\taster.push((ex, ey));\r\n\t\t\tang[ey][ex] = (ex as f64 - sx as f64).atan2(ey as f64 - sy as f64);\r\n\t\t}\r\n\t\t}\r\n\t\t}\r\n\t\tif detect >= max_det {\r\n\t\t\tmax_det = detect;\r\n\t\t\taster.sort_by(|(x1, y1), (x2, y2)| ang[*y2][*x2].partial_cmp(&ang[*y1][*x1]).unwrap());\r\n\t\t\taster.sort_by_key(|(x, y)| btwn[*y][*x]);\r\n\t\t\tvapour = aster[199];\r\n\t\t}\r\n\t}\r\n\t}\r\n\t}\r\n\tprintln!(\"Part A: {}\", max_det); // 221\r\n\tprintln!(\"Part B: {}\", vapour.0 * 100 + vapour.1); // 806\r\n}\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2940,"cells":{"blob_id":{"kind":"string","value":"fb77b7aa24d2d3bd97c7f147c149665782414c1d"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"algon-320/mandarin"},"path":{"kind":"string","value":"/kernel/src/global.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1247,"string":"1,247"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use crate::console::{Attribute, Console};\nuse crate::graphics::{font, FrameBuffer, Scaled};\n\nuse crate::sync::spin::SpinMutex;\nuse core::mem::MaybeUninit;\n\npub static FRAME_BUF: SpinMutex>> =\n SpinMutex::new(\"frame_buffer\", MaybeUninit::uninit());\n\npub fn init_frame_buffer(frame_buffer: FrameBuffer) {\n let mut fb = FRAME_BUF.lock();\n unsafe { fb.as_mut_ptr().write(Scaled(frame_buffer)) };\n}\n\npub fn lock_frame_buffer)>(mut f: F) {\n let mut fb = FRAME_BUF.lock();\n let fb = unsafe { &mut *fb.as_mut_ptr() };\n f(fb)\n}\n\npub static CONSOLE: SpinMutex = SpinMutex::new(\"console\", Console::new(80, 27));\n\npub fn init_console(columns: usize, lines: usize) {\n let mut console = CONSOLE.lock();\n console.resize(columns, lines);\n}\n\npub fn console_write(attr: Attribute, args: core::fmt::Arguments) {\n let mut console = CONSOLE.lock();\n\n use core::fmt::Write;\n let old_attr = console.attr;\n console.attr = attr;\n console.write_fmt(args).unwrap();\n console.attr = old_attr;\n}\npub fn console_flush() {\n let mut console = CONSOLE.lock();\n\n lock_frame_buffer(|fb| {\n console.render(fb, &mut font::ShinonomeFont);\n });\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2941,"cells":{"blob_id":{"kind":"string","value":"ca3b5872214906c728258dca015c36f1abc89c86"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"rob-clarke/arusti"},"path":{"kind":"string","value":"/arusti/tests/olan_tests.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4264,"string":"4,264"},"score":{"kind":"number","value":3.0625,"string":"3.0625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use arusti;\n\nuse arusti::{ElementType,Element};\n\nfn compare_elements(result: &Vec, expectation: &Vec) {\n assert_eq!(result.len(), expectation.len(), \"Figure has wrong number of elements\");\n for (index,(result,expected)) in result.iter().zip( expectation.iter() ).enumerate() {\n assert_eq!(result, expected, \"Element {} does not match expectation\", index);\n }\n }\n\n#[test]\nfn loop_plain() {\n let sequence_str = \"o\".to_string();\n let sequence = arusti::olan::parse_sequence(sequence_str);\n\n let expected_elements = vec![\n Element::line(0.0),\n Element::radius(180.0),\n Element::radius(180.0),\n Element::line(0.0),\n ];\n \n compare_elements(&sequence.figures[0].elements, &expected_elements);\n }\n\n#[test]\nfn loop_with_leading_roll() {\n let sequence_str = \"1o\".to_string();\n let sequence = arusti::olan::parse_sequence(sequence_str);\n\n let expected_elements = vec![\n Element::line(0.0),\n Element { angle: 360.0, argument: 1.0, .. Element::new(ElementType::Roll) },\n Element::radius(180.0),\n Element::radius(180.0),\n Element::line(0.0),\n ];\n \n compare_elements(&sequence.figures[0].elements, &expected_elements);\n }\n\n#[test]\nfn loop_with_combining_roll() {\n let sequence_str = \"o1\".to_string();\n let sequence = arusti::olan::parse_sequence(sequence_str);\n\n let expected_elements = vec![\n Element::line(0.0),\n Element::radius(180.0),\n Element { angle: 360.0, argument: 1.0, .. Element::new(ElementType::Roll) },\n Element::radius(180.0),\n Element::line(0.0),\n ];\n \n compare_elements(&sequence.figures[0].elements, &expected_elements);\n }\n\n#[test]\nfn loop_with_all_rolls() {\n let sequence_str = \"1o1\".to_string();\n let sequence = arusti::olan::parse_sequence(sequence_str);\n\n let expected_elements = vec![\n Element::line(0.0),\n Element { angle: 360.0, argument: 1.0, .. Element::new(ElementType::Roll) },\n Element::radius(180.0),\n Element { angle: 360.0, argument: 1.0, .. Element::new(ElementType::Roll) },\n Element::radius(180.0),\n Element::line(0.0),\n ];\n \n compare_elements(&sequence.figures[0].elements, &expected_elements);\n }\n\n#[test]\nfn loop_with_inverted_flight() {\n let sequence_str = \"-o-\".to_string();\n let sequence = arusti::olan::parse_sequence(sequence_str);\n\n let expected_elements = vec![\n Element::invline(0.0),\n Element::radius(-180.0),\n Element::radius(-180.0),\n Element::invline(0.0),\n ];\n \n compare_elements(&sequence.figures[0].elements, &expected_elements);\n }\n\n#[test]\nfn loop_with_inverted_entry_and_inverting_leading_roll() {\n let sequence_str = \"-2o\".to_string();\n let sequence = arusti::olan::parse_sequence(sequence_str);\n\n let expected_elements = vec![\n Element::invline(0.0),\n Element { angle: 180.0, argument: 1.0, .. Element::new(ElementType::Roll) },\n Element::radius(180.0),\n Element::radius(180.0),\n Element::line(0.0),\n ];\n \n compare_elements(&sequence.figures[0].elements, &expected_elements);\n }\n\n#[test]\nfn loop_with_inverted_entry_and_inverting_combining_roll() {\n let sequence_str = \"-o2\".to_string();\n let sequence = arusti::olan::parse_sequence(sequence_str);\n\n let expected_elements = vec![\n Element::invline(0.0),\n Element::radius(-180.0),\n Element { angle: 180.0, argument: 1.0, .. Element::new(ElementType::Roll) },\n Element::radius(180.0),\n Element::line(0.0),\n ];\n \n compare_elements(&sequence.figures[0].elements, &expected_elements);\n }\n\n#[test]\nfn hammerhead_turn() {\n let sequence_str = \"h\".to_string();\n let sequence = arusti::olan::parse_sequence(sequence_str);\n\n let expected_elements = vec![\n Element::line(0.0), \n Element::radius(90.0),\n Element::line(90.0),\n Element { angle: 180.0, argument: 0.0, .. Element::new(ElementType::Stall) },\n Element::line(-90.0),\n Element::radius(90.0),\n Element::line(0.0),\n ];\n \n compare_elements(&sequence.figures[0].elements, &expected_elements);\n }\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2942,"cells":{"blob_id":{"kind":"string","value":"04b6bedbfb90e194343d2fd56500d851e2843422"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"m-lima/advent-of-code-2020"},"path":{"kind":"string","value":"/src/bin/112/build.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":814,"string":"814"},"score":{"kind":"number","value":2.625,"string":"2.625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"pub fn prepare() {\n use std::io::Write;\n\n const OUTPUT: &str = \"src/bin/112/input.rs\";\n const INPUT: &str = include_str!(\"input.txt\");\n println!(\"cargo:rerun-if-changed=src/bin/112/{}\", INPUT);\n\n let input: Vec<_> = INPUT\n .split('\\n')\n .filter(|line| !line.is_empty())\n .map(|line| line.chars().collect::>())\n .collect();\n\n let mut output = std::fs::File::create(OUTPUT).unwrap();\n output\n .write_all(\n format!(\n \"pub const INPUT: [[char; {}]; {}] = [\",\n input[0].len(),\n input.len()\n )\n .as_bytes(),\n )\n .unwrap();\n\n for line in input {\n output.write_all(format!(\"{:?},\", line).as_bytes()).unwrap();\n }\n\n output.write_all(b\"];\").unwrap();\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2943,"cells":{"blob_id":{"kind":"string","value":"1f1bd79e8d27d676bd719d96aaa3a92ee51c7b2e"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"longlb/exercism"},"path":{"kind":"string","value":"/rust/triangle/src/lib.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":987,"string":"987"},"score":{"kind":"number","value":3.578125,"string":"3.578125"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"pub struct Triangle {\n side1: u64,\n side2: u64,\n side3: u64,\n}\n\nimpl Triangle {\n pub fn build(sides: [u64; 3]) -> Option {\n let new_tri = Triangle {\n side1: sides[0],\n side2: sides[1],\n side3: sides[2],\n };\n\n if new_tri.is_valid() {\n Some(new_tri)\n } else {\n None\n }\n }\n\n pub fn is_equilateral(&self) -> bool {\n self.side1 == self.side2 && self.side2 == self.side3 && self.side3 == self.side1\n }\n\n pub fn is_scalene(&self) -> bool {\n self.side1 != self.side2 && self.side2 != self.side3 && self.side3 != self.side1\n }\n\n pub fn is_isosceles(&self) -> bool {\n self.side1 == self.side2 || self.side2 == self.side3 || self.side3 == self.side1\n }\n\n fn is_valid(&self) -> bool {\n self.side1 < self.side2 + self.side3\n && self.side2 < self.side1 + self.side3\n && self.side3 < self.side1 + self.side2\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2944,"cells":{"blob_id":{"kind":"string","value":"e393954bde0ff61b876070ee5572e15717893ce3"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"acohen4/steelmate"},"path":{"kind":"string","value":"/src/lib/engine.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":13224,"string":"13,224"},"score":{"kind":"number","value":3.15625,"string":"3.15625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use super::board::{Board, Color, Piece, PieceKind, Position};\nuse std::collections::HashMap;\n\nstruct MovePattern {\n is_repeatable: bool,\n move_enumerations: Vec,\n}\n\nimpl MovePattern {\n fn new(is_repeatable: bool, move_enumerations: Vec) -> MovePattern {\n MovePattern {\n is_repeatable,\n move_enumerations,\n }\n }\n}\n\npub enum BoardSetup {\n Basic,\n}\n\npub struct ChessEngine {\n pub board: Board,\n}\n\nimpl ChessEngine {\n\n pub fn create_board(setup: BoardSetup) -> Result {\n match setup {\n BoardSetup::Basic => ChessEngine::setup_basic_board()\n }\n }\n\n pub fn possible_moves(board: &Board, p: &Position) -> Result, String> {\n match board.get_space(p)? {\n Option::None => Ok(vec![]),\n Option::Some(Piece { kind: PieceKind::Pawn, color: c, has_moved: hm }) => {\n Ok(ChessEngine::generate_pawn_moves(board, p, *c, *hm))\n },\n Option::Some(Piece { kind: PieceKind::King, color: c, has_moved: hm }) => {\n Ok(ChessEngine::generate_king_moves(board, p, *c, *hm))\n },\n Option::Some(piece) => {\n let mut solutions = vec![];\n let pattern = ChessEngine::get_move_pattern(piece.kind)?;\n for diff in pattern.move_enumerations.iter() {\n ChessEngine::apply_move(board, &mut solutions, p, diff, &piece.color,\n pattern.is_repeatable)\n }\n Ok(solutions)\n }\n }\n }\n\n fn generate_king_moves(board: &Board, p: &Position, color: Color, has_moved: bool)\n -> Vec {\n let mut solutions = vec![];\n if !has_moved {\n if ChessEngine::can_side_castle(board, p, true) {\n solutions.push(Position::new(p.row, p.col - 3));\n }\n if ChessEngine::can_side_castle(board, p, false) {\n solutions.push(Position::new(p.row, p.col + 2));\n }\n }\n // do the basic case\n let surroundings: Vec = ChessEngine::expand_with_inverses(vec![\n Position::new(0, 1),\n Position::new(1, 0),\n Position::new(1, 1),\n ])\n .iter()\n .map(|pos| Position::add(p, pos))\n .collect();\n\n for pos in surroundings {\n if let Ok(_) = board.get_space(&pos) {\n if ChessEngine::is_enemy_space(board, &pos, color)\n || board.is_empty_space(&pos) {\n if !ChessEngine::is_threatened(board, &pos, color) {\n solutions.push(pos.clone());\n }\n }\n }\n }\n solutions\n }\n\n fn can_side_castle(board: &Board, king_pos: &Position, is_left: bool) -> bool {\n let direction = if is_left { -1 } else { 1 };\n let rook_col = if is_left { 0 } else { (board.get_size() as i32) - 1 };\n let mut can_castle =\n match board.get_space(&Position::new(king_pos.row, rook_col)){\n Ok(Option::Some(Piece {kind: _, color: _, has_moved: false})) => true,\n _ => false,\n };\n let mut i = king_pos.col;\n while i > 0 && can_castle {\n i = i + direction;\n match board.get_space(&Position::new(king_pos.row, i)) {\n Ok(Option::Some(_)) => can_castle = false,\n _ => ()\n }\n }\n can_castle\n }\n\n fn generate_pawn_moves(board: &Board, p: &Position, c: Color, has_moved: bool) -> Vec{\n // convert color to direction\n let mut solutions = vec![];\n let direction = if c == Color::White { 1 } else { -1 };\n let forward_space = Position::new(direction + p.row, p.col);\n if let Ok(Option::None) = board.get_space(&forward_space) {\n solutions.push(forward_space);\n if has_moved == false {\n let double_forward_space = Position::new(2 * direction + p.row\n , p.col);\n if let Ok(Option::None) = board.get_space(&double_forward_space) {\n solutions.push(double_forward_space);\n }\n }\n }\n let positive_diagonal_space = Position::new(p.row + direction\n , p.col + 1);\n if ChessEngine::is_enemy_space(board, &positive_diagonal_space, c) {\n solutions.push(positive_diagonal_space);\n }\n let negative_diagonal_space = Position::new(p.row + direction\n , p.col - 1);\n if ChessEngine::is_enemy_space(board, &negative_diagonal_space, c) {\n solutions.push(negative_diagonal_space);\n }\n solutions\n }\n\n fn is_enemy_space(board: &Board, p: &Position, c: Color) -> bool {\n if let Ok(\n Option::Some(Piece { kind: _, color: move_color, has_moved: _ })\n ) = board.get_space(p) {\n *move_color != c\n } else {\n false\n }\n }\n\n pub fn execute_move(board: &mut Board, from: &Position, to: &Position)\n -> Result, String> {\n let possibilities = ChessEngine::possible_moves(board, from)?;\n if possibilities.contains(to) {\n // if castle, also move Rook\n if ChessEngine::is_castle(board, from, to) {\n ChessEngine::castle_rook(board, from, to)?;\n }\n Ok(board.move_piece(from, to)?)\n } else {\n Err(String::from(\"You cannot move to this space\"))\n }\n }\n\n fn apply_move(\n board: &Board,\n sink: &mut Vec,\n pos: &Position,\n diff: &Position,\n color: &Color,\n repeat: bool,\n ) {\n let check_pos = Position::add(pos, diff);\n println!(\"Checking Position\");\n println!(\"{:?}\", check_pos);\n if let Err(_) = board.validate_position(&check_pos) {\n return;\n }\n if let Ok(space) = board.get_space(&check_pos) {\n match space {\n Option::None => {\n sink.push(check_pos);\n if repeat {\n ChessEngine::apply_move(board, sink, &check_pos, diff, color, repeat);\n }\n }\n Option::Some(piece) => {\n if piece.color != *color {\n sink.push(check_pos);\n }\n }\n }\n }\n }\n\n fn get_move_pattern(kind: PieceKind) -> Result {\n match kind {\n PieceKind::King | PieceKind::Pawn => Err(String::from(\"not supported\")),\n PieceKind::Queen => {\n let moves = ChessEngine::expand_with_inverses(vec![\n Position::new(0, 1),\n Position::new(1, 0),\n Position::new(1, 1),\n ]);\n Ok(MovePattern::new(true, moves))\n }\n PieceKind::Rook => {\n let moves = ChessEngine::expand_with_inverses(vec![\n Position::new(0, 1),\n Position::new(1, 0),\n ]);\n Ok(MovePattern::new(true, moves))\n }\n PieceKind::Bishop => {\n Ok(MovePattern::new(true, Position::new(1, 1)\n .yield_all_inverse_positions()))\n }\n PieceKind::Knight => {\n let moves = ChessEngine::expand_with_inverses(vec![\n Position::new(1, 2),\n Position::new(2, 1),\n ]);\n Ok(MovePattern::new(false, moves))\n }\n }\n }\n\n fn expand_with_inverses(positions: Vec) -> Vec {\n //positions.iter().map(|pos| pos.yield_all_inverse_positions()).collect()\n let mut expanded = Vec::new();\n for pos in positions.iter() {\n expanded.append(&mut pos.yield_all_inverse_positions());\n }\n expanded\n }\n\n fn is_castle(board: &Board, from: &Position, to: &Position) -> bool {\n board.get_space(from).unwrap().unwrap().kind == PieceKind::King\n && (from.col - to.col).abs() == 2\n }\n\n fn castle_rook(board: &mut Board, king_start: &Position, king_dest: &Position) -> Result<(), String> {\n let is_right = king_start.col > king_dest.col;\n let rook_from_col = if is_right {0} else {board.get_size() as i32};\n let rook_to_col = if is_right {king_dest.col - 1} else {king_dest.col + 1};\n ChessEngine::execute_move(board, &Position::new(king_start.row, rook_from_col),\n &Position::new(king_start.row, rook_to_col))?;\n Ok(())\n }\n\n fn is_threatened(board: &Board, pos: &Position, color: Color) -> bool {\n let threatened = board.get_piece_positions().iter()\n .filter(|(_, piece)| piece.color != color)\n .flat_map(|(position, _)| ChessEngine::possible_moves(board, position).unwrap())\n .any(|possible_move| possible_move == *pos);\n threatened\n }\n\n fn setup_basic_board() -> Result{\n let mut b = Board::new(8)?;\n //setup pawns\n b.fill(Some(6), None, Piece::new(PieceKind::Pawn, Color::Black))?;\n b.fill(Some(1), None, Piece::new(PieceKind::Pawn, Color::White))?;\n\n // populate accepts map of Spot => Piece\n let mut map = HashMap::new();\n // handle rooks\n map.insert(\n Position::new(0, 0),\n Piece::new(PieceKind::Rook, Color::White),\n );\n map.insert(\n Position::new(0, 7),\n Piece::new(PieceKind::Rook, Color::White),\n );\n map.insert(\n Position::new(7, 0),\n Piece::new(PieceKind::Rook, Color::Black),\n );\n map.insert(\n Position::new(7, 7),\n Piece::new(PieceKind::Rook, Color::Black),\n );\n // handle knights\n map.insert(\n Position::new(0, 1),\n Piece::new(PieceKind::Knight, Color::White),\n );\n map.insert(\n Position::new(0, 6),\n Piece::new(PieceKind::Knight, Color::White),\n );\n map.insert(\n Position::new(7, 1),\n Piece::new(PieceKind::Knight, Color::Black),\n );\n map.insert(\n Position::new(7, 6),\n Piece::new(PieceKind::Knight, Color::Black),\n );\n // handle bishops\n map.insert(\n Position::new(0, 2),\n Piece::new(PieceKind::Bishop, Color::White),\n );\n map.insert(\n Position::new(0, 5),\n Piece::new(PieceKind::Bishop, Color::White),\n );\n map.insert(\n Position::new(7, 2),\n Piece::new(PieceKind::Bishop, Color::Black),\n );\n map.insert(\n Position::new(7, 5),\n Piece::new(PieceKind::Bishop, Color::Black),\n );\n // handle queens\n map.insert(\n Position::new(0, 3),\n Piece::new(PieceKind::Queen, Color::White),\n );\n map.insert(\n Position::new(7, 3),\n Piece::new(PieceKind::Queen, Color::Black),\n );\n // handle kings\n map.insert(\n Position::new(0, 4),\n Piece::new(PieceKind::King, Color::White),\n );\n map.insert(\n Position::new(7, 4),\n Piece::new(PieceKind::King, Color::Black),\n );\n b.populate(map)?;\n Ok(b)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_basic_board() -> Result<(), String> {\n let board = ChessEngine::setup_basic_board()?;\n let pos = Position::new(0, 1);\n let res = board.get_space(&pos);\n let op = res?;\n\n assert_eq!(\n Some(&Piece {\n kind: PieceKind::Knight,\n color: Color::White,\n has_moved: false\n }),\n op\n );\n Ok(())\n }\n\n #[test]\n fn test_move_piece() -> Result<(), String> {\n let mut board = ChessEngine::setup_basic_board()?;\n let from = Position::new(1, 1);\n let to = Position::new(2, 1);\n ChessEngine::execute_move(&mut board, &from, &to)?;\n\n let op_to = board.get_space(&to)?;\n let op_from = board.get_space(&from)?;\n assert_eq!(\n Some(&Piece {\n kind: PieceKind::Pawn,\n color: Color::White,\n has_moved: true\n }),\n op_to\n );\n assert_eq!(None, op_from);\n Ok(())\n }\n\n #[test]\n fn test_possible_moves() -> Result<(), String> {\n let board = ChessEngine::setup_basic_board()?;\n let pos = Position::new(0, 1);\n let possibilities = ChessEngine::possible_moves(&board, &pos)?;\n\n board.pretty_print();\n\n println!(\"{:?}\", possibilities);\n assert_eq!(possibilities.len(), 2);\n Ok(())\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2945,"cells":{"blob_id":{"kind":"string","value":"b36f1451cae914f0eea9f2760d6377ec041aed44"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"yaozijian/RustProgramming"},"path":{"kind":"string","value":"/chap15/src/section1.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":667,"string":"667"},"score":{"kind":"number","value":3.71875,"string":"3.71875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"pub fn demo(){\n\n let x = 5;\n let y = &x;\n let z = Box::new(x);\n\n assert_eq!(x,5);\n assert_eq!(*y,5);\n assert_eq!(*z,5);\n}\n\npub fn demo2(){\n\n struct MyBox(T);\n\n impl MyBox{\n fn new(x: T) -> MyBox{\n MyBox(x)\n }\n }\n\n use std::ops::Deref;\n\n impl Deref for MyBox{\n type Target = T;\n fn deref(&self) -> &T{\n &self.0\n }\n }\n\n let x = 5;\n let y = &x;\n let z = MyBox::new(x);\n let a = MyBox::new(String::from(\"ABC\"));\n\n fn hello(x : &str){ println!(\"{}\",x); };\n\n assert_eq!(x,5);\n assert_eq!(*y,5);\n assert_eq!(*z,5);\n assert_eq!(*a,String::from(\"ABC\"));\n\n hello(a.deref().deref());\n hello(&a);\n hello(&*a);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2946,"cells":{"blob_id":{"kind":"string","value":"0aed52d6d235a63d94a9e35e41fca828a0307f8a"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"zhengrenzhe/nand2tetris"},"path":{"kind":"string","value":"/compiler/vm-compiler/src/lexical.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1670,"string":"1,670"},"score":{"kind":"number","value":3.4375,"string":"3.4375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#[derive(Debug)]\npub struct Token {\n pub command: String,\n pub target: String,\n pub arg: String,\n}\n\npub fn lexical(code: &str) -> Option {\n let parts: Vec<&str> = code.split(' ').filter(|code| !code.is_empty()).collect();\n\n if parts.is_empty() {\n return None;\n }\n\n Some(Token {\n command: String::from(parts[0]),\n target: String::from(*parts.get(1).unwrap_or(&\"\")),\n arg: String::from(*parts.get(2).unwrap_or(&\"\")),\n })\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_lexical_analysis() {\n if let Some(val) = lexical(\"\") {\n panic!(format!(\"val: {:?} should be None\", val));\n }\n\n match lexical(\"add\") {\n Some(token) => {\n assert_eq!(token.command, String::from(\"add\"));\n assert_eq!(token.target, String::from(\"\"));\n assert_eq!(token.arg, String::from(\"\"));\n }\n None => panic!(\"should not be None\"),\n }\n\n match lexical(\"push 12\") {\n Some(token) => {\n assert_eq!(token.command, String::from(\"push\"));\n assert_eq!(token.target, String::from(\"12\"));\n assert_eq!(token.arg, String::from(\"\"));\n }\n None => panic!(\"should not be None\"),\n }\n\n match lexical(\"push constant 12\") {\n Some(token) => {\n assert_eq!(token.command, String::from(\"push\"));\n assert_eq!(token.target, String::from(\"constant\"));\n assert_eq!(token.arg, String::from(\"12\"));\n }\n None => panic!(\"should not be None\"),\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2947,"cells":{"blob_id":{"kind":"string","value":"68d2c48e7b995f9cf69a985eb6292ef8c6ee5112"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"chyvonomys/serpanok"},"path":{"kind":"string","value":"/src/format.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5990,"string":"5,990"},"score":{"kind":"number","value":2.765625,"string":"2.765625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use chrono::{Datelike, Timelike};\n\npub fn format_lat_lon(lat: f32, lon: f32) -> String {\n format!(\"{:.03}°{} {:.03}°{}\",\n lat.abs(), if lat > 0.0 {\"N\"} else {\"S\"},\n lon.abs(), if lat > 0.0 {\"E\"} else {\"W\"},\n )\n}\n\nconst MONTH_ABBREVS: [&str; 12] = [\n \"Січ\", \"Лют\", \"Бер\", \"Кві\", \"Тра\", \"Чер\", \"Лип\", \"Сер\", \"Вер\", \"Жов\", \"Лис\", \"Гру\"\n];\n\nfn format_time(t: chrono::DateTime) -> String {\n format!(\"{} {} {:02}:{:02}\",\n t.day(),\n MONTH_ABBREVS.get(t.month0() as usize).unwrap_or(&\"?\"),\n t.hour(), t.minute()\n )\n}\n\nfn format_rain_rate(mmhr: f32) -> String {\n if mmhr < 0.01 {\n None\n } else if mmhr < 2.5 {\n Some(\"\\u{1F4A7}\")\n } else if mmhr < 7.6 {\n Some(\"\\u{1F4A7}\\u{1F4A7}\")\n } else {\n Some(\"\\u{1F4A7}\\u{1F4A7}\\u{1F4A7}\")\n }.map(|g| format!(\"{}{:.2}мм/год\", g, mmhr)).unwrap_or_else(|| \"--\".to_owned())\n}\n\nfn format_snow_rate(mmhr: f32) -> String {\n if mmhr < 0.01 {\n None\n } else if mmhr < 1.3 {\n Some(\"\\u{2744}\")\n } else if mmhr < 3.0 {\n Some(\"\\u{2744}\\u{2744}\")\n } else if mmhr < 7.6 {\n Some(\"\\u{2744}\\u{2744}\\u{2744}\")\n } else {\n Some(\"\\u{2744}\\u{26A0}\")\n }.map(|g| format!(\"{}{:.2}мм/год\", g, mmhr)).unwrap_or_else(|| \"--\".to_owned())\n}\n\nfn format_wind_dir(u: f32, v: f32) -> &'static str {\n let ws_az = (-v).atan2(-u) / std::f32::consts::PI * 180.0;\n\n if ws_az > 135.0 + 22.5 {\n \"\\u{2192}\"\n } else if ws_az > 90.0 + 22.5 {\n \"\\u{2198}\"\n } else if ws_az > 45.0 + 22.5 {\n \"\\u{2193}\"\n } else if ws_az > 22.5 {\n \"\\u{2199}\"\n } else if ws_az > -22.5 {\n \"\\u{2190}\"\n } else if ws_az > -45.0 - 22.5 {\n \"\\u{2196}\"\n } else if ws_az > -90.0 - 22.5 {\n \"\\u{2191}\"\n } else if ws_az > -135.0 - 22.5 {\n \"\\u{2197}\"\n } else {\n \"\\u{2192}\"\n }\n}\n\nuse crate::data;\n\npub struct ForecastText(pub String);\n\npub fn format_place_link(name: &Option, lat: f32, lon: f32) -> String {\n let text = name.clone().unwrap_or_else(|| format_lat_lon(lat, lon));\n format!(\"[{}](http://www.openstreetmap.org/?mlat={}&mlon={})\", text, lat, lon)\n}\n\npub fn format_forecast(name: &Option, lat: f32, lon: f32, f: &data::Forecast, tz: chrono_tz::Tz) -> ForecastText {\n let interval = (f.time.1 - f.time.0).num_minutes() as f32;\n let mut result = String::new();\n\n result.push_str(&format_place_link(name, lat, lon));\n result.push('\\n');\n result.push_str(&format!(\"_{}_\\n\", format_time(f.time.0.with_timezone(&tz))));\n if let Some(tmpk) = f.temperature {\n let tmpc = (10.0 * (tmpk - 273.15)).round() / 10.0;\n result.push_str(&format!(\"t повітря: *{:.1}°C*\\n\", tmpc));\n }\n if let Some(rain) = f.rain_accum {\n let rain_rate = ((rain.1 - rain.0) * 60.0 / interval).max(0.0);\n result.push_str(&format!(\"дощ: *{}*\\n\", format_rain_rate(rain_rate)));\n }\n if let Some(snow) = f.snow_accum {\n let snow_rate = ((snow.1 - snow.0) * 60.0 / interval).max(0.0);\n result.push_str(&format!(\"сніг: *{}*\\n\", format_snow_rate(snow_rate)));\n }\n if let Some(snow_depth) = f.snow_depth {\n result.push_str(&format!(\"шар снігу: *{:.01}см*\\n\", snow_depth * 100.0));\n }\n if let Some(clouds) = f.total_cloud_cover {\n result.push_str(&format!(\"хмарність: *{:.0}%*\\n\", clouds.round()));\n }\n if let Some(wind) = f.wind_speed {\n let wind_speed = (wind.0 * wind.0 + wind.1 * wind.1).sqrt();\n result.push_str(&format!(\"вітер: *{} {:.1}м/с*\\n\", format_wind_dir(wind.0, wind.1), (10.0 * wind_speed).round() / 10.0));\n }\n if let Some(relhum) = f.rel_humidity {\n result.push_str(&format!(\"відн. вологість: *{:.0}%*\\n\", relhum));\n }\n if let Some(pmsl) = f.pressure_msl {\n result.push_str(&format!(\"атм. тиск: *{:.0}ммHg*\\n\", pmsl / 133.322))\n }\n ForecastText(result)\n}\n\nuse plotters::prelude::*;\n\npub fn format_exchange_graph(\n rs: &[(chrono::DateTime::, u32, u32)],\n from: &chrono::DateTime::,\n to: &chrono::DateTime::,\n) -> Result {\n let min_buy = rs.iter().map(|x| x.1).min().unwrap_or(0);\n let min_sell = rs.iter().map(|x| x.2).min().unwrap_or(0);\n let max_buy = rs.iter().map(|x| x.1).max().unwrap_or(3000);\n let max_sell = rs.iter().map(|x| x.2).max().unwrap_or(3000);\n\n let min = std::cmp::min(min_buy, min_sell) as f32 / 100.0;\n let max = std::cmp::max(max_buy, max_sell) as f32 / 100.0;\n\n let max_pad = max + 0.1 * (max - min);\n let min_pad = min - 0.1 * (max - min);\n\n let filename = format!(\"plot-{}.png\", chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, false));\n {\n let root = BitMapBackend::new(&filename, (200, 100)).into_drawing_area();\n root.fill(&RGBColor(255, 255, 240));\n let mut chart = ChartBuilder::on(&root)\n .x_label_area_size(20)\n .y_label_area_size(30)\n .build_cartesian_2d(*from..*to, min_pad..max_pad)\n .map_err(|e| e.to_string())?;\n\n chart\n .configure_mesh()\n .light_line_style(BLACK.mix(0.0).filled())\n .x_labels(5)\n .y_labels(5)\n .x_label_formatter(&|dt: &chrono::DateTime::| format!(\"{}:{}\", dt.hour(), dt.minute()))\n .draw()\n .map_err(|e| e.to_string())?;\n\n chart\n .draw_series(LineSeries::new(\n rs.iter().map(|x| (x.0, x.1 as f32 * 0.01)),\n &RGBColor(20, 20, 200),\n ))\n .map_err(|e| e.to_string())?;\n chart\n .draw_series(LineSeries::new(\n rs.iter().map(|x| (x.0, x.2 as f32 * 0.01)),\n &RGBColor(20, 200, 20),\n ))\n .map_err(|e| e.to_string())?;\n }\n Ok(filename)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2948,"cells":{"blob_id":{"kind":"string","value":"b16142cf5144097229d0a02f2e7942b78db3a226"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"mcmcgrath13/delf-rs"},"path":{"kind":"string","value":"/src/graph/mod.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":10170,"string":"10,170"},"score":{"kind":"number","value":3,"string":"3"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use std::collections::{HashMap, HashSet};\nuse std::process::exit;\n\nuse ansi_term::Colour::{Red, Green, Cyan};\nuse petgraph::{\n graph::{EdgeIndex, NodeIndex},\n Directed, Graph, Incoming, Outgoing,\n};\n\n/// The edge of a DelfGraph is a DelfEdge\npub mod edge;\n/// The node of a DelfGraph is a DelfObject\npub mod object;\n\nuse crate::storage::{get_connection, DelfStorageConnection};\nuse crate::DelfYamls;\n\n/// The DelfGraph is the core structure for delf's functionality. It contains the algorithm to traverse the graph, as well as metadata to perform the deletions.\n#[derive(Debug)]\npub struct DelfGraph {\n pub(crate) nodes: HashMap,\n pub(crate) edges: HashMap,\n graph: Graph,\n storages: HashMap>,\n}\n\nimpl DelfGraph {\n /// Create a new DelfGraph from a schema and a config. See [yaml_rust](../../yaml_rust/index.html) for information on creating the Yaml structs, or alternately use the helper functions: [read_files](../fn.read_files.html), [read_yamls](../fn.read_yamls.html) for constructing a DelfGraph from either paths or `&str` of yaml.\n pub fn new(yamls: &DelfYamls) -> DelfGraph {\n let schema = &yamls.schema;\n let config = &yamls.config;\n let mut edges_to_insert = Vec::new();\n let mut nodes = HashMap::::new();\n let mut edges = HashMap::::new();\n\n let mut graph = Graph::::new();\n\n // each yaml is an object\n for yaml in schema.iter() {\n let obj_name = String::from(yaml[\"object_type\"][\"name\"].as_str().unwrap());\n let obj_node = object::DelfObject::from(&yaml[\"object_type\"]);\n\n let node_id = graph.add_node(obj_node);\n nodes.insert(obj_name.clone(), node_id);\n\n // need to make sure all the nodes exist before edges can be added to the graph\n for e in yaml[\"object_type\"][\"edge_types\"].as_vec().unwrap().iter() {\n let delf_edge = edge::DelfEdge::from(e);\n edges_to_insert.push((obj_name.clone(), delf_edge));\n }\n }\n\n // add all the edges to the graph\n for (from, e) in edges_to_insert.iter_mut() {\n if !nodes.contains_key(&e.to.object_type) {\n eprintln!(\"Error creating edge {:#?}: No object with name {:#?}\", e.name, e.to.object_type);\n exit(1);\n }\n let edge_id = graph.add_edge(nodes[from], nodes[&e.to.object_type], e.clone());\n edges.insert(String::from(&e.name), edge_id);\n }\n\n // create the storage map\n let mut storages = HashMap::>::new();\n\n for yaml in config.iter() {\n for storage in yaml[\"storages\"].as_vec().unwrap().iter() {\n let storage_name = String::from(storage[\"name\"].as_str().unwrap());\n storages.insert(\n storage_name,\n get_connection(\n storage[\"plugin\"].as_str().unwrap(),\n storage[\"url\"].as_str().unwrap(),\n ),\n );\n }\n }\n\n return DelfGraph {\n nodes,\n edges,\n graph,\n storages,\n };\n }\n\n /// Pretty print the graph's contents.\n pub fn print(&self) {\n println!(\"{:#?}\", self.graph);\n }\n\n /// Given an edge name, get the corresponding DelfEdge\n pub fn get_edge(&self, edge_name: &String) -> &edge::DelfEdge {\n let edge_id = self.edges.get(edge_name).unwrap();\n return self.graph.edge_weight(*edge_id).unwrap();\n }\n\n /// Given an edge name and the ids of the to/from object instances, delete the edge\n pub fn delete_edge(&self, edge_name: &String, from_id: &String, to_id: &String) {\n let e = self.get_edge(edge_name);\n e.delete_one(from_id, to_id, self);\n }\n\n /// Given an object name, get the corresponding DelfObject\n pub fn get_object(&self, object_name: &String) -> &object::DelfObject {\n let object_id = self.nodes.get(object_name).unwrap();\n return self.graph.node_weight(*object_id).unwrap();\n }\n\n /// Given the object name and the id of the instance, delete the object\n pub fn delete_object(&self, object_name: &String, id: &String) {\n self._delete_object(object_name, id, None);\n }\n\n fn _delete_object(\n &self,\n object_name: &String,\n id: &String,\n from_edge: Option<&edge::DelfEdge>,\n ) {\n let obj = self.get_object(object_name);\n\n let deleted = obj.delete(id, from_edge, &self.storages);\n\n if deleted {\n let edges = self.graph.edges_directed(self.nodes[&obj.name], Outgoing);\n for e in edges {\n e.weight().delete_all(id, &obj.id_type, self);\n }\n }\n }\n\n /// Validate that the objects and edges described in the schema exist in the corresponding storage as expected. Additionally, ensure that all objects in the graph are reachable by traversal via `deep` or `refcount` edges starting at an object with deletion type of `directly`, `directly_only`, `short_ttl`, or `not_deleted`. This ensures that all objects are deletable and accounted for.\n pub fn validate(&self) {\n println!(\"\\u{1f50d} {}\", Cyan.bold().paint(\"Validating DelF graph...\"));\n\n let mut errs = Vec::new();\n let mut passed = true;\n for (_, node_id) in self.nodes.iter() {\n match self.graph\n .node_weight(*node_id)\n .unwrap()\n .validate(&self.storages) {\n Err(e) => errs.push(e),\n _ => ()\n }\n }\n\n if errs.len() > 0 {\n passed = false;\n println!(\"\\u{274c} {}\", Red.paint(\"Not all objects found in storage\"));\n for err in errs.drain(..) {\n println!(\" {}\", err);\n }\n } else {\n println!(\"\\u{2705} {}\", Green.paint(\"Objects exist in storage\"));\n }\n\n for (_, edge_id) in self.edges.iter() {\n match self.graph.edge_weight(*edge_id).unwrap().validate(self) {\n Err(e) => errs.push(e),\n _ => ()\n }\n }\n\n if errs.len() > 0 {\n passed = false;\n println!(\"\\u{274c} {}\", Red.paint(\"Not all edges found in storage\"));\n for err in errs.drain(..) {\n println!(\" {}\", err);\n }\n } else {\n println!(\"\\u{2705} {}\", Green.paint(\"Edges exist in storage\"));\n }\n\n match self.reachability_analysis() {\n Err(e) => errs.push(e),\n _ => ()\n }\n\n if errs.len() > 0 {\n passed = false;\n println!(\"\\u{274c} {}\", Red.paint(\"Not all objects deletable\"));\n for err in errs.drain(..) {\n println!(\" {}\", err);\n }\n } else {\n println!(\"\\u{2705} {}\", Green.paint(\"All objects deletable\"));\n }\n\n if passed {\n println!(\"\\u{1F680} {} \\u{1F680}\", Green.bold().paint(\"Validation successful!\"));\n } else {\n println!(\"\\u{26a0} {} \\u{26a0}\", Red.bold().paint(\"Validation errors found\"));\n }\n }\n\n // Starting from a directly deletable (or excepted) node, ensure all ndoes are reached.\n fn reachability_analysis(&self) -> Result<(), String> {\n let mut visited_nodes = HashSet::new();\n for (_, node_id) in self.nodes.iter() {\n let obj = self.graph.node_weight(*node_id).unwrap();\n match obj.deletion {\n object::DeleteType::ShortTTL\n | object::DeleteType::Directly\n | object::DeleteType::DirectlyOnly\n | object::DeleteType::NotDeleted => {\n // this object is a starting point in traversal, start traversal\n self.visit_node(&obj.name, &mut visited_nodes);\n }\n _ => (),\n }\n }\n\n if visited_nodes.len() != self.nodes.len() {\n let node_set: HashSet = self.nodes.keys().cloned().collect();\n return Err(format!(\n \"Not all objects are deletable: {:?}\",\n node_set.difference(&visited_nodes)\n ));\n } else {\n return Ok(());\n }\n }\n\n // Recursively visit all un-visited nodes that are connected via depp or refcounte edges from the starting node with the passed in name\n fn visit_node(&self, name: &String, visited_nodes: &mut HashSet) {\n visited_nodes.insert(name.clone());\n\n let edges = self.graph.edges_directed(self.nodes[name], Outgoing);\n for e in edges {\n let ew = e.weight();\n match ew.deletion {\n edge::DeleteType::Deep | edge::DeleteType::RefCount => {\n if !visited_nodes.contains(&ew.to.object_type) {\n self.visit_node(&ew.to.object_type, visited_nodes);\n }\n }\n _ => (),\n }\n }\n }\n\n // find all the inbound edges for a given object\n fn get_inbound_edges(&self, obj: &object::DelfObject) -> Vec<&edge::DelfEdge> {\n let object_id = self.nodes.get(&obj.name).unwrap();\n let edges = self.graph.edges_directed(*object_id, Incoming);\n let mut res = Vec::new();\n for edge in edges {\n res.push(edge.weight());\n }\n\n return res;\n }\n\n /// Check all objects in the DelfGraph with the deletion type of `short_ttl` if there are instances of the object which are past their expiration time. If so, delete the objects.\n pub fn check_short_ttl(&self) {\n for (_, node_id) in self.nodes.iter() {\n let obj = self.graph.node_weight(*node_id).unwrap();\n\n for obj_id in obj.check_short_ttl(&self.storages).iter() {\n self.delete_object(&obj.name, obj_id);\n }\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2949,"cells":{"blob_id":{"kind":"string","value":"6c0e8e36b308ca708bae70153efefedd172f86a1"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"DesmondWillowbrook/cargo-optional-features-for-testing-and-examples"},"path":{"kind":"string","value":"/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":316,"string":"316"},"score":{"kind":"number","value":2.96875,"string":"2.96875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use test_features::one::add_one;\n\n#[cfg(feature = \"add_two\")]\nuse test_features::two::add_two;\n\nfn main () -> std::io::Result<()> {\n let num: usize = 5;\n\n println!(\"Add 1 to num: {}\", add_one(num));\n\n #[cfg(feature = \"add_two\")]\n {\n println!(\"Add 2 to num: {}\", add_two(num));\n }\n\n Ok(())\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2950,"cells":{"blob_id":{"kind":"string","value":"c844b05ad06a8c4daa911b893ebd4d3d01a64450"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"schungx/rhai"},"path":{"kind":"string","value":"/tests/debugging.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2320,"string":"2,320"},"score":{"kind":"number","value":2.96875,"string":"2.96875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0","MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"Apache-2.0\",\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"#![cfg(feature = \"debugging\")]\nuse rhai::{Engine, INT};\n\n#[cfg(not(feature = \"no_index\"))]\nuse rhai::Array;\n\n#[cfg(not(feature = \"no_object\"))]\nuse rhai::Map;\n\n#[test]\nfn test_debugging() {\n let mut engine = Engine::new();\n\n engine.register_debugger(\n |_, dbg| dbg,\n |_, _, _, _, _| Ok(rhai::debugger::DebuggerCommand::Continue),\n );\n\n #[cfg(not(feature = \"no_function\"))]\n #[cfg(not(feature = \"no_index\"))]\n {\n let r = engine\n .eval::(\n \"\n fn foo(x) {\n if x >= 5 {\n back_trace()\n } else {\n foo(x+1)\n }\n }\n\n foo(0)\n \",\n )\n .unwrap();\n\n assert_eq!(r.len(), 6);\n\n assert_eq!(engine.eval::(\"len(back_trace())\").unwrap(), 0);\n }\n}\n\n#[test]\n#[cfg(not(feature = \"no_object\"))]\nfn test_debugger_state() {\n let mut engine = Engine::new();\n\n engine.register_debugger(\n |_, mut debugger| {\n // Say, use an object map for the debugger state\n let mut state = Map::new();\n // Initialize properties\n state.insert(\"hello\".into(), (42 as INT).into());\n state.insert(\"foo\".into(), false.into());\n debugger.set_state(state);\n debugger\n },\n |mut context, _, _, _, _| {\n // Print debugger state - which is an object map\n println!(\n \"Current state = {}\",\n context.global_runtime_state().debugger().state()\n );\n\n // Modify state\n let mut state = context\n .global_runtime_state_mut()\n .debugger_mut()\n .state_mut()\n .write_lock::()\n .unwrap();\n let hello = state.get(\"hello\").unwrap().as_int().unwrap();\n state.insert(\"hello\".into(), (hello + 1).into());\n state.insert(\"foo\".into(), true.into());\n state.insert(\"something_new\".into(), \"hello, world!\".into());\n\n // Continue with debugging\n Ok(rhai::debugger::DebuggerCommand::StepInto)\n },\n );\n\n engine.run(\"let x = 42;\").unwrap();\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2951,"cells":{"blob_id":{"kind":"string","value":"1921912b6e8472305a883f1d2b93b569d281c1c7"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"ssolaric/cses.fi"},"path":{"kind":"string","value":"/2. Sorting and Searching/7-sum-of-two-values.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1696,"string":"1,696"},"score":{"kind":"number","value":3.3125,"string":"3.3125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"// This is the 2sum problem.\nuse std::collections::HashMap;\nuse std::io;\nuse std::str;\n\npub struct Scanner {\n reader: R,\n buffer: Vec,\n}\n\nimpl Scanner {\n pub fn new(reader: R) -> Self {\n Self {\n reader,\n buffer: vec![],\n }\n }\n\n pub fn token(&mut self) -> T {\n loop {\n if let Some(token) = self.buffer.pop() {\n return token.parse().ok().expect(\"Failed parse\");\n }\n let mut input = String::new();\n self.reader.read_line(&mut input).expect(\"Failed read\");\n self.buffer = input.split_whitespace().rev().map(String::from).collect();\n }\n }\n}\n\nfn two_sum(values: &[i32], target: i32) -> Option<(usize, usize)> {\n let mut to_index = HashMap::new();\n let n = values.len();\n for i in 0..n {\n let to_find = target - values[i];\n if let Some(ind) = to_index.get(&to_find) {\n return Some((*ind, i));\n }\n to_index.insert(values[i], i);\n }\n None\n}\n\nfn solve(scan: &mut Scanner, out: &mut W) {\n let n: usize = scan.token();\n let target: i32 = scan.token();\n let mut values = Vec::new();\n for _ in 0..n {\n values.push(scan.token::());\n }\n match two_sum(&values, target) {\n Some((pos1, pos2)) => writeln!(out, \"{} {}\", pos1 + 1, pos2 + 1).ok(),\n None => writeln!(out, \"IMPOSSIBLE\").ok(),\n };\n}\n\nfn main() {\n let (stdin, stdout) = (io::stdin(), io::stdout());\n let mut scan = Scanner::new(stdin.lock());\n let mut out = io::BufWriter::new(stdout.lock());\n solve(&mut scan, &mut out);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2952,"cells":{"blob_id":{"kind":"string","value":"0231e78af7a2c964807b586b2b572d0e445cdd36"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"UnicodeSnowman/matasano-crypto-challenges"},"path":{"kind":"string","value":"/rust/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1502,"string":"1,502"},"score":{"kind":"number","value":2.90625,"string":"2.90625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"extern crate matasano;\n\nuse matasano::one;\nuse matasano::two;\n\nfn main() {\n println!(\"{}\", \"Section One\");\n println!(\"{}\", \"================\");\n //one::convert_hex_to_base64(\"49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d\");\n\n //one::fixed_xor();\n\n //let hex_string: &str = \"1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736\";\n //let bytes: Vec = hex_string.from_hex().unwrap();\n //one::single_bit_xor_cypher(&bytes);\n //one::single_bit_xor_cypher(&hex_string);\n\n// let winner = one::detect_single_character_xor();\n// match winner {\n// Ok(w) => println!(\"WINNAR {:?} {:?}\", w.key, w.secret),\n// Err(err) => println!(\"oh noes, you lose {:?}\", err)\n// }\n\n //let key: Vec = vec!(b'I', b'C', b'E');\n //let string_bytes: Vec = \"Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal\".bytes().collect();\n //let xored_string = one::repeating_key_xor(&string_bytes, &key);\n\n //let res = one::break_repeating_key_xor();\n\n println!(\"{}\", \"Section Two\");\n println!(\"{}\", \"================\");\n// let mut bytes = \"YELLOW SUBMARINE\".bytes().collect();\n// two::pad_pkcs_7(&mut bytes, 20);\n// println!(\"{:?}\", String::from_utf8(bytes).unwrap());\n\n //two::an_ecb_cbc_detection_oracle::run();\n //two::byte_at_a_time_ecb_decryption_simple::run();\n //two::ecb_cut_and_paste::run();\n two::byte_at_a_time_ecb_decryption_harder::run();\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2953,"cells":{"blob_id":{"kind":"string","value":"e4c3abce32634160b79e30513b200d65573cb2d5"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Palmr/lameboy"},"path":{"kind":"string","value":"/src/lameboy/cpu/instructions/stack.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1350,"string":"1,350"},"score":{"kind":"number","value":3.25,"string":"3.25"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use crate::lameboy::cpu::Cpu;\n\n/// Push an 8-bit value to the stack.\n/// Decrements the stack pointer and then writes the 8-bit value using the new stack pointer value.\npub fn push_stack_d8(cpu: &mut Cpu, d8: u8) {\n // Decrement stack pointer\n cpu.registers.sp = cpu.registers.sp.wrapping_sub(1);\n\n // Write byte to stack\n cpu.mmu.write8(cpu.registers.sp, d8);\n}\n\n/// Push a 16-bit value to the stack.\n/// Pushing the high byte of the value first, then the low byte.\npub fn push_stack_d16(cpu: &mut Cpu, d16: u16) {\n // Write high byte\n push_stack_d8(cpu, ((d16 >> 8) & 0xFF) as u8);\n // Write low byte\n push_stack_d8(cpu, (d16 & 0xFF) as u8);\n}\n\n/// Pop an 8-bit value off the stack.\n/// Decrements the stack pointer and then writes the 8-bit value using the new stack pointer value.\npub fn pop_stack_d8(cpu: &mut Cpu) -> u8 {\n // Read byte from stack\n let value = cpu.mmu.read8(cpu.registers.sp);\n\n // Increment stack pointer\n cpu.registers.sp = cpu.registers.sp.wrapping_add(1);\n\n value\n}\n\n/// Pop a 16-bit value off the stack.\n/// Pushing the high byte of the value first, then the low byte.\npub fn pop_stack_d16(cpu: &mut Cpu) -> u16 {\n let mut value: u16;\n // Pop low byte\n value = u16::from(pop_stack_d8(cpu));\n // Pop high byte\n value |= (u16::from(pop_stack_d8(cpu))) << 8;\n\n value\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2954,"cells":{"blob_id":{"kind":"string","value":"d8c93dcd1e1c57d800375b0cc53edfdc80aafdc8"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"feds01/lang"},"path":{"kind":"string","value":"/compiler/hash-reporting/src/errors.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1408,"string":"1,408"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"//! Hash Compiler error and warning reporting module\n//!\n//! All rights reserved 2021 (c) The Hash Language authors\n\nuse std::{io, process::exit};\nuse thiserror::Error;\n\nuse hash_ast::error::ParseError;\n\n/// Enum representing the variants of error that can occur when running an interactive session\n#[derive(Error, Debug)]\npub enum InteractiveCommandError {\n #[error(\"Unkown command `{0}`.\")]\n UnrecognisedCommand(String),\n\n #[error(\"Command `{0}` does not take any arguments.\")]\n ZeroArguments(String),\n\n // @Future: Maybe provide a second paramater to support multiple argument command\n #[error(\"Command `{0}` requires one argument.\")]\n ArgumentMismatchError(String),\n\n #[error(\"Unexpected error: `{0}`\")]\n InternalError(String),\n}\n\n/// Error message prefix\nconst ERR: &str = \"\\x1b[31m\\x1b[1merror\\x1b[0m\";\n\n/// Errors that might occur when attempting to compile and or interpret a\n/// program.\n#[derive(Debug, Error)]\npub enum CompilerError {\n #[error(\"{0}\")]\n IoError(#[from] io::Error),\n #[error(\"{message}\")]\n ArgumentError { message: String },\n #[error(\"{0}\")]\n ParseError(#[from] ParseError),\n #[error(\"{0}\")]\n InterpreterError(#[from] InteractiveCommandError),\n}\n\nimpl CompilerError {\n pub fn report_and_exit(&self) -> ! {\n self.report();\n exit(-1);\n }\n\n pub fn report(&self) {\n println!(\"{}: {}\", ERR, self);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2955,"cells":{"blob_id":{"kind":"string","value":"a7b9e243d738716f575b35969fd85aa122dd714c"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"immunant/c2rust"},"path":{"kind":"string","value":"/c2rust-bitfields-derive/src/lib.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8743,"string":"8,743"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause","Apache-2.0"],"string":"[\n \"BSD-3-Clause\",\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"#![recursion_limit = \"512\"]\n\nuse proc_macro::{Span, TokenStream};\nuse quote::quote;\nuse syn::parse::Error;\nuse syn::punctuated::Punctuated;\nuse syn::spanned::Spanned;\nuse syn::{\n parse_macro_input, Attribute, Field, Fields, Ident, ItemStruct, Lit, Meta, NestedMeta, Path,\n PathArguments, PathSegment, Token,\n};\n\n#[cfg(target_endian = \"big\")]\ncompile_error!(\"Big endian architectures are not currently supported\");\n\n/// This struct keeps track of a single bitfield attr's params\n/// as well as the bitfield's field name.\n#[derive(Debug)]\nstruct BFFieldAttr {\n field_name: Ident,\n name: String,\n ty: String,\n bits: (String, proc_macro2::Span),\n}\n\nfn parse_bitfield_attr(\n attr: &Attribute,\n field_ident: &Ident,\n) -> Result, Error> {\n let mut name = None;\n let mut ty = None;\n let mut bits = None;\n let mut bits_span = None;\n\n if let Meta::List(meta_list) = attr.parse_meta()? {\n for nested_meta in meta_list.nested {\n if let NestedMeta::Meta(Meta::NameValue(meta_name_value)) = nested_meta {\n let rhs_string = match meta_name_value.lit {\n Lit::Str(lit_str) => lit_str.value(),\n _ => {\n let err_str = \"Found bitfield attribute with non str literal assignment\";\n let span = meta_name_value.path.span();\n\n return Err(Error::new(span, err_str));\n }\n };\n\n if let Some(lhs_ident) = meta_name_value.path.get_ident() {\n match lhs_ident.to_string().as_str() {\n \"name\" => name = Some(rhs_string),\n \"ty\" => ty = Some(rhs_string),\n \"bits\" => {\n bits = Some(rhs_string);\n bits_span = Some(meta_name_value.path.span());\n }\n // This one shouldn't ever occur here,\n // but we're handling it just to be safe\n \"padding\" => {\n return Ok(None);\n }\n _ => {}\n }\n }\n } else if let NestedMeta::Meta(Meta::Path(ref path)) = nested_meta {\n if let Some(ident) = path.get_ident() {\n if ident == \"padding\" {\n return Ok(None);\n }\n }\n }\n }\n }\n\n if name.is_none() || ty.is_none() || bits.is_none() {\n let mut missing_fields = Vec::new();\n\n if name.is_none() {\n missing_fields.push(\"name\");\n }\n\n if ty.is_none() {\n missing_fields.push(\"ty\");\n }\n\n if bits.is_none() {\n missing_fields.push(\"bits\");\n }\n\n let err_str = format!(\"Missing bitfield params: {:?}\", missing_fields);\n let span = attr.path.segments.span();\n\n return Err(Error::new(span, err_str));\n }\n\n Ok(Some(BFFieldAttr {\n field_name: field_ident.clone(),\n name: name.unwrap(),\n ty: ty.unwrap(),\n bits: (bits.unwrap(), bits_span.unwrap()),\n }))\n}\n\nfn filter_and_parse_fields(field: &Field) -> Vec> {\n let attrs: Vec<_> = field\n .attrs\n .iter()\n .filter(|attr| attr.path.segments.last().unwrap().ident == \"bitfield\")\n .collect();\n\n if attrs.is_empty() {\n return Vec::new();\n }\n\n attrs\n .into_iter()\n .map(|attr| parse_bitfield_attr(attr, field.ident.as_ref().unwrap()))\n .flat_map(Result::transpose) // Remove the Ok(None) values\n .collect()\n}\n\nfn parse_bitfield_ty_path(field: &BFFieldAttr) -> Path {\n let leading_colon = if field.ty.starts_with(\"::\") {\n Some(Token![::]([\n Span::call_site().into(),\n Span::call_site().into(),\n ]))\n } else {\n None\n };\n\n let mut segments = Punctuated::new();\n let mut segment_strings = field.ty.split(\"::\").peekable();\n\n while let Some(segment_string) = segment_strings.next() {\n segments.push_value(PathSegment {\n ident: Ident::new(segment_string, Span::call_site().into()),\n arguments: PathArguments::None,\n });\n\n if segment_strings.peek().is_some() {\n segments.push_punct(Token![::]([\n Span::call_site().into(),\n Span::call_site().into(),\n ]));\n }\n }\n\n Path {\n leading_colon,\n segments,\n }\n}\n\n#[proc_macro_derive(BitfieldStruct, attributes(bitfield))]\npub fn bitfield_struct(input: TokenStream) -> TokenStream {\n let struct_item = parse_macro_input!(input as ItemStruct);\n\n match bitfield_struct_impl(struct_item) {\n Ok(ts) => ts,\n Err(error) => error.to_compile_error().into(),\n }\n}\n\nfn bitfield_struct_impl(struct_item: ItemStruct) -> Result {\n // REVIEW: Should we throw a compile error if bit ranges on a single field overlap?\n let struct_ident = struct_item.ident;\n let fields = match struct_item.fields {\n Fields::Named(named_fields) => named_fields.named,\n Fields::Unnamed(_) => {\n let err_str =\n \"Unnamed struct fields are not currently supported but may be in the future.\";\n let span = struct_ident.span();\n\n return Err(Error::new(span, err_str));\n }\n Fields::Unit => {\n let err_str = \"Cannot create bitfield struct out of struct with no fields\";\n let span = struct_ident.span();\n\n return Err(Error::new(span, err_str));\n }\n };\n let bitfields: Result, Error> =\n fields.iter().flat_map(filter_and_parse_fields).collect();\n let bitfields = bitfields?;\n let field_types: Vec<_> = bitfields.iter().map(parse_bitfield_ty_path).collect();\n let field_types_return = &field_types;\n let field_types_typedef = &field_types;\n let field_types_setter_arg = &field_types;\n let method_names: Vec<_> = bitfields\n .iter()\n .map(|field| Ident::new(&field.name, Span::call_site().into()))\n .collect();\n let field_names: Vec<_> = bitfields.iter().map(|field| &field.field_name).collect();\n let field_names_setters = &field_names;\n let field_names_getters = &field_names;\n let method_name_setters: Vec<_> = method_names\n .iter()\n .map(|field_ident| {\n let span = Span::call_site().into();\n let setter_name = &format!(\"set_{}\", field_ident);\n\n Ident::new(setter_name, span)\n })\n .collect();\n let field_bit_info: Result, Error> = bitfields\n .iter()\n .map(|field| {\n let bit_string = &field.bits.0;\n let nums: Vec<_> = bit_string.split(\"..=\").collect();\n let err_str = \"bits param must be in the format \\\"1..=4\\\"\";\n\n if nums.len() != 2 {\n return Err(Error::new(field.bits.1, err_str));\n }\n\n let lhs = nums[0].parse::();\n let rhs = nums[1].parse::();\n\n let (lhs, rhs) = match (lhs, rhs) {\n (Err(_), _) | (_, Err(_)) => return Err(Error::new(field.bits.1, err_str)),\n (Ok(lhs), Ok(rhs)) => (lhs, rhs),\n };\n\n Ok(quote! { (#lhs, #rhs) })\n })\n .collect();\n let field_bit_info = field_bit_info?;\n let field_bit_info_setters = &field_bit_info;\n let field_bit_info_getters = &field_bit_info;\n\n // TODO: Method visibility determined by struct field visibility?\n let q = quote! {\n #[automatically_derived]\n impl #struct_ident {\n #(\n /// This method allows you to write to a bitfield with a value\n pub fn #method_name_setters(&mut self, int: #field_types_setter_arg) {\n use c2rust_bitfields::FieldType;\n\n let field = &mut self.#field_names_setters;\n let (lhs_bit, rhs_bit) = #field_bit_info_setters;\n int.set_field(field, (lhs_bit, rhs_bit));\n }\n\n /// This method allows you to read from a bitfield to a value\n pub fn #method_names(&self) -> #field_types_return {\n use c2rust_bitfields::FieldType;\n\n type IntType = #field_types_typedef;\n\n let field = &self.#field_names_getters;\n let (lhs_bit, rhs_bit) = #field_bit_info_getters;\n ::get_field(field, (lhs_bit, rhs_bit))\n }\n )*\n }\n };\n\n Ok(q.into())\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2956,"cells":{"blob_id":{"kind":"string","value":"b8df6ae8e4de33703de889d4f76f010bd7c789e5"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"stkfd/rd-histogram"},"path":{"kind":"string","value":"/src/simple_vec_histogram.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6022,"string":"6,022"},"score":{"kind":"number","value":3.125,"string":"3.125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use num::traits::NumAssign;\nuse ord_subset::{OrdSubset, OrdSubsetIterExt, OrdSubsetSliceExt};\nuse std::cmp::Ordering;\nuse traits::{DynamicHistogram, EmptyClone, Merge, MergeRef};\n\n#[derive(Clone, Debug, PartialEq)]\npub struct SimpleVecHistogram {\n bins: Vec>,\n bins_cap: usize,\n}\n\n#[derive(Clone, Debug, PartialEq)]\npub struct Bin {\n left: V,\n right: V,\n count: C,\n sum: V,\n}\n\nimpl\n SimpleVecHistogram\n{\n fn search_bins(&self, value: V) -> Result {\n self.bins.binary_search_by(|probe| {\n if probe.left <= value && probe.right > value {\n Ordering::Equal\n } else if probe.left > value {\n Ordering::Greater\n } else {\n Ordering::Less\n }\n })\n }\n\n fn shrink_to_fit(&mut self) {\n while self.bins.len() > self.bins_cap {\n let merge_result = self\n .bins\n .iter()\n .zip(self.bins.iter().skip(1))\n .enumerate()\n .map(|(i, (bin, next_bin))| {\n // calculate distances between bins\n (i, bin, next_bin, next_bin.left - bin.right)\n })\n .ord_subset_min_by_key(|(_i, _bin, _next_bin, distance)| *distance)\n .map(|(i, bin, next_bin, _)| {\n let merged_bin = Bin {\n left: bin.left,\n right: next_bin.right,\n sum: bin.sum + next_bin.sum,\n count: bin.count + next_bin.count,\n };\n (i, merged_bin)\n });\n\n if let Some((i, merged_bin)) = merge_result {\n self.bins[i] = merged_bin;\n self.bins.remove(i + 1);\n }\n }\n }\n\n fn bins(&self) -> &[Bin] {\n self.bins.as_slice()\n }\n}\n\nimpl>\n DynamicHistogram for SimpleVecHistogram\n{\n /// Type of a bin in this histogram\n type Bin = Bin;\n\n /// Instantiate a histogram with the given number of maximum bins\n fn new(n_bins: usize) -> Self {\n SimpleVecHistogram {\n bins: Vec::with_capacity(n_bins),\n bins_cap: n_bins,\n }\n }\n\n /// Insert a new data point into this histogram\n fn insert(&mut self, value: V, count: C) {\n let search_result = self.search_bins(value);\n\n match search_result {\n Ok(found) => {\n self.bins[found].count += count;\n self.bins[found].sum += value * count.into();\n }\n Err(insert_at) => self.bins.insert(\n insert_at,\n Bin {\n left: value,\n right: value,\n count,\n sum: value * count.into(),\n },\n ),\n }\n\n self.shrink_to_fit();\n }\n\n /// Count the total number of data points in this histogram (over all bins)\n fn count(&self) -> C {\n unimplemented!()\n }\n}\n\nimpl> EmptyClone\n for SimpleVecHistogram\n{\n fn empty_clone(&self) -> Self {\n SimpleVecHistogram::new(self.bins_cap)\n }\n}\n\nimpl> MergeRef\n for SimpleVecHistogram\n{\n fn merge_ref(&mut self, other: &Self) {\n self.bins.extend_from_slice(other.bins());\n self.bins.ord_subset_sort_by_key(|b| b.left);\n self.shrink_to_fit();\n }\n}\n\nimpl> Merge\n for SimpleVecHistogram\n{\n fn merge(&mut self, other: Self) {\n self.bins.extend(other.bins.into_iter());\n self.bins.ord_subset_sort_by_key(|b| b.left);\n self.shrink_to_fit();\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn insert() {\n // fill with the maximum bin number\n let mut h = SimpleVecHistogram::new(5);\n let samples: &[(f64, u32)] = &[(1., 1), (2., 1), (3., 1), (4., 1), (5., 1)];\n h.insert_iter(samples);\n\n for (bin, s) in h.bins().iter().zip(samples.iter()) {\n assert_eq!(s.0, bin.left);\n assert_eq!(s.0, bin.right);\n }\n // checks merging the closest two bins\n h.insert(5.5, 2);\n assert_eq!(\n h.bins()[4],\n Bin {\n left: 5.,\n right: 5.5,\n count: 3,\n sum: 16.\n }\n );\n // checks inserting into an existing bin\n h.insert(5.2, 1);\n assert_eq!(\n h.bins()[4],\n Bin {\n left: 5.,\n right: 5.5,\n count: 4,\n sum: 21.2\n }\n );\n }\n\n #[test]\n fn merge() {\n // fill with the maximum bin number\n let samples1: &[(f64, u32)] = &[(1., 1), (2., 1), (3., 1), (4., 1), (5., 1)];\n let samples2: &[(f64, u32)] = &[(1.1, 1), (2.1, 1), (3.1, 1), (4.1, 1), (5.1, 1)];\n\n let mut h = SimpleVecHistogram::new(5);\n h.insert_iter(samples1);\n println!(\"{:?}\", h);\n\n let mut h2 = SimpleVecHistogram::new(5);\n h2.insert_iter(samples2);\n println!(\"{:?}\", h2);\n\n h.merge(h2);\n println!(\"{:?}\", h);\n assert_eq!(h.bins().len(), 5);\n assert_eq!(\n h.bins()[2],\n Bin {\n left: 3.,\n right: 3.1,\n count: 2,\n sum: 6.1\n }\n );\n assert_eq!(\n h.bins()[4],\n Bin {\n left: 5.,\n right: 5.1,\n count: 2,\n sum: 10.1\n }\n );\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2957,"cells":{"blob_id":{"kind":"string","value":"c0563791dd9ae4d6ca09b42b63a69f0273affb6d"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"emakryo/cmpro"},"path":{"kind":"string","value":"/src/abc221/src/bin/c.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":885,"string":"885"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#![allow(unused_macros, unused_imports)]\n\nuse proconio::marker::Bytes;\nmacro_rules! dbg {\n ($($xs:expr),+) => {\n if cfg!(debug_assertions) {\n std::dbg!($($xs),+)\n } else {\n ($($xs),+)\n }\n }\n}\n\nfn main() {\n proconio::input!{\n n: Bytes,\n }\n\n let m = n.len();\n let mut cs = n.into_iter().map(|c| (c - b'0') as u64).collect::>();\n cs.sort();\n cs.reverse();\n\n let mut a = 0;\n let mut b = 0;\n\n for i in 0..m/2 {\n let c = cs[2*i];\n let d = cs[2*i+1];\n // d <= c\n\n if a <= b {\n a = 10*a + c;\n b = 10*b + d;\n } else {\n a = 10*a + d;\n b = 10*b + c;\n }\n }\n\n if m%2==1 {\n if a <= b {\n a = 10*a + cs[m-1];\n } else {\n b = 10*b + cs[m-1];\n }\n }\n\n println!(\"{}\", a*b);\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2958,"cells":{"blob_id":{"kind":"string","value":"134d79f3059cc8fda9706ba4154a79fba04014db"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"b-ramsey/cargo-generate"},"path":{"kind":"string","value":"/src/git.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":886,"string":"886"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0","MIT","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"Apache-2.0\",\n \"MIT\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use git2::{\n build::CheckoutBuilder, build::RepoBuilder, Repository as GitRepository, RepositoryInitOptions,\n};\nuse quicli::prelude::*;\nuse remove_dir_all::remove_dir_all;\nuse std::path::PathBuf;\nuse Args;\n\npub fn create(project_dir: &PathBuf, args: Args) -> Result {\n let mut rb = RepoBuilder::new();\n rb.bare(false).with_checkout(CheckoutBuilder::new());\n\n if let Some(ref branch) = args.branch {\n rb.branch(branch);\n }\n\n Ok(rb.clone(&args.git, &project_dir)?)\n}\n\npub fn remove_history(project_dir: &PathBuf) -> Result<()> {\n Ok(remove_dir_all(project_dir.join(\".git\")).context(\"Error cleaning up cloned template\")?)\n}\n\npub fn init(project_dir: &PathBuf) -> Result {\n Ok(\n GitRepository::init_opts(project_dir, RepositoryInitOptions::new().bare(false))\n .context(\"Couldn't init new repository\")?,\n )\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2959,"cells":{"blob_id":{"kind":"string","value":"d63faa075580a490542c4c763c335b56e8df9877"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"racer-rust/racer"},"path":{"kind":"string","value":"/src/racer/codecleaner.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":14591,"string":"14,591"},"score":{"kind":"number","value":3.5,"string":"3.5"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use crate::core::{BytePos, ByteRange};\n\n/// Type of the string\n#[derive(Clone, Copy, Debug)]\nenum StrStyle {\n /// normal string starts with \"\n Cooked,\n /// Raw(n) => raw string started with n #s\n Raw(usize),\n}\n\n#[derive(Clone, Copy)]\nenum State {\n Code,\n Comment,\n CommentBlock,\n String(StrStyle),\n Char,\n Finished,\n}\n\n#[derive(Clone, Copy)]\npub struct CodeIndicesIter<'a> {\n src: &'a str,\n pos: BytePos,\n state: State,\n}\n\nimpl<'a> Iterator for CodeIndicesIter<'a> {\n type Item = ByteRange;\n\n fn next(&mut self) -> Option {\n match self.state {\n State::Code => Some(self.code()),\n State::Comment => Some(self.comment()),\n State::CommentBlock => Some(self.comment_block()),\n State::String(style) => Some(self.string(style)),\n State::Char => Some(self.char()),\n State::Finished => None,\n }\n }\n}\n\nimpl<'a> CodeIndicesIter<'a> {\n fn code(&mut self) -> ByteRange {\n let mut pos = self.pos;\n let start = match self.state {\n State::String(_) | State::Char => pos.decrement(), // include quote\n _ => pos,\n };\n let src_bytes = self.src.as_bytes();\n for &b in &src_bytes[pos.0..] {\n pos = pos.increment();\n match b {\n b'/' if src_bytes.len() > pos.0 => match src_bytes[pos.0] {\n b'/' => {\n self.state = State::Comment;\n self.pos = pos.increment();\n return ByteRange::new(start, pos.decrement());\n }\n b'*' => {\n self.state = State::CommentBlock;\n self.pos = pos.increment();\n return ByteRange::new(start, pos.decrement());\n }\n _ => {}\n },\n b'\"' => {\n // \"\n let str_type = self.detect_str_type(pos);\n self.state = State::String(str_type);\n self.pos = pos;\n return ByteRange::new(start, pos); // include dblquotes\n }\n b'\\'' => {\n // single quotes are also used for lifetimes, so we need to\n // be confident that this is not a lifetime.\n // Look for backslash starting the escape, or a closing quote:\n if src_bytes.len() > pos.increment().0\n && (src_bytes[pos.0] == b'\\\\' || src_bytes[pos.increment().0] == b'\\'')\n {\n self.state = State::Char;\n self.pos = pos;\n return ByteRange::new(start, pos); // include single quote\n }\n }\n _ => {}\n }\n }\n\n self.state = State::Finished;\n ByteRange::new(start, self.src.len().into())\n }\n\n fn comment(&mut self) -> ByteRange {\n let mut pos = self.pos;\n let src_bytes = self.src.as_bytes();\n for &b in &src_bytes[pos.0..] {\n pos = pos.increment();\n if b == b'\\n' {\n if pos.0 + 2 <= src_bytes.len() && src_bytes[pos.0..pos.0 + 2] == [b'/', b'/'] {\n continue;\n }\n break;\n }\n }\n self.pos = pos;\n self.code()\n }\n\n fn comment_block(&mut self) -> ByteRange {\n let mut nesting_level = 0usize;\n let mut prev = b' ';\n let mut pos = self.pos;\n for &b in &self.src.as_bytes()[pos.0..] {\n pos = pos.increment();\n match b {\n b'/' if prev == b'*' => {\n prev = b' ';\n if nesting_level == 0 {\n break;\n } else {\n nesting_level -= 1;\n }\n }\n b'*' if prev == b'/' => {\n prev = b' ';\n nesting_level += 1;\n }\n _ => {\n prev = b;\n }\n }\n }\n self.pos = pos;\n self.code()\n }\n\n fn string(&mut self, str_type: StrStyle) -> ByteRange {\n let src_bytes = self.src.as_bytes();\n let mut pos = self.pos;\n match str_type {\n StrStyle::Raw(level) => {\n // raw string (e.g. br#\"\\\"#)\n #[derive(Debug)]\n enum SharpState {\n Sharp {\n // number of preceding #s\n num_sharps: usize,\n // Position of last \"\n quote_pos: BytePos,\n },\n None, // No preceding \"##...\n }\n let mut cur_state = SharpState::None;\n let mut end_was_found = false;\n // detect corresponding end(if start is r##\", \"##) greedily\n for (i, &b) in src_bytes[self.pos.0..].iter().enumerate() {\n match cur_state {\n SharpState::Sharp {\n num_sharps,\n quote_pos,\n } => {\n cur_state = match b {\n b'#' => SharpState::Sharp {\n num_sharps: num_sharps + 1,\n quote_pos,\n },\n b'\"' => SharpState::Sharp {\n num_sharps: 0,\n quote_pos: BytePos(i),\n },\n _ => SharpState::None,\n }\n }\n SharpState::None => {\n if b == b'\"' {\n cur_state = SharpState::Sharp {\n num_sharps: 0,\n quote_pos: BytePos(i),\n };\n }\n }\n }\n if let SharpState::Sharp {\n num_sharps,\n quote_pos,\n } = cur_state\n {\n if num_sharps == level {\n end_was_found = true;\n pos += quote_pos.increment();\n break;\n }\n }\n }\n if !end_was_found {\n pos = src_bytes.len().into();\n }\n }\n StrStyle::Cooked => {\n let mut is_not_escaped = true;\n for &b in &src_bytes[pos.0..] {\n pos = pos.increment();\n match b {\n b'\"' if is_not_escaped => {\n break;\n } // \"\n b'\\\\' => {\n is_not_escaped = !is_not_escaped;\n }\n _ => {\n is_not_escaped = true;\n }\n }\n }\n }\n };\n self.pos = pos;\n self.code()\n }\n\n fn char(&mut self) -> ByteRange {\n let mut is_not_escaped = true;\n let mut pos = self.pos;\n for &b in &self.src.as_bytes()[pos.0..] {\n pos = pos.increment();\n match b {\n b'\\'' if is_not_escaped => {\n break;\n }\n b'\\\\' => {\n is_not_escaped = !is_not_escaped;\n }\n _ => {\n is_not_escaped = true;\n }\n }\n }\n self.pos = pos;\n self.code()\n }\n\n fn detect_str_type(&self, pos: BytePos) -> StrStyle {\n let src_bytes = self.src.as_bytes();\n let mut sharp = 0;\n if pos == BytePos::ZERO {\n return StrStyle::Cooked;\n }\n // now pos is at one byte after \", so we have to start at pos - 2\n for &b in src_bytes[..pos.decrement().0].iter().rev() {\n match b {\n b'#' => sharp += 1,\n b'r' => return StrStyle::Raw(sharp),\n _ => return StrStyle::Cooked,\n }\n }\n StrStyle::Cooked\n }\n}\n\n/// Returns indices of chunks of code (minus comments and string contents)\npub fn code_chunks(src: &str) -> CodeIndicesIter<'_> {\n CodeIndicesIter {\n src,\n state: State::Code,\n pos: BytePos::ZERO,\n }\n}\n\n#[cfg(test)]\nmod code_indices_iter_test {\n use super::*;\n use crate::testutils::{rejustify, slice};\n\n #[test]\n fn removes_a_comment() {\n let src = &rejustify(\n \"\n this is some code // this is a comment\n some more code\n \",\n );\n let mut it = code_chunks(src);\n assert_eq!(\"this is some code \", slice(src, it.next().unwrap()));\n assert_eq!(\"some more code\", slice(src, it.next().unwrap()));\n }\n\n #[test]\n fn removes_consecutive_comments() {\n let src = &rejustify(\n \"\n this is some code // this is a comment\n // this is more comment\n // another comment\n some more code\n \",\n );\n let mut it = code_chunks(src);\n assert_eq!(\"this is some code \", slice(src, it.next().unwrap()));\n assert_eq!(\"some more code\", slice(src, it.next().unwrap()));\n }\n\n #[test]\n fn removes_string_contents() {\n let src = &rejustify(\n \"\n this is some code \\\"this is a string\\\" more code\n \",\n );\n let mut it = code_chunks(src);\n assert_eq!(\"this is some code \\\"\", slice(src, it.next().unwrap()));\n assert_eq!(\"\\\" more code\", slice(src, it.next().unwrap()));\n }\n\n #[test]\n fn removes_char_contents() {\n let src = &rejustify(\n \"\n this is some code \\'\\\"\\' more code \\'\\\\x00\\' and \\'\\\\\\'\\' that\\'s it\n \",\n );\n let mut it = code_chunks(src);\n assert_eq!(\"this is some code \\'\", slice(src, it.next().unwrap()));\n assert_eq!(\"\\' more code \\'\", slice(src, it.next().unwrap()));\n assert_eq!(\"\\' and \\'\", slice(src, it.next().unwrap()));\n assert_eq!(\"\\' that\\'s it\", slice(src, it.next().unwrap()));\n }\n\n #[test]\n fn removes_string_contents_with_a_comment_in_it() {\n let src = &rejustify(\n \"\n this is some code \\\"string with a // fake comment \\\" more code\n \",\n );\n let mut it = code_chunks(src);\n assert_eq!(\"this is some code \\\"\", slice(src, it.next().unwrap()));\n assert_eq!(\"\\\" more code\", slice(src, it.next().unwrap()));\n }\n\n #[test]\n fn removes_a_comment_with_a_dbl_quote_in_it() {\n let src = &rejustify(\n \"\n this is some code // comment with \\\" double quote\n some more code\n \",\n );\n let mut it = code_chunks(src);\n assert_eq!(\"this is some code \", slice(src, it.next().unwrap()));\n assert_eq!(\"some more code\", slice(src, it.next().unwrap()));\n }\n\n #[test]\n fn removes_multiline_comment() {\n let src = &rejustify(\n \"\n this is some code /* this is a\n \\\"multiline\\\" comment */some more code\n \",\n );\n let mut it = code_chunks(src);\n assert_eq!(\"this is some code \", slice(src, it.next().unwrap()));\n assert_eq!(\"some more code\", slice(src, it.next().unwrap()));\n }\n\n #[test]\n fn handles_nesting_of_block_comments() {\n let src = &rejustify(\n \"\n this is some code /* nested /* block */ comment */ some more code\n \",\n );\n let mut it = code_chunks(src);\n assert_eq!(\"this is some code \", slice(src, it.next().unwrap()));\n assert_eq!(\" some more code\", slice(src, it.next().unwrap()));\n }\n\n #[test]\n fn handles_documentation_block_comments_nested_into_block_comments() {\n let src = &rejustify(\n \"\n this is some code /* nested /** documentation block */ comment */ some more code\n \",\n );\n let mut it = code_chunks(src);\n assert_eq!(\"this is some code \", slice(src, it.next().unwrap()));\n assert_eq!(\" some more code\", slice(src, it.next().unwrap()));\n }\n\n #[test]\n fn removes_string_with_escaped_dblquote_in_it() {\n let src = &rejustify(\n \"\n this is some code \\\"string with a \\\\\\\" escaped dblquote fake comment \\\" more code\n \",\n );\n\n let mut it = code_chunks(src);\n assert_eq!(\"this is some code \\\"\", slice(src, it.next().unwrap()));\n assert_eq!(\"\\\" more code\", slice(src, it.next().unwrap()));\n }\n\n #[test]\n fn removes_raw_string_with_dangling_escape_in_it() {\n let src = &rejustify(\n \"\n this is some code br\\\" escaped dblquote raw string \\\\\\\" more code\n \",\n );\n\n let mut it = code_chunks(src);\n assert_eq!(\"this is some code br\\\"\", slice(src, it.next().unwrap()));\n assert_eq!(\"\\\" more code\", slice(src, it.next().unwrap()));\n }\n\n #[test]\n fn removes_string_with_escaped_slash_before_dblquote_in_it() {\n let src = &rejustify(\"\n this is some code \\\"string with an escaped slash, so dbl quote does end the string after all \\\\\\\\\\\" more code\n \");\n\n let mut it = code_chunks(src);\n assert_eq!(\"this is some code \\\"\", slice(src, it.next().unwrap()));\n assert_eq!(\"\\\" more code\", slice(src, it.next().unwrap()));\n }\n\n #[test]\n fn handles_tricky_bit_from_str_rs() {\n let src = &rejustify(\n \"\n before(\\\"\\\\\\\\\\'\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\");\n more_code(\\\" skip me \\\")\n \",\n );\n\n for range in code_chunks(src) {\n let range = || range.to_range();\n println!(\"BLOB |{}|\", &src[range()]);\n if src[range()].contains(\"skip me\") {\n panic!(\"{}\", &src[range()]);\n }\n }\n }\n\n #[test]\n fn removes_nested_rawstr() {\n let src = &rejustify(\n r####\"\n this is some code br###\"\"\" r##\"\"##\"### more code\n \"####,\n );\n\n let mut it = code_chunks(src);\n assert_eq!(\"this is some code br###\\\"\", slice(src, it.next().unwrap()));\n assert_eq!(\"\\\"### more code\", slice(src, it.next().unwrap()));\n }\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2960,"cells":{"blob_id":{"kind":"string","value":"3f25a94579101de7158a4a0e2f469e40937aa5cd"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Aloso/parkour"},"path":{"kind":"string","value":"/src/error.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":9015,"string":"9,015"},"score":{"kind":"number","value":3.71875,"string":"3.71875"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["MIT","Apache-2.0"],"string":"[\n \"MIT\",\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use std::fmt;\nuse std::num::{ParseFloatError, ParseIntError};\n\nuse crate::help::PossibleValues;\nuse crate::util::Flag;\n\n/// The error type when parsing command-line arguments. You can create an\n/// `Error` by creating an `ErrorInner` and converting it with `.into()`.\n///\n/// This error type supports an error source for attaching context to the error.\n#[derive(Debug)]\npub struct Error {\n inner: ErrorInner,\n source: Option>,\n}\n\nimpl Error {\n /// Attach context to the error. Note that this overwrites the current\n /// source, if there is one.\n ///\n /// ### Usage\n ///\n /// ```\n /// use parkour::{Error, util::Flag};\n ///\n /// Error::missing_value()\n /// .with_source(Error::in_subcommand(\"test\"))\n /// # ;\n /// ```\n ///\n /// This could produce the following output:\n /// ```text\n /// missing value\n /// source: in subcommand `test`\n /// ```\n pub fn with_source(\n self,\n source: impl std::error::Error + Sync + Send + 'static,\n ) -> Self {\n Error { source: Some(Box::new(source)), ..self }\n }\n\n /// Attach context to the error. This function ensures that an already\n /// attached source isn't discarded, but appended to the the new source. The\n /// sources therefore form a singly linked list.\n ///\n /// ### Usage\n ///\n /// ```\n /// use parkour::{Error, ErrorInner, util::Flag};\n ///\n /// Error::missing_value()\n /// .chain(ErrorInner::IncompleteValue(1))\n /// # ;\n /// ```\n pub fn chain(mut self, source: ErrorInner) -> Self {\n let mut new = Self::from(source);\n new.source = self.source.take();\n Error { source: Some(Box::new(new)), ..self }\n }\n\n /// Create a `NoValue` error\n pub fn no_value() -> Self {\n ErrorInner::NoValue.into()\n }\n\n /// Returns `true` if this is a `NoValue` error\n pub fn is_no_value(&self) -> bool {\n matches!(self.inner, ErrorInner::NoValue)\n }\n\n /// Create a `MissingValue` error\n pub fn missing_value() -> Self {\n ErrorInner::MissingValue.into()\n }\n\n /// Returns the [`ErrorInner`] of this error\n pub fn inner(&self) -> &ErrorInner {\n &self.inner\n }\n\n /// Create a `EarlyExit` error\n pub fn early_exit() -> Self {\n ErrorInner::EarlyExit.into()\n }\n\n /// Returns `true` if this is a `EarlyExit` error\n pub fn is_early_exit(&self) -> bool {\n matches!(self.inner, ErrorInner::EarlyExit)\n }\n\n /// Create a `UnexpectedValue` error\n pub fn unexpected_value(\n got: impl ToString,\n expected: Option,\n ) -> Self {\n ErrorInner::InvalidValue { got: got.to_string(), expected }.into()\n }\n\n /// Create a `MissingArgument` error\n pub fn missing_argument(arg: impl ToString) -> Self {\n ErrorInner::MissingArgument { arg: arg.to_string() }.into()\n }\n\n /// Create a `InArgument` error\n pub fn in_argument(flag: &Flag) -> Self {\n ErrorInner::InArgument(flag.first_to_string()).into()\n }\n\n /// Create a `InSubcommand` error\n pub fn in_subcommand(cmd: impl ToString) -> Self {\n ErrorInner::InSubcommand(cmd.to_string()).into()\n }\n\n /// Create a `TooManyArgOccurrences` error\n pub fn too_many_arg_occurrences(arg: impl ToString, max: Option) -> Self {\n ErrorInner::TooManyArgOccurrences { arg: arg.to_string(), max }.into()\n }\n}\n\nimpl From for Error {\n fn from(inner: ErrorInner) -> Self {\n Error { inner, source: None }\n }\n}\n\n/// The error type when parsing command-line arguments\n#[derive(Debug, PartialEq)]\npub enum ErrorInner {\n /// The argument you tried to parse wasn't present at the current position.\n /// Has a similar purpose as `Option::None`\n NoValue,\n\n /// The argument you tried to parse wasn't present at the current position,\n /// but was required\n MissingValue,\n\n /// The argument you tried to parse was only partly present\n IncompleteValue(usize),\n\n /// Used when an argument should abort argument parsing, like --help\n EarlyExit,\n\n /// Indicates that the error originated in the specified argument. This\n /// should be used as the source for another error\n InArgument(String),\n\n /// Indicates that the error originated in the specified subcommand. This\n /// should be used as the source for another error\n InSubcommand(String),\n\n /// The parsed value doesn't meet our expectations\n InvalidValue {\n /// The value we tried to parse\n got: String,\n /// The expectation that was violated. For example, this string can\n /// contain a list of accepted values.\n expected: Option,\n },\n\n /// The parsed list contains more items than allowed\n TooManyValues {\n /// The maximum number of items\n max: usize,\n /// The number of items that was parsed\n count: usize,\n },\n\n /// The parsed array has the wrong length\n WrongNumberOfValues {\n /// The length of the array\n expected: usize,\n /// The number of items that was parsed\n got: usize,\n },\n\n /// A required argument was not provided\n MissingArgument {\n /// The name of the argument that is missing\n arg: String,\n },\n\n /// An unknown argument was provided\n UnexpectedArgument {\n /// The (full) argument that wasn't expected\n arg: String,\n },\n\n /// The argument has a value, but no value was expected\n UnexpectedValue {\n /// The value of the argument\n value: String,\n },\n\n /// An argument was provided more often than allowed\n TooManyArgOccurrences {\n /// The name of the argument that was provided too many times\n arg: String,\n /// The maximum number of times the argument may be provided\n max: Option,\n },\n\n /// Parsing an integer failed\n ParseIntError(ParseIntError),\n\n /// Parsing a floating-point number failed\n ParseFloatError(ParseFloatError),\n}\n\nimpl From for Error {\n fn from(e: ParseIntError) -> Self {\n ErrorInner::ParseIntError(e).into()\n }\n}\nimpl From for Error {\n fn from(e: ParseFloatError) -> Self {\n ErrorInner::ParseFloatError(e).into()\n }\n}\n\nimpl std::error::Error for Error {\n fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n match &self.source {\n Some(source) => Some(&**source as &(dyn std::error::Error + 'static)),\n None => None,\n }\n }\n}\n\nimpl fmt::Display for Error {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n match &self.inner {\n ErrorInner::NoValue => write!(f, \"no value\"),\n ErrorInner::MissingValue => write!(f, \"missing value\"),\n ErrorInner::IncompleteValue(part) => {\n write!(f, \"missing part {} of value\", part)\n }\n ErrorInner::EarlyExit => write!(f, \"early exit\"),\n ErrorInner::InArgument(opt) => write!(f, \"in `{}`\", opt.escape_debug()),\n ErrorInner::InSubcommand(cmd) => {\n write!(f, \"in subcommand {}\", cmd.escape_debug())\n }\n ErrorInner::InvalidValue { expected, got } => {\n if let Some(expected) = expected {\n write!(\n f,\n \"unexpected value `{}`, expected {}\",\n got.escape_debug(),\n expected,\n )\n } else {\n write!(f, \"unexpected value `{}`\", got.escape_debug())\n }\n }\n ErrorInner::UnexpectedArgument { arg } => {\n write!(f, \"unexpected argument `{}`\", arg.escape_debug())\n }\n ErrorInner::UnexpectedValue { value } => {\n write!(f, \"unexpected value `{}`\", value.escape_debug())\n }\n ErrorInner::TooManyValues { max, count } => {\n write!(f, \"too many values, expected at most {}, got {}\", max, count)\n }\n ErrorInner::WrongNumberOfValues { expected, got } => {\n write!(f, \"wrong number of values, expected {}, got {}\", expected, got)\n }\n ErrorInner::MissingArgument { arg } => {\n write!(f, \"required {} was not provided\", arg)\n }\n ErrorInner::TooManyArgOccurrences { arg, max } => {\n if let Some(max) = max {\n write!(\n f,\n \"{} was used too often, it can be used at most {} times\",\n arg, max\n )\n } else {\n write!(f, \"{} was used too often\", arg)\n }\n }\n\n ErrorInner::ParseIntError(e) => write!(f, \"{}\", e),\n ErrorInner::ParseFloatError(e) => write!(f, \"{}\", e),\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2961,"cells":{"blob_id":{"kind":"string","value":"3abb46cea2b60c54f13e04b08078c306026a654a"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"philipcraig/mylang"},"path":{"kind":"string","value":"/src/frame.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8295,"string":"8,295"},"score":{"kind":"number","value":3.5625,"string":"3.5625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use crate::ast::{BinaryOp, Expression, Function, OpName, Statement, UnaryOp};\nuse std::{collections::HashMap, fmt, rc::Rc};\nuse thiserror::Error;\n\n#[derive(Debug, PartialEq)]\npub enum Value {\n Boolean(bool),\n Float(f64),\n Function(Rc),\n Integer(i32),\n String(Rc),\n}\n\nimpl fmt::Display for Value {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n match self {\n Value::Boolean(b) => write!(f, \"Boolean({})\", b),\n Value::Float(float) => write!(f, \"Float({})\", float),\n Value::Function(_) => write!(f, \"Function()\"),\n Value::Integer(i) => write!(f, \"Integer({})\", i),\n Value::String(s) => write!(f, \"String({})\", s),\n }\n }\n}\n\n#[derive(Error, Debug, PartialEq)]\npub enum EvaluationError {\n #[error(\"Evaluation requested on unknown identifier `{0}`\")]\n UnknownIdentifier(String),\n #[error(\"Called on {0}, which is not a callable type\")]\n NonCallableType(String),\n #[error(\"Mismatch in argument count for Function {name:?}. Expected {expected:?} arguments but got {got:?}\")]\n ArgumentCountMismatch {\n name: String,\n expected: usize,\n got: usize,\n },\n #[error(\"Function {0} didn't return a value\")]\n NoReturnValue(String),\n #[error(\"Can't apply a unary operation {opname:?} to {value:?}\")]\n IllegalUnaryOperation { opname: String, value: String },\n #[error(\"Can't apply binary operation {opname:?} to {left:?} {right:?}\")]\n IllegalBinaryOperation {\n opname: String,\n left: String,\n right: String,\n },\n}\n\npub struct Frame {\n values: HashMap>,\n}\n\nimpl Frame {\n pub(crate) fn new() -> Self {\n Self {\n values: HashMap::new(),\n }\n }\n\n pub(crate) fn evaluate_body(\n &mut self,\n body: &[Statement],\n ) -> Result>, EvaluationError> {\n for statement in body {\n if let Some(v) = self.evaluate_statement(statement)? {\n return Ok(Some(v));\n }\n }\n Ok(None)\n }\n\n fn evaluate_expression(&self, expression: &Expression) -> Result, EvaluationError> {\n match expression {\n Expression::Boolean(b) => Ok(Rc::new(Value::Boolean(*b))),\n Expression::Float(f) => Ok(Rc::new(Value::Float(*f))),\n Expression::Function(function) => Ok(Rc::new(Value::Function(function.clone()))),\n Expression::Integer(i) => Ok(Rc::new(Value::Integer(*i))),\n Expression::StringLiteral(s) => Ok(Rc::new(Value::String(s.clone()))),\n Expression::Identifier(identifier) => self.values.get(identifier).map_or_else(\n || Err(EvaluationError::UnknownIdentifier(identifier.to_string())),\n |value| Ok(Rc::clone(value)),\n ),\n Expression::Call(call) => {\n if let Some(value) = self.values.get(&call.name) {\n match &**value {\n Value::Boolean(_)\n | Value::Float(_)\n | Value::Integer(_)\n | Value::String(_) => {\n Err(EvaluationError::NonCallableType((**value).to_string()))\n }\n Value::Function(function) => {\n if function.arguments.len() == call.arguments.len() {\n let mut function_frame = Self::new();\n for (arg_name, arg_expression) in\n function.arguments.iter().zip(call.arguments.iter())\n {\n let argument_value =\n self.evaluate_expression(arg_expression)?;\n function_frame\n .values\n .insert(arg_name.clone(), argument_value);\n }\n (function_frame.evaluate_body(&function.body)?).map_or_else(\n || Err(EvaluationError::NoReturnValue(call.name.clone())),\n |return_value| Ok(Rc::clone(&return_value)),\n )\n } else {\n Err(EvaluationError::ArgumentCountMismatch {\n name: call.name.clone(),\n expected: function.arguments.len(),\n got: call.arguments.len(),\n })\n }\n }\n }\n } else {\n Err(EvaluationError::UnknownIdentifier(call.name.clone()))\n }\n }\n Expression::UnaryOp(op) => self.evaluate_unary_op(op),\n Expression::BinaryOp(op) => self.evaluate_binary_op(op),\n }\n }\n\n fn evaluate_statement(\n &mut self,\n statement: &Statement,\n ) -> Result>, EvaluationError> {\n match &statement {\n Statement::Let(let_statement) => {\n let value = self.evaluate_expression(&let_statement.expression)?;\n self.values.insert(let_statement.identifier.clone(), value);\n Ok(None)\n }\n Statement::Return(return_statement) => {\n Ok(Some(self.evaluate_expression(return_statement)?))\n }\n Statement::Expression(expression) => {\n let _value = self.evaluate_expression(expression);\n // TODO: Print _value to the console if we're in a REPL.\n Ok(None)\n }\n }\n }\n\n fn evaluate_unary_op(&self, op: &UnaryOp) -> Result, EvaluationError> {\n let target = self.evaluate_expression(&op.target)?;\n match (&*target, &op.operation) {\n (Value::Float(_) | Value::Integer(_), OpName::Plus) => Ok(target.clone()),\n (Value::Float(f), OpName::Minus) => Ok(Rc::new(Value::Float(-f))),\n (Value::Integer(i), OpName::Minus) => Ok(Rc::new(Value::Integer(-i))),\n (\n Value::Boolean(_)\n | Value::Function(_)\n | Value::String(_)\n | Value::Float(_)\n | Value::Integer(_),\n _,\n ) => Err(EvaluationError::IllegalUnaryOperation {\n opname: op.operation.to_string(),\n value: (*target).to_string(),\n }),\n }\n }\n\n fn evaluate_binary_op(&self, op: &BinaryOp) -> Result, EvaluationError> {\n let left = self.evaluate_expression(&op.left)?;\n let right = self.evaluate_expression(&op.right)?;\n match (&op.operation, &*left, &*right) {\n (OpName::Plus, &Value::Integer(lhs), &Value::Integer(rhs)) => {\n Ok(Rc::new(Value::Integer(lhs + rhs)))\n }\n (OpName::Minus, &Value::Integer(lhs), &Value::Integer(rhs)) => {\n Ok(Rc::new(Value::Integer(lhs - rhs)))\n }\n (OpName::Divide, &Value::Integer(lhs), &Value::Integer(rhs)) => {\n Ok(Rc::new(Value::Integer(lhs / rhs)))\n }\n (OpName::Multiply, &Value::Integer(lhs), &Value::Integer(rhs)) => {\n Ok(Rc::new(Value::Integer(lhs * rhs)))\n }\n (OpName::Plus, &Value::Float(lhs), &Value::Float(rhs)) => {\n Ok(Rc::new(Value::Float(lhs + rhs)))\n }\n (OpName::Minus, &Value::Float(lhs), &Value::Float(rhs)) => {\n Ok(Rc::new(Value::Float(lhs - rhs)))\n }\n (OpName::Divide, &Value::Float(lhs), &Value::Float(rhs)) => {\n Ok(Rc::new(Value::Float(lhs / rhs)))\n }\n (OpName::Multiply, &Value::Float(lhs), &Value::Float(rhs)) => {\n Ok(Rc::new(Value::Float(lhs * rhs)))\n }\n _ => Err(EvaluationError::IllegalBinaryOperation {\n opname: op.operation.to_string(),\n left: left.to_string(),\n right: right.to_string(),\n }),\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2962,"cells":{"blob_id":{"kind":"string","value":"9f6d6cab3295d329c4a4e91d8b2012c420e076ed"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"tatetian/ngo2"},"path":{"kind":"string","value":"/src/libos/src/entry/context_switch/gp_regs.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1147,"string":"1,147"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use crate::prelude::*;\n\n/// The general-purpose registers of CPU.\n///\n/// Note. The Rust definition of this struct must be kept in sync with assembly code.\n#[derive(Clone, Copy, Debug, Default)]\n#[repr(C)]\npub struct GpRegs {\n pub r8: u64,\n pub r9: u64,\n pub r10: u64,\n pub r11: u64,\n pub r12: u64,\n pub r13: u64,\n pub r14: u64,\n pub r15: u64,\n pub rdi: u64,\n pub rsi: u64,\n pub rbp: u64,\n pub rbx: u64,\n pub rdx: u64,\n pub rax: u64,\n pub rcx: u64,\n pub rsp: u64,\n pub rip: u64,\n pub rflags: u64,\n}\n\nimpl From<&sgx_cpu_context_t> for GpRegs {\n fn from(src: &sgx_cpu_context_t) -> Self {\n Self {\n r8: src.r8,\n r9: src.r9,\n r10: src.r10,\n r11: src.r11,\n r12: src.r12,\n r13: src.r13,\n r14: src.r14,\n r15: src.r15,\n rdi: src.rdi,\n rsi: src.rsi,\n rbp: src.rbp,\n rbx: src.rbx,\n rdx: src.rdx,\n rax: src.rax,\n rcx: src.rcx,\n rsp: src.rsp,\n rip: src.rip,\n rflags: src.rflags,\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2963,"cells":{"blob_id":{"kind":"string","value":"d9272fe0ee2e4eb06d3f65f8aa5b66cd7332d701"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Cazadorro/sfal"},"path":{"kind":"string","value":"/src/erfc.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4869,"string":"4,869"},"score":{"kind":"number","value":3.234375,"string":"3.234375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"/// Functions that approximate the erfc(x), the \"Complementary Error Function\".\n\nuse super::erf;\nuse super::consts;\nuse std::f64;\n\n///https://en.wikipedia.org/wiki/Error_function#Asymptotic_expansion\npub fn divergent_series(x: f64, max_n: u64) -> f64 {\n let mut prod = 1.0;\n let mut sum = 1.0;\n for n in 1..max_n {\n if n & 1 == 1 {\n prod *= n as f64;\n }\n prod /= (2.0 * x * x);\n }\n (f64::exp(-(x * x)) / (x * f64::consts::PI.sqrt())) * sum\n}\n\n///https://en.wikipedia.org/wiki/Error_function#Continued_fraction_expansion\npub fn continued_fraction(x: f64, max_n: u64) -> f64 {\n let mut fraction = 1.0;\n for i in (1..=max_n).rev() {\n let ai = i as f64 / 2.0;\n if i & 1 == 1 {\n fraction = (x * x) + (ai as f64 / fraction);\n } else {\n fraction = 1.0 + (ai as f64 / fraction);\n }\n }\n (x / f64::consts::PI.sqrt()) * f64::exp(-(x * x)) / fraction\n}\n\n///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations\npub fn abramowitz_0(x: f64) -> f64 {\n let x_negative = x < 0.0;\n let x = if x_negative { -x } else { x };\n let ai_array = [0.278393, 0.230389, 0.000972, 0.078108];\n let mut denominator_sum = 1.0_f64;\n let mut x_prod = 1.0;\n for i in 0..ai_array.len() {\n x_prod *= x;\n denominator_sum += ai_array[i] * x_prod;\n }\n let result = (1.0 / denominator_sum.powi(4));\n if x_negative {\n -result\n } else {\n result\n }\n}\n\n///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations\npub fn abramowitz_1(x: f64) -> f64 {\n let x_negative = x < 0.0;\n let x = if x_negative { -x } else { x };\n let p = 0.47047;\n let t = 1.0/(1.0 + p*x);\n let ai_array = [0.3480242,-0.0958798,0.7478556];\n let mut sum = 1.0;\n let mut t_prod = 1.0;\n for i in 0..ai_array.len() {\n t_prod *= t;\n sum += ai_array[i] * t_prod;\n }\n let result = (sum*f64::exp(-(x*x)));\n if x_negative {\n -result\n } else {\n result\n }\n}\n\n///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations\npub fn abramowitz_2(x: f64) -> f64 {\n let x_negative = x < 0.0;\n let x = if x_negative { -x } else { x };\n let ai_array = [0.0705230784, 0.0422820123, 0.0092705272, 0.0001520143, 0.0002765672, 0.0000430638];\n let mut denominator_sum = 1.0_f64;\n let mut x_prod = 1.0;\n for i in 0..ai_array.len() {\n x_prod *= x;\n denominator_sum += ai_array[i] * x_prod;\n }\n\n let result = (1.0 / denominator_sum.powi(16));\n if x_negative {\n -result\n } else {\n result\n }\n}\n\n///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations\npub fn abramowitz_3(x: f64) -> f64 {\n let x_negative = x < 0.0;\n let x = if x_negative { -x } else { x };\n let p = 0.3275911;\n let t = 1.0/(1.0 + p*x);\n let ai_array = [0.254829592,-0.284496736,1.421413741,-1.453152027,1.061405429];\n let mut sum = 1.0;\n let mut t_prod = 1.0;\n for i in 0..ai_array.len() {\n t_prod *= t;\n sum += ai_array[i] * t_prod;\n }\n let result = (sum*f64::exp(-(x*x)));\n if x_negative {\n -result\n } else {\n result\n }\n}\n\n///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations\npub fn karagiannidis(x: f64) -> f64{\n let x_negative = x < 0.0;\n let x = if x_negative { -x } else { x };\n\n\n let a = 1.98;\n let b = 1.135;\n\n let result = ((1.0 - f64::exp(-a*x))*f64::exp(-(x*x)))/(b * f64::consts::PI.sqrt() * x);\n if x_negative {\n -result\n } else {\n result\n }\n}\n\n///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations\npub fn sergei_pade(x:f64)-> f64{\n 1.0 - erf::sergei_pade(x)\n}\n\npub fn polynomial_9th(x:f64) -> f64{\n 1.0 - erf::polynomial_9th(x)\n}\n\n///Numerical Recipes third edition page 265.\npub fn recipes_cheb(x : f64) -> f64{\n let cheb_coef_array = [-1.3026537197817094, 6.4196979235649026e-1,\n 1.9476473204185836e-2,-9.561514786808631e-3,-9.46595344482036e-4,\n 3.66839497852761e-4,4.2523324806907e-5,-2.0278578112534e-5,\n -1.624290004647e-6,1.303655835580e-6,1.5626441722e-8,-8.5238095915e-8,\n 6.529054439e-9,5.059343495e-9,-9.91364156e-10,-2.27365122e-10,\n 9.6467911e-11, 2.394038e-12,-6.886027e-12,8.94487e-13, 3.13092e-13,\n -1.12708e-13,3.81e-16,7.106e-15,-1.523e-15,-9.4e-17,1.21e-16,-2.8e-17];\n\n let mut d=0.0;\n let mut dd=0.0;\n let x_negative = x < 0.0;\n let x = if x_negative{ -x }else{ x };\n\n let t = 2.0/(2.0+x);\n let ty = 4.0*t - 2.0;\n for j in (0..cheb_coef_array.len()).rev() {\n let tmp = d;\n d = ty*d - dd + cheb_coef_array[j as usize];\n dd = tmp;\n }\n let result = t*f64::exp(-x*x + 0.5*(cheb_coef_array[0] + ty*d) - dd);\n if x_negative{\n -result\n }else{\n result\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2964,"cells":{"blob_id":{"kind":"string","value":"e95967df9ce5dd18e8ee73c489ce9ef120d27977"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"fuerstenau/gorrosion-gtp"},"path":{"kind":"string","value":"/src/data/color.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":778,"string":"778"},"score":{"kind":"number","value":2.859375,"string":"2.859375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use super::super::messages::WriteGTP;\nuse super::*;\nuse std::io;\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum Value {\n\tBlack,\n\tWhite,\n}\n\nimpl WriteGTP for Value {\n\tfn write_gtp(&self, f: &mut impl io::Write) -> io::Result<()> {\n\t\tmatch self {\n\t\t\tValue::Black => write!(f, \"Black\"),\n\t\t\tValue::White => write!(f, \"White\"),\n\t\t}\n\t}\n}\n\nsingleton_type!(Color);\n\nimpl HasType for Value {\n\tfn has_type(&self, _t: &Type) -> bool {\n\t\ttrue\n\t}\n}\n\nimpl Data for Value {\n\ttype Type = Type;\n\n\tfn parse<'a, I: Input<'a>>(i: I, _t: &Self::Type) -> IResult {\n\t\t#[rustfmt::skip]\n\t\talt!(i,\n\t\t\tvalue!(\n\t\t\t\tValue::White,\n\t\t\t\talt!(tag_no_case!(\"W\") | tag_no_case!(\"white\"))\n\t\t\t) |\n\t\t\tvalue!(\n\t\t\t\tValue::Black,\n\t\t\t\talt!(tag_no_case!(\"B\") | tag_no_case!(\"black\"))\n\t\t\t)\n\t\t)\n\t}\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2965,"cells":{"blob_id":{"kind":"string","value":"f75ec2b2f15bd84d20f2a363894ec906bd7cecb0"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"skanev/playground"},"path":{"kind":"string","value":"/advent-of-code/2021/day09/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1989,"string":"1,989"},"score":{"kind":"number","value":3.328125,"string":"3.328125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::{collections::VecDeque, fs};\n\nfn parse_input() -> Vec> {\n let text = fs::read_to_string(\"../inputs/09\").unwrap();\n let height = text.lines().count();\n let width = text.lines().next().unwrap().len();\n\n let mut result = vec![vec![9; width + 2]; height + 2];\n\n for (i, line) in text.lines().enumerate() {\n for (j, byte) in line.bytes().enumerate() {\n result[i + 1][j + 1] = byte - b'0';\n }\n }\n\n result\n}\n\nfn low_points(map: &Vec>) -> Vec<(usize, usize)> {\n let height = map.len();\n let width = map[0].len();\n\n let mut result = vec![];\n\n for i in 1..(height - 2) {\n for j in 1..(width - 2) {\n if map[i][j] < map[i - 1][j]\n && map[i][j] < map[i + 1][j]\n && map[i][j] < map[i][j - 1]\n && map[i][j] < map[i][j + 1]\n {\n result.push((i, j));\n }\n }\n }\n\n result\n}\n\nfn fill(map: &mut Vec>, point: (usize, usize)) -> usize {\n let mut left: VecDeque<(usize, usize)> = VecDeque::new();\n let mut count = 0;\n\n left.push_back(point);\n\n while left.len() > 0 {\n let point = left.pop_front().unwrap();\n\n if map[point.0][point.1] == 9 {\n continue;\n }\n\n map[point.0][point.1] = 9;\n count += 1;\n\n left.push_back((point.0 - 1, point.1));\n left.push_back((point.0 + 1, point.1));\n left.push_back((point.0, point.1 - 1));\n left.push_back((point.0, point.1 + 1));\n }\n\n count\n}\n\nfn main() {\n let mut map = parse_input();\n let lows = low_points(&map);\n\n let first: usize = lows.iter().map(|&(x, y)| (map[x][y] as usize) + 1).sum();\n\n let mut basins: Vec = vec![];\n\n for point in lows {\n basins.push(fill(&mut map, point));\n }\n basins.sort();\n\n let second: usize = basins[basins.len() - 3..].iter().product();\n\n println!(\"first = {}\", first);\n println!(\"second = {}\", second);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2966,"cells":{"blob_id":{"kind":"string","value":"9170d885608392e23cee3e89a0170fb7bf621d19"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"ArthurMatthys/Gomoku"},"path":{"kind":"string","value":"/src/model/score_board.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2434,"string":"2,434"},"score":{"kind":"number","value":2.875,"string":"2.875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use super::super::render::board::SIZE_BOARD;\n\n#[derive(Clone, Copy)]\npub struct ScoreBoard([[[(u8, Option, Option); 4]; SIZE_BOARD]; SIZE_BOARD]);\n\nimpl ScoreBoard {\n /// Retrieve score_board[x][y][dir]\n pub fn get(&self, x: usize, y: usize, dir: usize) -> (u8, Option, Option) {\n self.0[x][y][dir]\n }\n\n /// Check and Retrieve score_board[x][y][dir] if possible\n pub fn get_check(\n &self,\n x: usize,\n y: usize,\n dir: usize,\n ) -> Option<(u8, Option, Option)> {\n self.0\n .get(x)\n .map(|b| b.get(y).map(|c| c.get(dir)))\n .flatten()\n .flatten()\n .cloned()\n }\n\n /// Change value of score_board[x][y][dir]\n pub fn set(\n &mut self,\n x: usize,\n y: usize,\n dir: usize,\n score: (u8, Option, Option),\n ) -> () {\n self.0[x][y][dir] = score;\n }\n\n /// Retrieve score_board[x][y]\n pub fn get_arr(&self, x: usize, y: usize) -> [(u8, Option, Option); 4] {\n self.0[x][y]\n }\n\n pub fn reset(&mut self, x: usize, y: usize, dir: usize) -> () {\n self.0[x][y][dir] = (0, Some(false), Some(false));\n }\n\n // Print score_board\n pub fn print(&self) -> () {\n self.0.iter().for_each(|x| {\n x.iter().for_each(|y| {\n y.iter().for_each(|el| print!(\"{:2}\", el.0));\n print!(\"||\");\n });\n println!();\n })\n }\n}\n\nimpl From<[[[(u8, Option, Option); 4]; SIZE_BOARD]; SIZE_BOARD]> for ScoreBoard {\n fn from(item: [[[(u8, Option, Option); 4]; SIZE_BOARD]; SIZE_BOARD]) -> Self {\n ScoreBoard(item)\n }\n}\n\nimpl From for [[[(u8, Option, Option); 4]; SIZE_BOARD]; SIZE_BOARD] {\n fn from(item: ScoreBoard) -> Self {\n item.0\n }\n}\n\nimpl PartialEq for ScoreBoard {\n fn eq(&self, other: &Self) -> bool {\n for x in 0..SIZE_BOARD {\n for y in 0..SIZE_BOARD {\n for dir in 0..4 {\n if self.0[x][y][dir].0 != other.0[x][y][dir].0\n || self.0[x][y][dir].1 != other.0[x][y][dir].1\n || self.0[x][y][dir].2 != other.0[x][y][dir].2\n {\n return false;\n }\n }\n }\n }\n true\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2967,"cells":{"blob_id":{"kind":"string","value":"78e668f8d152738b18f2c4770faed77a5edf2d21"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"kerinin/email-rs"},"path":{"kind":"string","value":"/src/rfc2822/quoted.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6883,"string":"6,883"},"score":{"kind":"number","value":2.734375,"string":"2.734375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use bytes::{Bytes, ByteStr};\nuse chomp::*;\n\nuse rfc2822::folding::*;\nuse rfc2822::obsolete::*;\nuse rfc2822::primitive::*;\n\n// quoted-pair = (\"\\\" text) / obs-qp\n// Consumes & returns matches\npub fn quoted_pair(i: Input) -> U8Result {\n parse!{i;\n or( \n |i| parse!{i; token(b'\\\\') >> text() },\n obs_qp,\n )}\n}\n\n/*\n#[test]\npub fn test_quoted_pair() {\nassert_eq!(parse_only(quoted_pair, \"\\\\\\n\".as_bytes()), Ok(\"\\n\".as_bytes()));\n}\n*/\n\n// qtext = NO-WS-CTL / ; Non white space controls\n//\n// %d33 / ; The rest of the US-ASCII\n// %d35-91 / ; characters not including \"\\\"\n// %d93-126 ; or the quote character\nconst QTEXT: [bool; 256] = [\n // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19\n false, true, true, true, true, true, true, true, true, false, false, true, true, false, true, true, true, true, true, true, // 0 - 19\n true, true, true, true, true, true, true, true, true, true, true, true, false, true, false, true, true, true, true, true, // 20 - 39\n true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // 40 - 59\n true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // 60 - 79\n true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, true, true, true, true, true, // 80 - 99\n true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // 100 - 119\n true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, // 120 - 139\n false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 140 - 159\n false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 160 - 179\n false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 180 - 199\n false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 200 - 219\n false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 220 - 239\n false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false // 240 - 256\n];\npub fn qtext(i: Input) -> U8Result {\n satisfy(i, |c| QTEXT[c as usize])\n}\n\n// qcontent = qtext / quoted-pair\npub fn qcontent(i: Input) -> U8Result {\n parse!{i;\n qtext() <|> quoted_pair()\n }\n}\n\n#[test]\nfn test_qcontent() {\n let i = b\"G\";\n let msg = parse_only(qcontent, i);\n assert!(msg.is_ok());\n assert_eq!(msg.unwrap(), b'G');\n\n let i = b\"\\\\\\\"\";\n let msg = parse_only(qcontent, i);\n assert!(msg.is_ok());\n assert_eq!(msg.unwrap(), b'\\\"');\n}\n\n// quoted-string = [CFWS]\n// DQUOTE *([FWS] qcontent) [FWS] DQUOTE\n// [CFWS]\n// NOTE: in order to reduce allocations, this checks for runs of qtext \n// explicitly, so expanding things out:\n// quoted-string = [CFWS] DQUOTE *([FWS] qcontent) [FWS] DQUOTE [CFWS]\n//\n// substitute qcontent: \n// = [CFWS] DQUOTE *([FWS] (qtext / quoted-pair)) [FWS] DQUOTE [CFWS]\n//\n// associate many\n// = [CFWS] DQUOTE *([FWS] (1*qtext / quoted-pair)) [FWS] DQUOTE [CFWS]\n//\npub fn quoted_string(i: Input) -> U8Result {\n option(i, cfws, Bytes::empty()).bind(|i, ws1| {\n dquote(i).then(|i| {\n\n let a = |i| {\n option(i, fws, Bytes::empty()).bind(|i, ws2| {\n or(i,\n |i| matched_by(i, |i| skip_many1(i, qtext)).map(|(v, _)| Bytes::from_slice(v)),\n |i| quoted_pair(i).map(|c| Bytes::from_slice(&[c][..])),\n ).bind(|i, cs| {\n i.ret(ws2.concat(&cs))\n })\n })\n };\n\n many(i, a).bind(|i, rs: Vec| {\n option(i, fws, Bytes::empty()).bind(|i, ws3| {\n dquote(i).then(|i| {\n option(i, cfws, Bytes::empty()).bind(|i, ws4| {\n let bs = rs.into_iter().fold(ws1, |acc, r| acc.concat(&r));\n\n i.ret(bs.concat(&ws3).concat(&ws4))\n })\n })\n })\n })\n })\n })\n}\n\n#[test]\nfn test_quoted_string() {\n let i = b\"\\\"Giant; \\\\\\\"Big\\\\\\\" Box\\\"\";\n let msg = parse_only(quoted_string, i);\n assert!(msg.is_ok());\n assert_eq!(msg.unwrap(), Bytes::from_slice(b\"Giant; \\\"Big\\\" Box\"));\n}\n\npub fn quoted_string_not

(i: Input, mut p: P) -> U8Result where\nP: FnMut(u8) -> bool,\n{\n option(i, cfws, Bytes::empty()).bind(|i, ws1| {\n dquote(i).then(|i| {\n many1(i, |i| {\n option(i, fws, Bytes::empty()).bind(|i, ws2| {\n matched_by(i, |i| {\n peek_next(i).bind(|i, next| {\n if p(next) {\n i.err(Error::Unexpected)\n } else {\n qcontent(i)\n }\n })\n\n }).bind(|i, (v, _)| {\n i.ret(ws2.concat(&Bytes::from_slice(v)))\n })\n })\n }).bind(|i, rs: Vec| {\n option(i, fws, Bytes::empty()).bind(|i, ws3| {\n dquote(i).then(|i| {\n option(i, cfws, Bytes::empty()).bind(|i, ws4| {\n let bs = rs.into_iter().fold(ws1, |acc, r| acc.concat(&r));\n\n i.ret(bs.concat(&ws3).concat(&ws4))\n })\n })\n })\n })\n })\n })\n}\n\n\n#[test]\nfn test_quoted_string_not() {\n let i = b\"\\\"jdoe\\\"\";\n let msg = parse_only(|i| quoted_string_not(i, |c| c == b'@'), i);\n assert_eq!(msg, Ok(Bytes::from_slice(b\"jdoe\")));\n\n let i = b\"\\\"jdoe\\\"@example.com\";\n let msg = parse_only(|i| quoted_string_not(i, |c| c == b'@'), i);\n assert_eq!(msg, Ok(Bytes::from_slice(b\"jdoe\")));\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2968,"cells":{"blob_id":{"kind":"string","value":"50a892d11aded402f16b56046793a5e33e989d75"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"iCodeIN/rust-advent"},"path":{"kind":"string","value":"/y2020/ex04/src/validators.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2842,"string":"2,842"},"score":{"kind":"number","value":3.34375,"string":"3.34375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use regex::Regex;\nuse std::ops::RangeInclusive;\n\npub trait Validator {\n fn validate(&self, value: &str) -> bool;\n}\n\npub struct U16RangeValidator {\n range: RangeInclusive,\n}\n\nimpl U16RangeValidator {\n pub fn new(range: RangeInclusive) -> Self {\n U16RangeValidator { range }\n }\n}\n\nimpl Validator for U16RangeValidator {\n fn validate(&self, value: &str) -> bool {\n if let Ok(year) = value.parse::() {\n return self.range.contains(&year);\n }\n false\n }\n}\n\npub struct RegexValidator {\n regex: Regex,\n}\n\nimpl RegexValidator {\n pub fn new(regex: Regex) -> Self {\n RegexValidator { regex }\n }\n}\n\nimpl Validator for RegexValidator {\n fn validate(&self, value: &str) -> bool {\n self.regex.is_match(value)\n }\n}\n\n// byr (Birth Year) - four digits; at least 1920 and at most 2002.\npub fn create_byr_validator() -> U16RangeValidator {\n U16RangeValidator::new(1920..=2002)\n}\n\n// iyr (Issue Year) - four digits; at least 2010 and at most 2020.\npub fn create_iyr_validator() -> U16RangeValidator {\n U16RangeValidator::new(2010..=2020)\n}\n\n// eyr (Expiration Year) - four digits; at least 2020 and at most 2030.\npub fn create_eyr_validator() -> U16RangeValidator {\n U16RangeValidator::new(2020..=2030)\n}\n\n// hgt (Height) - a number followed by either cm or in.\n// If cm, the number must be at least 150 and at most 193.\n// If in, the number must be at least 59 and at most 76.\npub struct HgtValidator {\n regex: Regex,\n}\n\nimpl HgtValidator {\n pub fn new() -> Self {\n let regex = Regex::new(r\"^(\\d+)(in|cm)$\").unwrap();\n HgtValidator { regex }\n }\n}\n\nimpl Validator for HgtValidator {\n fn validate(&self, value: &str) -> bool {\n if let Some(captures) = self.regex.captures(value) {\n let unit = captures.get(2).unwrap().as_str();\n\n if let Ok(num) = captures.get(1).unwrap().as_str().parse::() {\n return (unit == \"in\" && (59..=76).contains(&num))\n || (unit == \"cm\" && (150..=193).contains(&num));\n }\n }\n false\n }\n}\n\npub fn create_hgt_validator() -> HgtValidator {\n HgtValidator::new()\n}\n\n// hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f.\npub fn create_hcl_validator() -> RegexValidator {\n let regex = Regex::new(r\"^#[0-9a-fA-F]{6}$\").unwrap();\n RegexValidator::new(regex)\n}\n\n// ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth.\npub fn create_ecl_validator() -> RegexValidator {\n let regex = Regex::new(r\"^(amb|blu|brn|gry|grn|hzl|oth)$\").unwrap();\n RegexValidator::new(regex)\n}\n\n// pid (Passport ID) - a nine-digit number, including leading zeroes.\npub fn create_pid_validator() -> RegexValidator {\n let regex = Regex::new(r\"^\\d{9}$\").unwrap();\n RegexValidator::new(regex)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2969,"cells":{"blob_id":{"kind":"string","value":"158bc4f31dcdf8670799376e3b8855835b601485"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"open-telemetry/opentelemetry-rust"},"path":{"kind":"string","value":"/opentelemetry-sdk/src/testing/trace/in_memory_exporter.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4403,"string":"4,403"},"score":{"kind":"number","value":2.734375,"string":"2.734375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use crate::export::trace::{ExportResult, SpanData, SpanExporter};\nuse futures_util::future::BoxFuture;\nuse opentelemetry::trace::{TraceError, TraceResult};\nuse std::sync::{Arc, Mutex};\n\n/// An in-memory span exporter that stores span data in memory.\n///\n/// This exporter is useful for testing and debugging purposes. It stores\n/// metric data in a `Vec`. Metrics can be retrieved\n/// using the `get_finished_spans` method.\n/// # Example\n/// ```\n///# use opentelemetry::trace::{SpanKind, TraceContextExt};\n///# use opentelemetry::{global, trace::Tracer, Context};\n///# use opentelemetry_sdk::propagation::TraceContextPropagator;\n///# use opentelemetry_sdk::runtime;\n///# use opentelemetry_sdk::testing::trace::InMemorySpanExporterBuilder;\n///# use opentelemetry_sdk::trace::{BatchSpanProcessor, TracerProvider};\n///\n///# #[tokio::main]\n///# async fn main() {\n/// let exporter = InMemorySpanExporterBuilder::new().build();\n/// let provider = TracerProvider::builder()\n/// .with_span_processor(BatchSpanProcessor::builder(exporter.clone(), runtime::Tokio).build())\n/// .build();\n///\n/// global::set_tracer_provider(provider.clone());\n///\n/// let tracer = global::tracer(\"example/in_memory_exporter\");\n/// let span = tracer\n/// .span_builder(\"say hello\")\n/// .with_kind(SpanKind::Server)\n/// .start(&tracer);\n///\n/// let cx = Context::current_with_span(span);\n/// cx.span().add_event(\"handling this...\", Vec::new());\n/// cx.span().end();\n///\n/// let results = provider.force_flush();\n/// for result in results {\n/// if let Err(e) = result {\n/// println!(\"{:?}\", e)\n/// }\n/// }\n/// let spans = exporter.get_finished_spans().unwrap();\n/// for span in spans {\n/// println!(\"{:?}\", span)\n/// }\n///# }\n/// ```\n#[derive(Clone, Debug)]\npub struct InMemorySpanExporter {\n spans: Arc>>,\n}\n\nimpl Default for InMemorySpanExporter {\n fn default() -> Self {\n InMemorySpanExporterBuilder::new().build()\n }\n}\n\n/// Builder for [`InMemorySpanExporter`].\n/// # Example\n/// ```\n///# use opentelemetry_sdk::testing::trace::InMemorySpanExporterBuilder;\n///\n/// let exporter = InMemorySpanExporterBuilder::new().build();\n/// ```\n#[derive(Clone, Debug)]\npub struct InMemorySpanExporterBuilder {}\n\nimpl Default for InMemorySpanExporterBuilder {\n fn default() -> Self {\n Self::new()\n }\n}\n\nimpl InMemorySpanExporterBuilder {\n /// Creates a new instance of the `InMemorySpanExporterBuilder`.\n pub fn new() -> Self {\n Self {}\n }\n\n /// Creates a new instance of the `InMemorySpanExporter`.\n pub fn build(&self) -> InMemorySpanExporter {\n InMemorySpanExporter {\n spans: Arc::new(Mutex::new(Vec::new())),\n }\n }\n}\n\nimpl InMemorySpanExporter {\n /// Returns the finished span as a vector of `SpanData`.\n ///\n /// # Errors\n ///\n /// Returns a `TraceError` if the internal lock cannot be acquired.\n ///\n /// # Example\n ///\n /// ```\n /// # use opentelemetry_sdk::testing::trace::InMemorySpanExporter;\n ///\n /// let exporter = InMemorySpanExporter::default();\n /// let finished_spans = exporter.get_finished_spans().unwrap();\n /// ```\n pub fn get_finished_spans(&self) -> TraceResult> {\n self.spans\n .lock()\n .map(|spans_guard| spans_guard.iter().cloned().collect())\n .map_err(TraceError::from)\n }\n\n /// Clears the internal storage of finished spans.\n ///\n /// # Example\n ///\n /// ```\n /// # use opentelemetry_sdk::testing::trace::InMemorySpanExporter;\n ///\n /// let exporter = InMemorySpanExporter::default();\n /// exporter.reset();\n /// ```\n pub fn reset(&self) {\n let _ = self.spans.lock().map(|mut spans_guard| spans_guard.clear());\n }\n}\n\nimpl SpanExporter for InMemorySpanExporter {\n fn export(&mut self, batch: Vec) -> BoxFuture<'static, ExportResult> {\n if let Err(err) = self\n .spans\n .lock()\n .map(|mut spans_guard| spans_guard.append(&mut batch.clone()))\n .map_err(TraceError::from)\n {\n return Box::pin(std::future::ready(Err(Into::into(err))));\n }\n Box::pin(std::future::ready(Ok(())))\n }\n\n fn shutdown(&mut self) {\n self.reset()\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2970,"cells":{"blob_id":{"kind":"string","value":"2006d078ad47d36d15c36ed32964ca4e48ba983a"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Jackywathy/mipsy"},"path":{"kind":"string","value":"/crates/mipsy_web/src/components/pagebackground.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":800,"string":"800"},"score":{"kind":"number","value":2.640625,"string":"2.640625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use yew::prelude::*;\nuse yew::{Children, Properties};\n\n#[derive(Properties, Clone)]\npub struct Props {\n #[prop_or_default]\n pub children: Children,\n}\n\npub struct PageBackground {\n pub props: Props,\n}\n\nimpl Component for PageBackground {\n type Message = ();\n type Properties = Props;\n\n fn create(props: Self::Properties, _: ComponentLink) -> Self {\n PageBackground { props }\n }\n\n fn change(&mut self, props: Self::Properties) -> ShouldRender {\n self.props = props;\n true\n }\n\n fn update(&mut self, _: Self::Message) -> ShouldRender {\n true\n }\n\n fn view(&self) -> Html {\n html! {\n

\n { for self.props.children.iter() }\n
\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2971,"cells":{"blob_id":{"kind":"string","value":"6f26f1b91aa0aa6fbc61955934f49b2b711a4f1e"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"cjoh88/Zombie"},"path":{"kind":"string","value":"/src/editor/input.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2246,"string":"2,246"},"score":{"kind":"number","value":2.921875,"string":"2.921875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use sfml::window::{Key};\r\nuse sfml::window::{event};\r\nuse sfml::window::MouseButton;\r\nuse sfml::graphics::{RenderWindow};\r\nuse sfml::system::{Vector2i, Vector2f};\r\nuse sfml::graphics::RenderTarget;\r\n\r\nuse editor::world::World;\r\n\r\npub struct EditorInputHandler {\r\n\tdummy: i32\r\n}\r\n\r\nimpl EditorInputHandler {\r\n\tpub fn new() -> Self {\r\n\t\tEditorInputHandler {\r\n\t\t\tdummy: 0,\r\n\t\t}\r\n\t}\r\n\r\n\tpub fn handle_input(&mut self, world: &mut World, window: &mut RenderWindow) {\r\n\t\tfor event in window.events() {\r\n\t\t\tmatch event {\r\n\t\t\t\tevent::Closed => window.close(),\r\n\t\t\t\tevent::KeyPressed{code, ..} => self.handle_key_pressed(world, window, code),\t//world, window, code\r\n\t\t\t\tevent::KeyReleased{code, ..} => self.handle_key_released(world, window, code),\t//world, window, code\r\n\t\t\t\tevent::MouseButtonPressed{button, x, y} => self.handle_mouse_pressed(world, window, button, x, y), //world, window, button, x, y\r\n\t\t\t\t_ => (),\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tfn handle_key_pressed(&mut self, world: &mut World, window: &mut RenderWindow, code: Key) {\r\n\t\tmatch code {\r\n Key::Escape => window.close(),\r\n Key::Right | Key::D => world.get_mut_camera().move_right(),\r\n Key::Left | Key::A => world.get_mut_camera().move_left(),\r\n Key::Up | Key::W => world.get_mut_camera().move_up(),\r\n Key::Down | Key::S => world.get_mut_camera().move_down(),\r\n _ => ()\r\n }\r\n\t}\r\n\tfn handle_key_released(&mut self, world: &mut World, window: &mut RenderWindow, code: Key) {\r\n match code {\r\n Key::Right | Key::Left | Key::D | Key::A => world.get_mut_camera().stop_horizontal(),\r\n Key::Up | Key::Down | Key::W | Key::S => world.get_mut_camera().stop_vertical(),\r\n Key::Add => world.get_mut_camera().zoom(0.5),\r\n Key::Subtract => world.get_mut_camera().zoom(2.0),\r\n _ => ()\r\n }\r\n }\r\n\r\n fn handle_mouse_pressed(&mut self, editor: &mut World, window: &mut RenderWindow, code: MouseButton, x: i32, y: i32) {\r\n /*let v = Vector2i::new(x,y);\r\n let v2: Vector2f = window.map_pixel_to_coords(&v, &editor.get_view());\r\n let v3 = screen_to_map(v2);\r\n println!(\"Mouse({}, {})\", v3.x, v3.y);*/\r\n\r\n }\r\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2972,"cells":{"blob_id":{"kind":"string","value":"9cfe05532aedfe26141eba73dd1bd0d2ee01e656"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"rust-lang/rust-analyzer"},"path":{"kind":"string","value":"/crates/ide-diagnostics/src/handlers/unresolved_macro_call.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1607,"string":"1,607"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0","MIT"],"string":"[\n \"Apache-2.0\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext};\n\n// Diagnostic: unresolved-macro-call\n//\n// This diagnostic is triggered if rust-analyzer is unable to resolve the path\n// to a macro in a macro invocation.\npub(crate) fn unresolved_macro_call(\n ctx: &DiagnosticsContext<'_>,\n d: &hir::UnresolvedMacroCall,\n) -> Diagnostic {\n // Use more accurate position if available.\n let display_range = ctx.resolve_precise_location(&d.macro_call, d.precise_location);\n let bang = if d.is_bang { \"!\" } else { \"\" };\n Diagnostic::new(\n DiagnosticCode::RustcHardError(\"unresolved-macro-call\"),\n format!(\"unresolved macro `{}{bang}`\", d.path.display(ctx.sema.db)),\n display_range,\n )\n .experimental()\n}\n\n#[cfg(test)]\nmod tests {\n use crate::tests::check_diagnostics;\n\n #[test]\n fn unresolved_macro_diag() {\n check_diagnostics(\n r#\"\nfn f() {\n m!();\n} //^ error: unresolved macro `m!`\n\n\"#,\n );\n }\n\n #[test]\n fn test_unresolved_macro_range() {\n check_diagnostics(\n r#\"\nfoo::bar!(92);\n //^^^ error: unresolved macro `foo::bar!`\n\"#,\n );\n }\n\n #[test]\n fn unresolved_legacy_scope_macro() {\n check_diagnostics(\n r#\"\nmacro_rules! m { () => {} }\n\nm!(); m2!();\n //^^ error: unresolved macro `m2!`\n\"#,\n );\n }\n\n #[test]\n fn unresolved_module_scope_macro() {\n check_diagnostics(\n r#\"\nmod mac {\n#[macro_export]\nmacro_rules! m { () => {} } }\n\nself::m!(); self::m2!();\n //^^ error: unresolved macro `self::m2!`\n\"#,\n );\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2973,"cells":{"blob_id":{"kind":"string","value":"2d3c47f93338cb47dfcdef8c16ab9c8fa0fea7bf"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"zmbush/cargo"},"path":{"kind":"string","value":"/src/cargo/core/resolver/mod.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":22960,"string":"22,960"},"score":{"kind":"number","value":2.546875,"string":"2.546875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["GCC-exception-2.0","BSD-3-Clause","LGPL-2.0-or-later","OpenSSL","Zlib","MIT","curl","GPL-2.0-only","LicenseRef-scancode-openssl","LicenseRef-scancode-ssleay-windows","Unlicense","LGPL-2.1-only","Apache-2.0"],"string":"[\n \"GCC-exception-2.0\",\n \"BSD-3-Clause\",\n \"LGPL-2.0-or-later\",\n \"OpenSSL\",\n \"Zlib\",\n \"MIT\",\n \"curl\",\n \"GPL-2.0-only\",\n \"LicenseRef-scancode-openssl\",\n \"LicenseRef-scancode-ssleay-windows\",\n \"Unlicense\",\n \"LGPL-2.1-only\",\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use std::cell::RefCell;\nuse std::collections::HashSet;\nuse std::collections::hash_map::HashMap;\nuse std::fmt;\nuse std::rc::Rc;\nuse semver;\n\nuse core::{PackageId, Registry, SourceId, Summary, Dependency};\nuse core::PackageIdSpec;\nuse util::{CargoResult, Graph, human, ChainError, CargoError};\nuse util::profile;\nuse util::graph::{Nodes, Edges};\n\npub use self::encode::{EncodableResolve, EncodableDependency, EncodablePackageId};\npub use self::encode::Metadata;\n\nmod encode;\n\n/// Represents a fully resolved package dependency graph. Each node in the graph\n/// is a package and edges represent dependencies between packages.\n///\n/// Each instance of `Resolve` also understands the full set of features used\n/// for each package as well as what the root package is.\n#[derive(PartialEq, Eq, Clone)]\npub struct Resolve {\n graph: Graph,\n features: HashMap>,\n root: PackageId,\n metadata: Option,\n}\n\n#[derive(Clone, Copy)]\npub enum Method<'a> {\n Everything,\n Required{ dev_deps: bool,\n features: &'a [String],\n uses_default_features: bool,\n target_platform: Option<&'a str>},\n}\n\nimpl Resolve {\n fn new(root: PackageId) -> Resolve {\n let mut g = Graph::new();\n g.add(root.clone(), &[]);\n Resolve { graph: g, root: root, features: HashMap::new(), metadata: None }\n }\n\n pub fn copy_metadata(&mut self, other: &Resolve) {\n self.metadata = other.metadata.clone();\n }\n\n pub fn iter(&self) -> Nodes {\n self.graph.iter()\n }\n\n pub fn root(&self) -> &PackageId { &self.root }\n\n pub fn deps(&self, pkg: &PackageId) -> Option> {\n self.graph.edges(pkg)\n }\n\n pub fn query(&self, spec: &str) -> CargoResult<&PackageId> {\n let spec = try!(PackageIdSpec::parse(spec).chain_error(|| {\n human(format!(\"invalid package id specification: `{}`\", spec))\n }));\n let mut ids = self.iter().filter(|p| spec.matches(*p));\n let ret = match ids.next() {\n Some(id) => id,\n None => return Err(human(format!(\"package id specification `{}` \\\n matched no packages\", spec))),\n };\n return match ids.next() {\n Some(other) => {\n let mut msg = format!(\"There are multiple `{}` packages in \\\n your project, and the specification \\\n `{}` is ambiguous.\\n\\\n Please re-run this command \\\n with `-p ` where `` is one \\\n of the following:\",\n spec.name(), spec);\n let mut vec = vec![ret, other];\n vec.extend(ids);\n minimize(&mut msg, vec, &spec);\n Err(human(msg))\n }\n None => Ok(ret)\n };\n\n fn minimize(msg: &mut String,\n ids: Vec<&PackageId>,\n spec: &PackageIdSpec) {\n let mut version_cnt = HashMap::new();\n for id in ids.iter() {\n *version_cnt.entry(id.version()).or_insert(0) += 1;\n }\n for id in ids.iter() {\n if version_cnt[id.version()] == 1 {\n msg.push_str(&format!(\"\\n {}:{}\", spec.name(),\n id.version()));\n } else {\n msg.push_str(&format!(\"\\n {}\",\n PackageIdSpec::from_package_id(*id)));\n }\n }\n }\n }\n\n pub fn features(&self, pkg: &PackageId) -> Option<&HashSet> {\n self.features.get(pkg)\n }\n}\n\nimpl fmt::Debug for Resolve {\n fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {\n try!(write!(fmt, \"graph: {:?}\\n\", self.graph));\n try!(write!(fmt, \"\\nfeatures: {{\\n\"));\n for (pkg, features) in &self.features {\n try!(write!(fmt, \" {}: {:?}\\n\", pkg, features));\n }\n write!(fmt, \"}}\")\n }\n}\n\n#[derive(Clone)]\nstruct Context {\n activations: HashMap<(String, SourceId), Vec>>,\n resolve: Resolve,\n visited: Rc>>,\n}\n\n/// Builds the list of all packages required to build the first argument.\npub fn resolve(summary: &Summary, method: Method,\n registry: &mut Registry) -> CargoResult {\n trace!(\"resolve; summary={}\", summary.package_id());\n let summary = Rc::new(summary.clone());\n\n let cx = Box::new(Context {\n resolve: Resolve::new(summary.package_id().clone()),\n activations: HashMap::new(),\n visited: Rc::new(RefCell::new(HashSet::new())),\n });\n let _p = profile::start(format!(\"resolving: {}\", summary.package_id()));\n match try!(activate(cx, registry, &summary, method)) {\n Ok(cx) => {\n debug!(\"resolved: {:?}\", cx.resolve);\n Ok(cx.resolve)\n }\n Err(e) => Err(e),\n }\n}\n\nfn activate(mut cx: Box,\n registry: &mut Registry,\n parent: &Rc,\n method: Method)\n -> CargoResult>> {\n // Dependency graphs are required to be a DAG, so we keep a set of\n // packages we're visiting and bail if we hit a dupe.\n let id = parent.package_id();\n if !cx.visited.borrow_mut().insert(id.clone()) {\n return Err(human(format!(\"cyclic package dependency: package `{}` \\\n depends on itself\", id)))\n }\n\n // If we're already activated, then that was easy!\n if flag_activated(&mut *cx, parent, &method) {\n cx.visited.borrow_mut().remove(id);\n return Ok(Ok(cx))\n }\n debug!(\"activating {}\", parent.package_id());\n\n // Extracting the platform request.\n let platform = match method {\n Method::Required{target_platform: platform, ..} => platform,\n Method::Everything => None,\n };\n\n // First, figure out our set of dependencies based on the requsted set of\n // features. This also calculates what features we're going to enable for\n // our own dependencies.\n let deps = try!(resolve_features(&mut cx, parent, method));\n\n // Next, transform all dependencies into a list of possible candidates which\n // can satisfy that dependency.\n let mut deps = try!(deps.into_iter().map(|(_dep_name, (dep, features))| {\n let mut candidates = try!(registry.query(dep));\n // When we attempt versions for a package, we'll want to start at the\n // maximum version and work our way down.\n candidates.sort_by(|a, b| {\n b.version().cmp(a.version())\n });\n let candidates = candidates.into_iter().map(Rc::new).collect::>();\n Ok((dep, candidates, features))\n }).collect::>>());\n\n // When we recurse, attempt to resolve dependencies with fewer candidates\n // before recursing on dependencies with more candidates. This way if the\n // dependency with only one candidate can't be resolved we don't have to do\n // a bunch of work before we figure that out.\n deps.sort_by(|&(_, ref a, _), &(_, ref b, _)| {\n a.len().cmp(&b.len())\n });\n\n // Workaround compilation error: `deps` does not live long enough\n let platform = platform.map(|s| &*s);\n\n Ok(match try!(activate_deps(cx, registry, parent, platform, &deps, 0)) {\n Ok(cx) => {\n cx.visited.borrow_mut().remove(parent.package_id());\n Ok(cx)\n }\n Err(e) => Err(e),\n })\n}\n\n// Activate this summary by inserting it into our list of known activations.\n//\n// Returns if this summary with the given method is already activated.\nfn flag_activated(cx: &mut Context,\n summary: &Rc,\n method: &Method) -> bool {\n let id = summary.package_id();\n let key = (id.name().to_string(), id.source_id().clone());\n let prev = cx.activations.entry(key).or_insert(Vec::new());\n if !prev.iter().any(|c| c == summary) {\n cx.resolve.graph.add(id.clone(), &[]);\n prev.push(summary.clone());\n return false\n }\n debug!(\"checking if {} is already activated\", summary.package_id());\n let (features, use_default) = match *method {\n Method::Required { features, uses_default_features, .. } => {\n (features, uses_default_features)\n }\n Method::Everything => return false,\n };\n\n let has_default_feature = summary.features().contains_key(\"default\");\n match cx.resolve.features(id) {\n Some(prev) => {\n features.iter().all(|f| prev.contains(f)) &&\n (!use_default || prev.contains(\"default\") || !has_default_feature)\n }\n None => features.len() == 0 && (!use_default || !has_default_feature)\n }\n}\n\nfn activate_deps<'a>(cx: Box,\n registry: &mut Registry,\n parent: &Summary,\n platform: Option<&'a str>,\n deps: &'a [(&Dependency, Vec>, Vec)],\n cur: usize) -> CargoResult>> {\n if cur == deps.len() { return Ok(Ok(cx)) }\n let (dep, ref candidates, ref features) = deps[cur];\n\n let method = Method::Required{\n dev_deps: false,\n features: &features,\n uses_default_features: dep.uses_default_features(),\n target_platform: platform};\n\n let key = (dep.name().to_string(), dep.source_id().clone());\n let prev_active = cx.activations.get(&key)\n .map(|v| &v[..]).unwrap_or(&[]);\n trace!(\"{}[{}]>{} {} candidates\", parent.name(), cur, dep.name(),\n candidates.len());\n trace!(\"{}[{}]>{} {} prev activations\", parent.name(), cur,\n dep.name(), prev_active.len());\n\n // Filter the set of candidates based on the previously activated\n // versions for this dependency. We can actually use a version if it\n // precisely matches an activated version or if it is otherwise\n // incompatible with all other activated versions. Note that we define\n // \"compatible\" here in terms of the semver sense where if the left-most\n // nonzero digit is the same they're considered compatible.\n let my_candidates = candidates.iter().filter(|&b| {\n prev_active.iter().any(|a| a == b) ||\n prev_active.iter().all(|a| {\n !compatible(a.version(), b.version())\n })\n });\n\n // Alright, for each candidate that's gotten this far, it meets the\n // following requirements:\n //\n // 1. The version matches the dependency requirement listed for this\n // package\n // 2. There are no activated versions for this package which are\n // semver-compatible, or there's an activated version which is\n // precisely equal to `candidate`.\n //\n // This means that we're going to attempt to activate each candidate in\n // turn. We could possibly fail to activate each candidate, so we try\n // each one in turn.\n let mut last_err = None;\n for candidate in my_candidates {\n trace!(\"{}[{}]>{} trying {}\", parent.name(), cur, dep.name(),\n candidate.version());\n let mut my_cx = cx.clone();\n my_cx.resolve.graph.link(parent.package_id().clone(),\n candidate.package_id().clone());\n\n // If we hit an intransitive dependency then clear out the visitation\n // list as we can't induce a cycle through transitive dependencies.\n if !dep.is_transitive() {\n my_cx.visited.borrow_mut().clear();\n }\n let my_cx = match try!(activate(my_cx, registry, candidate, method)) {\n Ok(cx) => cx,\n Err(e) => { last_err = Some(e); continue }\n };\n match try!(activate_deps(my_cx, registry, parent, platform, deps,\n cur + 1)) {\n Ok(cx) => return Ok(Ok(cx)),\n Err(e) => { last_err = Some(e); }\n }\n }\n trace!(\"{}[{}]>{} -- {:?}\", parent.name(), cur, dep.name(),\n last_err);\n\n // Oh well, we couldn't activate any of the candidates, so we just can't\n // activate this dependency at all\n Ok(activation_error(&cx, registry, last_err, parent, dep, prev_active,\n &candidates))\n}\n\nfn activation_error(cx: &Context,\n registry: &mut Registry,\n err: Option>,\n parent: &Summary,\n dep: &Dependency,\n prev_active: &[Rc],\n candidates: &[Rc]) -> CargoResult> {\n match err {\n Some(e) => return Err(e),\n None => {}\n }\n if candidates.len() > 0 {\n let mut msg = format!(\"failed to select a version for `{}` \\\n (required by `{}`):\\n\\\n all possible versions conflict with \\\n previously selected versions of `{}`\",\n dep.name(), parent.name(),\n dep.name());\n 'outer: for v in prev_active.iter() {\n for node in cx.resolve.graph.iter() {\n let edges = match cx.resolve.graph.edges(node) {\n Some(edges) => edges,\n None => continue,\n };\n for edge in edges {\n if edge != v.package_id() { continue }\n\n msg.push_str(&format!(\"\\n version {} in use by {}\",\n v.version(), edge));\n continue 'outer;\n }\n }\n msg.push_str(&format!(\"\\n version {} in use by ??\",\n v.version()));\n }\n\n msg.push_str(&format!(\"\\n possible versions to select: {}\",\n candidates.iter()\n .map(|v| v.version())\n .map(|v| v.to_string())\n .collect::>()\n .connect(\", \")));\n\n return Err(human(msg))\n }\n // Once we're all the way down here, we're definitely lost in the\n // weeds! We didn't actually use any candidates above, so we need to\n // give an error message that nothing was found.\n //\n // Note that we re-query the registry with a new dependency that\n // allows any version so we can give some nicer error reporting\n // which indicates a few versions that were actually found.\n let msg = format!(\"no matching package named `{}` found \\\n (required by `{}`)\\n\\\n location searched: {}\\n\\\n version required: {}\",\n dep.name(), parent.name(),\n dep.source_id(),\n dep.version_req());\n let mut msg = msg;\n let all_req = semver::VersionReq::parse(\"*\").unwrap();\n let new_dep = dep.clone().set_version_req(all_req);\n let mut candidates = try!(registry.query(&new_dep));\n candidates.sort_by(|a, b| {\n b.version().cmp(a.version())\n });\n if candidates.len() > 0 {\n msg.push_str(\"\\nversions found: \");\n for (i, c) in candidates.iter().take(3).enumerate() {\n if i != 0 { msg.push_str(\", \"); }\n msg.push_str(&c.version().to_string());\n }\n if candidates.len() > 3 {\n msg.push_str(\", ...\");\n }\n }\n\n // If we have a path dependency with a locked version, then this may\n // indicate that we updated a sub-package and forgot to run `cargo\n // update`. In this case try to print a helpful error!\n if dep.source_id().is_path() &&\n dep.version_req().to_string().starts_with(\"=\") &&\n candidates.len() > 0 {\n msg.push_str(\"\\nconsider running `cargo update` to update \\\n a path dependency's locked version\");\n\n }\n Err(human(msg))\n}\n\n// Returns if `a` and `b` are compatible in the semver sense. This is a\n// commutative operation.\n//\n// Versions `a` and `b` are compatible if their left-most nonzero digit is the\n// same.\nfn compatible(a: &semver::Version, b: &semver::Version) -> bool {\n if a.major != b.major { return false }\n if a.major != 0 { return true }\n if a.minor != b.minor { return false }\n if a.minor != 0 { return true }\n a.patch == b.patch\n}\n\nfn resolve_features<'a>(cx: &mut Context, parent: &'a Summary,\n method: Method)\n -> CargoResult)>> {\n let dev_deps = match method {\n Method::Everything => true,\n Method::Required { dev_deps, .. } => dev_deps,\n };\n\n // First, filter by dev-dependencies\n let deps = parent.dependencies();\n let deps = deps.iter().filter(|d| d.is_transitive() || dev_deps);\n\n // Second, ignoring dependencies that should not be compiled for this platform\n let deps = deps.filter(|d| {\n match method {\n Method::Required{target_platform: Some(ref platform), ..} => {\n d.is_active_for_platform(platform)\n },\n _ => true\n }\n });\n\n let (mut feature_deps, used_features) = try!(build_features(parent, method));\n let mut ret = HashMap::new();\n\n // Next, sanitize all requested features by whitelisting all the requested\n // features that correspond to optional dependencies\n for dep in deps {\n // weed out optional dependencies, but not those required\n if dep.is_optional() && !feature_deps.contains_key(dep.name()) {\n continue\n }\n let mut base = feature_deps.remove(dep.name()).unwrap_or(vec![]);\n for feature in dep.features().iter() {\n base.push(feature.clone());\n if feature.contains(\"/\") {\n return Err(human(format!(\"features in dependencies \\\n cannot enable features in \\\n other dependencies: `{}`\",\n feature)));\n }\n }\n ret.insert(dep.name(), (dep, base));\n }\n\n // All features can only point to optional dependencies, in which case they\n // should have all been weeded out by the above iteration. Any remaining\n // features are bugs in that the package does not actually have those\n // features.\n if feature_deps.len() > 0 {\n let unknown = feature_deps.keys().map(|s| &s[..])\n .collect::>();\n if unknown.len() > 0 {\n let features = unknown.connect(\", \");\n return Err(human(format!(\"Package `{}` does not have these features: \\\n `{}`\", parent.package_id(), features)))\n }\n }\n\n // Record what list of features is active for this package.\n if used_features.len() > 0 {\n let pkgid = parent.package_id();\n cx.resolve.features.entry(pkgid.clone())\n .or_insert(HashSet::new())\n .extend(used_features);\n }\n\n Ok(ret)\n}\n\n// Returns a pair of (feature dependencies, all used features)\n//\n// The feature dependencies map is a mapping of package name to list of features\n// enabled. Each package should be enabled, and each package should have the\n// specified set of features enabled.\n//\n// The all used features set is the set of features which this local package had\n// enabled, which is later used when compiling to instruct the code what\n// features were enabled.\nfn build_features(s: &Summary, method: Method)\n -> CargoResult<(HashMap>, HashSet)> {\n let mut deps = HashMap::new();\n let mut used = HashSet::new();\n let mut visited = HashSet::new();\n match method {\n Method::Everything => {\n for key in s.features().keys() {\n try!(add_feature(s, key, &mut deps, &mut used, &mut visited));\n }\n for dep in s.dependencies().iter().filter(|d| d.is_optional()) {\n try!(add_feature(s, dep.name(), &mut deps, &mut used,\n &mut visited));\n }\n }\n Method::Required{features: requested_features, ..} => {\n for feat in requested_features.iter() {\n try!(add_feature(s, feat, &mut deps, &mut used, &mut visited));\n }\n }\n }\n match method {\n Method::Everything |\n Method::Required { uses_default_features: true, .. } => {\n if s.features().get(\"default\").is_some() {\n try!(add_feature(s, \"default\", &mut deps, &mut used,\n &mut visited));\n }\n }\n Method::Required { uses_default_features: false, .. } => {}\n }\n return Ok((deps, used));\n\n fn add_feature(s: &Summary, feat: &str,\n deps: &mut HashMap>,\n used: &mut HashSet,\n visited: &mut HashSet) -> CargoResult<()> {\n if feat.is_empty() { return Ok(()) }\n\n // If this feature is of the form `foo/bar`, then we just lookup package\n // `foo` and enable its feature `bar`. Otherwise this feature is of the\n // form `foo` and we need to recurse to enable the feature `foo` for our\n // own package, which may end up enabling more features or just enabling\n // a dependency.\n let mut parts = feat.splitn(2, '/');\n let feat_or_package = parts.next().unwrap();\n match parts.next() {\n Some(feat) => {\n let package = feat_or_package;\n deps.entry(package.to_string())\n .or_insert(Vec::new())\n .push(feat.to_string());\n }\n None => {\n let feat = feat_or_package;\n if !visited.insert(feat.to_string()) {\n return Err(human(format!(\"Cyclic feature dependency: \\\n feature `{}` depends on itself\",\n feat)))\n }\n used.insert(feat.to_string());\n match s.features().get(feat) {\n Some(recursive) => {\n for f in recursive {\n try!(add_feature(s, f, deps, used, visited));\n }\n }\n None => {\n deps.entry(feat.to_string()).or_insert(Vec::new());\n }\n }\n visited.remove(&feat.to_string());\n }\n }\n Ok(())\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2974,"cells":{"blob_id":{"kind":"string","value":"1b4b1f4dd67bdc635d7c5d9cf5b1e7eb4b3d0c49"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"superhawk610/too-many-lists"},"path":{"kind":"string","value":"/src/first_improved.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1590,"string":"1,590"},"score":{"kind":"number","value":3.984375,"string":"3.984375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"/// some easy improvements over `first`\n///\n/// 1) change `Link` to simply alias `Option>`\n/// 2) substitute `std::mem::replace(x, None)` with `x.take()` (yay, options!)\n/// 3) substitute `match option { None => None, Some(x) => Some(y) }` with `option.map(|x| y)`\n\npub struct List {\n head: Link,\n}\n\nstruct Node {\n elem: i32,\n next: Link,\n}\n\ntype Link = Option>;\n\nimpl List {\n pub fn new() -> Self {\n List { head: None }\n }\n\n pub fn push(&mut self, elem: i32) {\n let new_node = Box::new(Node {\n elem: elem,\n next: self.head.take(),\n });\n\n self.head = Some(new_node);\n }\n\n pub fn pop(&mut self) -> Option {\n self.pop_node().map(|node| node.elem)\n }\n\n fn pop_node(&mut self) -> Link {\n self.head.take().map(|mut node| {\n self.head = node.next.take();\n node\n })\n }\n}\n\nimpl Drop for List {\n fn drop(&mut self) {\n while let Some(_) = self.pop_node() {}\n }\n}\n\n#[cfg(test)]\nmod test {\n use super::*;\n\n #[test]\n fn basics() {\n let mut list = List::new();\n\n list.push(1);\n list.push(2);\n list.push(3);\n\n // normal removal...\n assert_eq!(list.pop(), Some(3));\n assert_eq!(list.pop(), Some(2));\n\n list.push(4);\n list.push(5);\n\n // some more normal removal...\n assert_eq!(list.pop(), Some(5));\n assert_eq!(list.pop(), Some(4));\n\n // and exhaustion...\n assert_eq!(list.pop(), Some(1));\n assert_eq!(list.pop(), None);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2975,"cells":{"blob_id":{"kind":"string","value":"c5dcb378d3f65c5222879e2c91b862b6baf218aa"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"steveklabnik/clog"},"path":{"kind":"string","value":"/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2413,"string":"2,413"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"#![crate_name = \"clog\"]\n#![comment = \"A conventional changelog generator\"]\n#![license = \"MIT\"]\n#![feature(macro_rules, phase)]\n\nextern crate regex;\n#[phase(plugin)]\nextern crate regex_macros;\nextern crate serialize;\n#[phase(plugin)] extern crate docopt_macros;\nextern crate docopt;\nextern crate time;\n\nuse git::{ LogReaderConfig };\nuse log_writer::{ LogWriter, LogWriterOptions };\nuse std::io::{File, Open, Write};\nuse docopt::FlagParser;\n\nmod common;\nmod git;\nmod log_writer;\nmod section_builder;\n\ndocopt!(Args, \"clog\n\nUsage:\n clog [--repository= --setversion= --subtitle= \n --from= --to= --from-latest-tag]\n\nOptions:\n -h --help Show this screen.\n --version Show version\n -r --repository= e.g https://github.com/thoughtram/clog\n --setversion= e.g. 0.1.0\n --subtitle= e.g. crazy-release-name\n --from= e.g. 12a8546\n --to= e.g. 8057684\n --from-latest-tag uses the latest tag as starting point. Ignores other --from parameter\")\n\nfn main () {\n\n let start_nsec = ::time::get_time().nsec;\n let args: Args = FlagParser::parse().unwrap_or_else(|e| e.exit());\n\n let log_reader_config = LogReaderConfig {\n grep: \"^feat|^fix|BREAKING'\".to_string(),\n format: \"%H%n%s%n%b%n==END==\".to_string(),\n from: if args.flag_from_latest_tag { ::git::get_latest_tag() } else { args.flag_from },\n to: args.flag_to\n };\n\n let commits = ::git::get_log_entries(log_reader_config);\n\n let sections = ::section_builder::build_sections(commits.clone());\n\n let contents = match File::open(&Path::new(\"changelog.md\")).read_to_string() {\n Ok(content) => content,\n Err(_) => \"\".to_string()\n };\n\n let mut file = File::open_mode(&Path::new(\"changelog.md\"), Open, Write).ok().unwrap();\n let mut writer = LogWriter::new(&mut file, LogWriterOptions { \n repository_link: args.flag_repository,\n version: args.flag_setversion,\n subtitle: args.flag_subtitle\n });\n\n writer.write_header();\n writer.write_section(\"Bug Fixes\", &sections.fixes);\n writer.write_section(\"Features\", &sections.features);\n writer.write(contents.as_slice());\n\n let end_nsec = ::time::get_time().nsec;\n let elapsed_mssec = (end_nsec - start_nsec) / 1000000;\n println!(\"changelog updated. (took {} ms)\", elapsed_mssec);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2976,"cells":{"blob_id":{"kind":"string","value":"62aae4363ffd1c7035a96dc556dd050825538727"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"geoffjay/codility-rs"},"path":{"kind":"string","value":"/src/binary-gap/lib.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1401,"string":"1,401"},"score":{"kind":"number","value":3.375,"string":"3.375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#![feature(test)]\n\nextern crate test;\n\npub fn solution(n: i32) -> i32 {\n let mut gap = 0;\n let mut largest = 0;\n let mut num = n;\n let mut init = false;\n loop {\n // increase gap size when number is zero, and count has been initialized\n if num & 1 == 0 {\n if init {\n gap += 1;\n }\n } else {\n if gap > largest {\n largest = gap;\n }\n gap = 0;\n // start the count once a 1 has been seen\n init = true;\n }\n num >>= 1;\n if num == 0 {\n break;\n }\n }\n largest\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use test::Bencher;\n\n #[test]\n fn it_works() {\n assert_eq!(solution(9), 2);\n assert_eq!(solution(529), 4);\n assert_eq!(solution(20), 1);\n assert_eq!(solution(15), 0);\n assert_eq!(solution(1041), 5);\n assert_eq!(solution(32), 0);\n assert_eq!(solution(0b0000), 0);\n assert_eq!(solution(0b10000), 0);\n assert_eq!(solution(0b10000000), 0);\n assert_eq!(solution(0b10000001), 6);\n }\n\n #[bench]\n #[ignore]\n fn bench_solution(b: &mut Bencher) {\n b.iter(|| solution(204913));\n }\n\n #[bench]\n #[ignore]\n fn bench_solution_many(b: &mut Bencher) {\n b.iter(|| (0..10000).map(solution).collect::>())\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2977,"cells":{"blob_id":{"kind":"string","value":"7ead7a9fcd57b7a557255d3c2f5a347291de7637"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"rust-embedded/embedded-hal"},"path":{"kind":"string","value":"/embedded-hal-nb/src/serial.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3970,"string":"3,970"},"score":{"kind":"number","value":3.421875,"string":"3.421875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","Apache-2.0","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"MIT\",\n \"Apache-2.0\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"//! Serial interface.\n\n/// Serial error.\npub trait Error: core::fmt::Debug {\n /// Convert error to a generic serial error kind\n ///\n /// By using this method, serial errors freely defined by HAL implementations\n /// can be converted to a set of generic serial errors upon which generic\n /// code can act.\n fn kind(&self) -> ErrorKind;\n}\n\nimpl Error for core::convert::Infallible {\n #[inline]\n fn kind(&self) -> ErrorKind {\n match *self {}\n }\n}\n\n/// Serial error kind.\n///\n/// This represents a common set of serial operation errors. HAL implementations are\n/// free to define more specific or additional error types. However, by providing\n/// a mapping to these common serial errors, generic code can still react to them.\n#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]\n#[non_exhaustive]\npub enum ErrorKind {\n /// The peripheral receive buffer was overrun.\n Overrun,\n /// Received data does not conform to the peripheral configuration.\n /// Can be caused by a misconfigured device on either end of the serial line.\n FrameFormat,\n /// Parity check failed.\n Parity,\n /// Serial line is too noisy to read valid data.\n Noise,\n /// A different error occurred. The original error may contain more information.\n Other,\n}\n\nimpl Error for ErrorKind {\n #[inline]\n fn kind(&self) -> ErrorKind {\n *self\n }\n}\n\nimpl core::fmt::Display for ErrorKind {\n #[inline]\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self {\n Self::Overrun => write!(f, \"The peripheral receive buffer was overrun\"),\n Self::Parity => write!(f, \"Parity check failed\"),\n Self::Noise => write!(f, \"Serial line is too noisy to read valid data\"),\n Self::FrameFormat => write!(\n f,\n \"Received data does not conform to the peripheral configuration\"\n ),\n Self::Other => write!(\n f,\n \"A different error occurred. The original error may contain more information\"\n ),\n }\n }\n}\n\n/// Serial error type trait.\n///\n/// This just defines the error type, to be used by the other traits.\npub trait ErrorType {\n /// Error type\n type Error: Error;\n}\n\nimpl ErrorType for &mut T {\n type Error = T::Error;\n}\n\n/// Read half of a serial interface.\n///\n/// Some serial interfaces support different data sizes (8 bits, 9 bits, etc.);\n/// This can be encoded in this trait via the `Word` type parameter.\npub trait Read: ErrorType {\n /// Reads a single word from the serial interface\n fn read(&mut self) -> nb::Result;\n}\n\nimpl + ?Sized, Word: Copy> Read for &mut T {\n #[inline]\n fn read(&mut self) -> nb::Result {\n T::read(self)\n }\n}\n\n/// Write half of a serial interface.\npub trait Write: ErrorType {\n /// Writes a single word to the serial interface.\n fn write(&mut self, word: Word) -> nb::Result<(), Self::Error>;\n\n /// Ensures that none of the previously written words are still buffered.\n fn flush(&mut self) -> nb::Result<(), Self::Error>;\n}\n\nimpl + ?Sized, Word: Copy> Write for &mut T {\n #[inline]\n fn write(&mut self, word: Word) -> nb::Result<(), Self::Error> {\n T::write(self, word)\n }\n\n #[inline]\n fn flush(&mut self) -> nb::Result<(), Self::Error> {\n T::flush(self)\n }\n}\n\n/// Implementation of `core::fmt::Write` for the HAL's `serial::Write`.\n///\n/// TODO write example of usage\n\nimpl core::fmt::Write for dyn Write + '_\nwhere\n Word: Copy + From,\n{\n #[inline]\n fn write_str(&mut self, s: &str) -> core::fmt::Result {\n let _ = s\n .bytes()\n .map(|c| nb::block!(self.write(Word::from(c))))\n .last();\n Ok(())\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2978,"cells":{"blob_id":{"kind":"string","value":"963697e7187c6fc18e4ed1c62c6b6aff79afb9cb"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"MiyamonY/atcoder"},"path":{"kind":"string","value":"/abc/036/d/01/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2655,"string":"2,655"},"score":{"kind":"number","value":2.859375,"string":"2.859375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"#[allow(unused_macros)]\nmacro_rules! scan {\n () => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().to_string()\n }\n };\n (;;) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().split_whitespace().map(|s| s.to_string()).collect::>()\n }\n };\n (;;$n:expr) => {\n {\n (0..$n).map(|_| scan!()).collect::>()\n }\n };\n ($t:ty) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.trim().parse::<$t>().unwrap()\n }\n };\n ($($t:ty),*) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n let mut iter = line.split_whitespace();\n (\n $(iter.next().unwrap().parse::<$t>().unwrap(),)*\n )\n }\n };\n ($t:ty;;) => {\n {\n let mut line: String = String::new();\n std::io::stdin().read_line(&mut line).unwrap();\n line.split_whitespace()\n .map(|t| t.parse::<$t>().unwrap())\n .collect::>()\n }\n };\n ($t:ty;;$n:expr) => {\n (0..$n).map(|_| scan!($t;;)).collect::>()\n };\n ($t:ty; $n:expr) => {\n (0..$n).map(|_|\n scan!($t)\n ).collect::>()\n };\n ($($t:ty),*; $n:expr) => {\n (0..$n).map(|_|\n scan!($($t),*)\n ).collect::>()\n };\n}\n\nconst MOD: i64 = 1_000_000_007;\n\nfn dfs_w(graph: &[Vec], p: usize, n: usize, dp: &mut [Option]) -> i64 {\n let mut whites = 1;\n for &g in &graph[n] {\n if g != p {\n whites *= dfs(graph, n, g, dp);\n whites %= MOD;\n }\n }\n whites\n}\n\nfn dfs(graph: &[Vec], p: usize, n: usize, dp: &mut [Option]) -> i64 {\n if let Some(v) = dp[n] {\n return v;\n }\n\n let mut whites = 1;\n for &g in &graph[n] {\n if g != p {\n whites *= dfs_w(graph, n, g, dp);\n whites %= MOD;\n }\n }\n let v = (dfs_w(graph, p, n, dp) + whites) % MOD;\n dp[n] = Some(v);\n v\n}\n\nfn main() {\n let n = scan!(usize);\n\n let mut graph = vec![vec![]; n + 1];\n for _ in 0..n - 1 {\n let (a, b) = scan!(usize, usize);\n graph[a].push(b);\n graph[b].push(a);\n }\n\n let mut dp = vec![None; n + 1];\n println!(\"{}\", dfs(&graph, 0, 1, &mut dp));\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2979,"cells":{"blob_id":{"kind":"string","value":"c476bad1aefaa05cf003fa16b01a4248b0e75bc9"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"liu-hz18/rCore-v2"},"path":{"kind":"string","value":"/src/process/kernel_stack.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3748,"string":"3,748"},"score":{"kind":"number","value":3.5,"string":"3.5"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"//! 内核栈 [`KernelStack`]\r\n//!\r\n//! 用户态的线程出现中断时,因为用户栈无法保证可用性,中断处理流程必须在内核栈上进行。\r\n//! 所以我们创建一个公用的内核栈,即当发生中断时,会将 Context 写到内核栈顶。\r\n//!\r\n//! ### 线程 [`Context`] 的存放\r\n//! > 1. 线程初始化时,一个 `Context` 放置在内核栈顶,`sp` 指向 `Context` 的位置\r\n//! > (即 栈顶 - `size_of::()`)\r\n//! > 2. 切换到线程,执行 `__restore` 时,将 `Context` 的数据恢复到寄存器中后,\r\n//! > 会将 `Context` 出栈(即 `sp += size_of::()`),\r\n//! > 然后保存 `sp` 至 `sscratch`(此时 `sscratch` 即为内核栈顶)\r\n//! > 3. 发生中断时,将 `sscratch` 和 `sp` 互换,入栈一个 `Context` 并保存数据\r\n//!\r\n//! 容易发现,线程的 `Context` 一定保存在内核栈顶。因此,当线程需要运行(切换到)时,\r\n//! 从 [`Thread`] 中取出 `Context` 然后置于内核栈顶即可\r\n\r\n// 做法:\r\n// 1. 预留一段空间作为内核栈\r\n// 2. 运行线程时,在 sscratch 寄存器中保存内核栈顶指针\r\n// 3. 如果线程遇到中断,则将 Context 压入 sscratch 指向的栈中(Context 的地址为 sscratch - size_of::()),同时用新的栈地址来替换 sp(此时 sp 也会被复制到 a0 作为 handle_interrupt 的参数)\r\n// 4. 从中断中返回时(__restore 时),a0 应指向被压在内核栈中的 Context。此时出栈 Context 并且将栈顶保存到 sscratch 中\r\n\r\nuse super::*;\r\nuse core::mem::size_of;\r\n\r\n/// 内核栈\r\n#[repr(align(16))]\r\n#[repr(C)]\r\npub struct KernelStack([u8; KERNEL_STACK_SIZE]);\r\n\r\n/// 公用的内核栈\r\npub static mut KERNEL_STACK: KernelStack = KernelStack([0; KERNEL_STACK_SIZE]);\r\n\r\n// 创建线程时,需要使用的操作就是在内核栈顶压入一个初始状态 Context\r\nimpl KernelStack {\r\n /// 在栈顶加入 Context 并且返回新的栈顶指针\r\n pub fn push_context(&mut self, context: Context) -> *mut Context {\r\n // 栈顶sp\r\n let stack_top = &self.0 as *const _ as usize + size_of::();\r\n // Context 的位置\r\n let push_address = (stack_top - size_of::()) as *mut Context; // 编译器负责解析这个指针\r\n // Context 压入栈顶\r\n unsafe {\r\n *push_address = context; // 编译器负责对内存对应位置依次赋值\r\n }\r\n push_address\r\n }\r\n}\r\n\r\n// 关于内核栈(和sscratch)的作用的探讨:\r\n/*\r\n 如果不使用 sscratch 提供内核栈,而是像原来一样,遇到中断就直接将上下文压栈, 会有什么问题?\r\n 1. 一种情况不会出现问题: 只运行一个非常善意的线程,比如 loop {}\r\n 2. 一种情况导致异常无法处理(指无法进入 handle_interrupt):\r\n 线程把自己的 sp 搞丢了,比如 mv sp, x0。此时无法保存寄存器,也没有能够支持操作系统正常运行的栈\r\n 3. 一种情况导致产生嵌套异常(指第二个异常能够进行到调用 handle_interrupt 时,不考虑后续执行情况)\r\n 运行两个线程。在两个线程切换的时候,会需要切换页表。但是此时操作系统运行在前一个线程的栈上,一旦切换,再访问栈就会导致缺页,因为每个线程的栈只在自己的页表中\r\n 4. 一种情况导致一个用户进程(先不考虑是怎么来的)可以将自己变为内核进程,或以内核态执行自己的代码\r\n 用户进程巧妙地设计 sp,使得它恰好落在内核的某些变量附近,于是在保存寄存器时就修改了变量的值。这相当于任意修改操作系统的控制信息\r\n*/\r\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2980,"cells":{"blob_id":{"kind":"string","value":"c35f2531daf6327618f829e4d7e15ea4dc61309f"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"gdoct/rustvm"},"path":{"kind":"string","value":"/src/instructions/asl.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2522,"string":"2,522"},"score":{"kind":"number","value":3.140625,"string":"3.140625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause"],"string":"[\n \"BSD-3-Clause\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use crate::traits::{ Instruction, VirtualCpu };\nuse crate::types::{ Byte };\nuse crate::instructions::generic::*;\n\nfn asl(cpu: &mut dyn VirtualCpu, num: Byte, with: Byte) {\n let asl = num << with;\n cpu.set_a(asl);\n}\n\n/// AslZp: ASL zeropage\n/// Arithmetic Shift Left (ASL) operation between \n/// the content of Accumulator and the content of \n/// the zero page address\npub struct AslZp { }\nimpl Instruction for AslZp {\n fn opcode (&self) -> &'static str { \"ASL\"}\n fn hexcode(&self) -> Byte { 0x06 }\n fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> {\n let zp = fetch_zp_val(cpu)?;\n let a = cpu.get_a();\n asl(cpu, a, zp);\n Ok(())\n }\n}\n\n/// Asl: ASL \n/// Arithmetic Shift Left (ASL) operation between immediate val\n/// and the content of the Accumulator\npub struct Asl { }\nimpl Instruction for Asl {\n fn opcode (&self) -> &'static str { \"ASL\"}\n fn hexcode(&self) -> Byte { 0x0A }\n fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> {\n let imm = fetch_imm_val(cpu)?;\n let a = cpu.get_a();\n asl(cpu, imm, a);\n Ok(())\n }\n}\n\n/// AslAbs: ASL absolute\n/// Arithmetic Shift Left (ASL) operation between the content of \n/// Accumulator and the content located at address $1234\npub struct AslAbs { }\nimpl Instruction for AslAbs {\n fn opcode (&self) -> &'static str { \"ASL\"}\n fn hexcode(&self) -> Byte { 0x0E }\n fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> {\n let val = fetch_abs_val(cpu)?;\n let a = cpu.get_a();\n asl(cpu, a, val);\n Ok(())\n }\n}\n\n/// AslZpX: ASL absolute, indexed by X\npub struct AslZpX { }\nimpl Instruction for AslZpX {\n fn opcode (&self) -> &'static str { \"ASL\"}\n fn hexcode(&self) -> Byte { 0x16 }\n fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> {\n let val = fetch_absx_val(cpu)?;\n let a = cpu.get_a();\n asl(cpu, a, val);\n Ok(())\n }\n}\n\n/// AslAbsX: ASL absolute, indexed by X\n/// Arithmetic Shift Left (ASL) operation between the content of Accumulator and the content \n/// located at address calculated from $1234 adding content of X\npub struct AslAbsX { }\nimpl Instruction for AslAbsX {\n fn opcode (&self) -> &'static str { \"ASL\"}\n fn hexcode(&self) -> Byte { 0x1E }\n fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> {\n let val = fetch_absx_val(cpu)?;\n let a = cpu.get_a();\n asl(cpu, a, val);\n Ok(())\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2981,"cells":{"blob_id":{"kind":"string","value":"f7d335dc73bf00f15287442fb8a40d2d3abe1ccc"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"jamestthompson3/subtxt-rs"},"path":{"kind":"string","value":"/src/lib.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2535,"string":"2,535"},"score":{"kind":"number","value":3.75,"string":"3.75"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"pub struct Parser<'a> {\n input: std::str::Lines<'a>,\n}\n\nimpl<'a> Parser<'a> {\n pub fn new(text: &'a str) -> Self {\n Self {\n input: text.lines(),\n }\n }\n}\n\nimpl<'a> Iterator for Parser<'a> {\n type Item = Event<'a>;\n fn next(&mut self) -> Option {\n match self.input.next() {\n Some(line) => {\n if line.is_empty() {\n return Some(Event::Empty);\n }\n let mut chars = line.chars();\n match (chars.next().unwrap(), chars.next().unwrap()) {\n ('#', ' ') => Some(Event::Heading(line.split_at(2).1)),\n ('-', ' ') => Some(Event::List(line.split_at(2).1)),\n ('&', ' ') => Some(Event::Link(line.split_at(2).1)),\n ('>', ' ') => Some(Event::Quote(line.split_at(2).1)),\n _ => Some(Event::Text(line)),\n }\n }\n None => None,\n }\n }\n}\n\n#[derive(Debug, PartialEq)]\npub enum Event<'a> {\n Heading(&'a str),\n Text(&'a str),\n List(&'a str),\n Quote(&'a str),\n Link(&'a str),\n Empty,\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn parse_normal_input() {\n let test_string = \"# Heading\\n- List1\";\n let parser = Parser::new(test_string);\n let events = parser.collect::>();\n\n assert_eq!(events[0], Event::Heading(\"Heading\"));\n assert_eq!(events[1], Event::List(\"List1\"));\n }\n\n #[test]\n fn parse_malformed_input() {\n let test_string = \"# \";\n let parser = Parser::new(test_string);\n let events = parser.collect::>();\n\n assert_eq!(events[0], Event::Heading(\"\"));\n }\n\n #[test]\n fn parse_malformed_and_normal_input() {\n let test_string = \"# \\n- List1\";\n let parser = Parser::new(test_string);\n let events = parser.collect::>();\n\n assert_eq!(events[0], Event::Heading(\"\"));\n assert_eq!(events[1], Event::List(\"List1\"));\n }\n\n #[test]\n fn parse_typo_input() {\n let test_string = \"-List1\";\n let parser = Parser::new(test_string);\n let events = parser.collect::>();\n\n assert_eq!(events[0], Event::Text(\"-List1\"));\n }\n\n #[test]\n fn parse_empty_lines() {\n let test_string = \"asdf\\n\\nasdf\";\n let parser = Parser::new(test_string);\n let events = parser.collect::>();\n\n assert_eq!(events[1], Event::Empty);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2982,"cells":{"blob_id":{"kind":"string","value":"31e738f9fca604d1584626d02ea022781ef862b6"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"SymmetricChaos/project_euler_rust"},"path":{"kind":"string","value":"/src/worked_problems/euler_76.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2993,"string":"2,993"},"score":{"kind":"number","value":3.5625,"string":"3.5625"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"// Problem: How many different ways can one hundred be written as a sum of at least two positive integers?\n/*\n*/\n\nstruct AllIntegers {\n ctr: i64,\n parity: u8,\n} \n\nimpl Iterator for AllIntegers {\n type Item = i64;\n\n fn next(&mut self) -> Option {\n if self.parity == 0 {\n self.parity = 1;\n return Some(self.ctr)\n } else {\n self.parity = 0;\n self.ctr += 1;\n return Some(-(self.ctr-1))\n }\n }\n}\n\nfn gen_pentagonal(n: i64) -> i64 {\n (3*n*n-n)/2\n}\n\npub fn euler76() -> u64 {\n let mut known_partitions = [0i64;101];\n known_partitions[0] = 1;\n known_partitions[1] = 1;\n\n for n in 2..=100 {\n let mut ctr = AllIntegers{ctr: 1, parity: 0};\n let mut p = gen_pentagonal(ctr.next().unwrap());\n let mut sum = 0;\n let mut sign = [1,1,-1,-1].iter().cycle();\n while p <= n {\n sum += known_partitions[(n-p) as usize]*sign.next().unwrap();\n p = gen_pentagonal(ctr.next().unwrap());\n }\n known_partitions[n as usize] = sum\n }\n\n // We need to subtract 1 because the partitions we calculated include the number itself as a partition\n (known_partitions[100]-1) as u64\n}\n\n\npub fn euler76_example() {\n println!(\"\\nProblem: How many different ways can one hundred be written as a sum of at least two positive integers?\");\n println!(\"\\n\\nThis could possibly be done using brute force to calculate partitions of each integer and then memoizing the results. However Euler's Pentagonal Number Theorem gives us a much more efficient option where we don't need to brute force calculate any partitions except for 0 and 1, which both have a single partition.\");\n let s = \"\nstruct AllIntegers {\n ctr: i64,\n parity: u8,\n} \n\nimpl Iterator for AllIntegers {\n type Item = i64;\n\n fn next(&mut self) -> Option {\n if self.parity == 0 {\n self.parity = 1;\n return Some(self.ctr)\n } else {\n self.parity = 0;\n self.ctr += 1;\n return Some(-(self.ctr-1))\n }\n }\n}\n\nfn gen_pentagonal(n: i64) -> i64 {\n (3*n*n-n)/2\n}\n\npub fn euler76() -> u64 {\n let mut known_partitions = [0i64;101];\n known_partitions[0] = 1;\n known_partitions[1] = 1;\n\n for n in 2..=100 {\n let mut ctr = AllIntegers{ctr: 1, parity: 0};\n let mut p = gen_pentagonal(ctr.next().unwrap());\n let mut sum = 0;\n let mut sign = [1,1,-1,-1].iter().cycle();\n while p <= n {\n sum += known_partitions[(n-p) as usize]*sign.next().unwrap();\n p = gen_pentagonal(ctr.next().unwrap());\n }\n known_partitions[n as usize] = sum\n }\n\n // We need to subtract 1 because the partitions we calculated include the number itself as a partition\n (known_partitions[100]-1) as u64\n}\";\n println!(\"\\n{}\\n\",s);\n println!(\"The answer is: {}\",euler76());\n}\n\n\n#[test]\nfn test76() {\n assert_eq!(euler76(),190569291)\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2983,"cells":{"blob_id":{"kind":"string","value":"6d6eb9ccc92b1b7c0c047bbda5e8f96466302ad9"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"mandx/harplay"},"path":{"kind":"string","value":"/src/har/mod.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1559,"string":"1,559"},"score":{"kind":"number","value":2.9375,"string":"2.9375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"pub mod errors;\npub mod generic;\n\nuse std::fs::File;\nuse std::io::{BufReader, Read};\nuse std::path::Path;\n\nuse serde::{Deserialize, Serialize};\n\npub use errors::HarError;\nuse errors::*;\npub use generic::*;\n\n#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]\npub struct Har {\n pub log: Log,\n}\n\n/// Deserialize a HAR from a path\n#[cfg_attr(tarpaulin, skip)]\npub fn from_path>(path: P) -> Result {\n from_reader(BufReader::new(File::open(path).context(Opening)?))\n}\n\n/// Deserialize a HAR from type which implements Read\npub fn from_reader(read: R) -> Result {\n Ok(serde_json::from_reader::(read).context(Reading)?)\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use assert_matches::assert_matches;\n\n #[test]\n fn load_from_not_json_or_har() {\n let json = br#\"{\"some\": \"json\"}\"#;\n assert_matches!(from_reader(&json[..]), Err(_));\n let json = br#\"{\"log\": {}}\"#;\n assert_matches!(from_reader(&json[..]), Err(_));\n let json = br#\"{\"log\":{\"version\":\"1.2\",\"pages\":[],\"entries\":[]}}\"#;\n assert_matches!(from_reader(&json[..]), Err(_));\n }\n\n #[test]\n fn load_from_har() {\n let json =\n br#\"{\"log\":{\"creator\":{\"name\":\"Creator?\",\"version\":\"0.1\"},\"pages\":[],\"entries\":[]}}\"#;\n assert_matches!(from_reader(&json[..]), Ok(_));\n let json = br#\"{\"log\":{\"version\":\"1.2\",\"creator\":{\"name\":\"Creator?\",\"version\":\"0.1\"},\"pages\":[],\"entries\":[]}}\"#;\n assert_matches!(from_reader(&json[..]), Ok(_));\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2984,"cells":{"blob_id":{"kind":"string","value":"4f1f7675a2b1b60a4e4a2ee34b4bc0918db7bf77"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"arielb1/rustc-perf-collector"},"path":{"kind":"string","value":"/src/execute.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3855,"string":"3,855"},"score":{"kind":"number","value":2.609375,"string":"2.609375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"//! Execute benchmarks in a sysroot.\n\nuse std::str;\nuse std::path::{Path, PathBuf};\nuse std::process::Command;\n\nuse tempdir::TempDir;\n\nuse rustc_perf_collector::{Patch, Run};\n\nuse errors::{Result, ResultExt};\nuse rust_sysroot::sysroot::Sysroot;\nuse time_passes::{PassAverager, process_output};\n\npub struct Benchmark {\n pub name: String,\n pub path: PathBuf\n}\n\nimpl Benchmark {\n pub fn command>(&self, sysroot: &Sysroot, path: P) -> Command {\n let mut command = sysroot.command(path);\n command.current_dir(&self.path);\n command\n }\n\n /// Run a specific benchmark on a specific commit\n pub fn run(&self, sysroot: &Sysroot) -> Result> {\n info!(\"processing {}\", self.name);\n\n let mut patch_runs: Vec = Vec::new();\n for _ in 0..3 {\n let tmp_dir = TempDir::new(&format!(\"rustc-benchmark-{}\", self.name))?;\n info!(\"temporary directory is {}\", tmp_dir.path().display());\n\n info!(\"copying files to temporary directory\");\n let output = self.command(sysroot, \"cp\").arg(\"-r\").arg(\"-T\").arg(\"--\")\n .arg(\".\").arg(tmp_dir.path()).output()?;\n\n if !output.status.success() {\n bail!(\"copy failed: {}\", String::from_utf8_lossy(&output.stderr));\n }\n let make = || {\n let mut command = sysroot.command(\"make\");\n command.current_dir(tmp_dir.path());\n command\n };\n\n let output = make().arg(\"patches\").output()?;\n let mut patches = str::from_utf8(&output.stdout)\n .chain_err(|| format!(\"make patches in {} returned non UTF-8 output\", self.path.display()))?\n .split_whitespace()\n .collect::>();\n if patches.is_empty() {\n patches.push(\"\");\n }\n\n for patch in &patches {\n info!(\"running `make all{}`\", patch);\n let output = make().arg(&format!(\"all{}\", patch))\n .env(\"CARGO_OPTS\", \"\")\n .env(\"CARGO_RUSTC_OPTS\", \"-Z time-passes\")\n .output()?;\n\n if !output.status.success() {\n bail!(\"stderr non empty: {},\\n\\n stdout={}\",\n String::from_utf8_lossy(&output.stderr),\n String::from_utf8_lossy(&output.stdout)\n );\n }\n\n let patch_index = if let Some(p) = patch_runs.iter().position(|p_run| p_run.patch == *patch) {\n p\n } else {\n patch_runs.push(Patch {\n patch: patch.to_string(),\n name: self.name.clone(),\n runs: Vec::new(),\n });\n patch_runs.len() - 1\n };\n\n let combined_name = format!(\"{}{}\", self.name, patch);\n patch_runs[patch_index].runs.push(Run {\n passes: process_output(&combined_name, output.stdout)?,\n name: combined_name,\n });\n }\n }\n\n let mut patches = Vec::new();\n for patch_run in patch_runs {\n let mut runs = patch_run.runs.into_iter();\n let mut pa = PassAverager::new(runs.next().unwrap().passes);\n for run in runs {\n pa.average_with(run.passes)?;\n }\n patches.push(Patch {\n name: patch_run.name.clone(),\n patch: patch_run.patch.clone(),\n runs: vec![\n Run {\n name: patch_run.name + &patch_run.patch,\n passes: pa.state,\n }\n ],\n });\n }\n\n Ok(patches)\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2985,"cells":{"blob_id":{"kind":"string","value":"9dbba9ca63b7899339ef99ae88d923535b42df89"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"matthew86707/PDESimulator"},"path":{"kind":"string","value":"/PDESimulator/src/simulation.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3612,"string":"3,612"},"score":{"kind":"number","value":2.890625,"string":"2.890625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::sync::{Arc, Mutex};\nuse std::time::{Duration, Instant};\nuse std::{thread, time};\n\npub fn simulation_loop(display_values_mutex : Arc>, GRID_SIZE_X : usize, GRID_SIZE_Y : usize){\n let TIME_SAMPLES_PER_PRINTOUT : u32 = 100;\n let mut time_samples : u32 = 0;\n let mut time_acc : u32 = 0;\n let mut tick_number : u32 = 0;\n\n loop {\n let start = Instant::now();\n\n {\n let mut old_values = display_values_mutex.lock().unwrap();\n let new_values = heat_simulation_loop(block_array(*old_values), tick_number);\n tick_number += 1;\n *old_values = serialize_array(new_values);\n }\n\n time_acc += Instant::now().duration_since(start).subsec_millis();\n if (time_samples == TIME_SAMPLES_PER_PRINTOUT){\n println!(\"Delay : {}ms\", time_acc as f32 / TIME_SAMPLES_PER_PRINTOUT as f32);\n time_samples = 0;\n time_acc = 0;\n }\n time_samples += 1;\n \n let ten_millis = time::Duration::from_millis(5);\n thread::sleep(ten_millis);\n\n }\n }\n\n\nfn heat_simulation_loop(data : [[f32; 100];150], tick_number : u32) -> [[f32; 100];150] {\n let mut next_data : [[f32; 100];150] = data;\n //Actual simulation code\n {\n /*\n Heat equation : du/dt - (du/dx)^2, where u = temperature, t = time, and x = our spacial domain\n which, solved for du/dt : du/dt = (du/dx)^2\n expanding spacial domain and therefor it's derivitive into two dimensions : du/dt = (du/dx)^2 + (du/dy)^2\n\n From this PDE we can use the central difference method to approximate the 2nd spacial derivitives...\n \n From the difference quotient of the first derivitive...\n f(x - h) - f(x + h) / 2h\n We then derive the difference quotient of the 2nd derivitive...\n f(x - h) - 2 * f(x) + f(x + h) / h^2\n In code, this recurrence equation implies...\n next_data[i][j] += ((data[i + 1][j] - (2.0 * data[i][j]) + data[i - 1][j]) + (data[i][j + 1] - (2.0 * data[i][j]) + data[i][j - 1])) / h ^ 2; \n Which is seen implemented below.\n\n A note on boundry conditions : \n First derivitive boundry conditions set du/dx on all walls to be 0.5\n\n */\n for i in 0..150 - 1{\n for j in 0..100 - 1{\n if i == 0 || i == 150 || j == 0 || j == 100{\n //next_data[i][j] = 0.5;\n }else{\n next_data[i][j] += ((data[i + 1][j] - (2.0 * data[i][j]) + data[i - 1][j]) + (data[i][j + 1] - (2.0 * data[i][j]) + data[i][j - 1])) / 4.00; \n }\n }\n }\n if(tick_number < 200){\n next_data[75][20] = 1.0;\n next_data[75][40] = 1.0;\n next_data[75][60] = 1.0;\n next_data[75][80] = 1.0;\n\n next_data[95][20] = 1.0;\n next_data[95][40] = 1.0;\n next_data[95][60] = 1.0;\n next_data[95][80] = 1.0;\n }\n }\n return next_data;\n}\n\n\nfn serialize_array(array : [[f32; 100];150]) -> [f32; 15000]{\n let mut to_return : [f32; 15000] = [0.0; 15000];\n for i in 0..to_return.len() {\n to_return[i] = array[i % 150][i / 150];\n }\n return to_return;\n}\n\nfn block_array(array : [f32; 15000]) -> [[f32; 100];150]{\n let mut to_return : [[f32; 100];150] = [[0.0; 100]; 150];\n for i in 0..150{\n for j in 0..100{\n to_return[i][j] = array[j * 150 + i];\n }\n }\n return to_return;\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2986,"cells":{"blob_id":{"kind":"string","value":"1f4d83c360620fae73a2f35780e132c22c51605e"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"kroeckx/ruma"},"path":{"kind":"string","value":"/crates/ruma-events/src/room/redaction.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2461,"string":"2,461"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"//! Types for the *m.room.redaction* event.\n\nuse ruma_common::MilliSecondsSinceUnixEpoch;\nuse ruma_events_macros::{Event, EventContent};\nuse ruma_identifiers::{EventId, RoomId, UserId};\nuse serde::{Deserialize, Serialize};\n\nuse crate::Unsigned;\n\n/// Redaction event.\n#[derive(Clone, Debug, Event)]\n#[allow(clippy::exhaustive_structs)]\npub struct RedactionEvent {\n /// Data specific to the event type.\n pub content: RedactionEventContent,\n\n /// The ID of the event that was redacted.\n pub redacts: EventId,\n\n /// The globally unique event identifier for the user who sent the event.\n pub event_id: EventId,\n\n /// The fully-qualified ID of the user who sent this event.\n pub sender: UserId,\n\n /// Timestamp in milliseconds on originating homeserver when this event was sent.\n pub origin_server_ts: MilliSecondsSinceUnixEpoch,\n\n /// The ID of the room associated with this event.\n pub room_id: RoomId,\n\n /// Additional key-value pairs not signed by the homeserver.\n pub unsigned: Unsigned,\n}\n\n/// Redaction event without a `room_id`.\n#[derive(Clone, Debug, Event)]\n#[allow(clippy::exhaustive_structs)]\npub struct SyncRedactionEvent {\n /// Data specific to the event type.\n pub content: RedactionEventContent,\n\n /// The ID of the event that was redacted.\n pub redacts: EventId,\n\n /// The globally unique event identifier for the user who sent the event.\n pub event_id: EventId,\n\n /// The fully-qualified ID of the user who sent this event.\n pub sender: UserId,\n\n /// Timestamp in milliseconds on originating homeserver when this event was sent.\n pub origin_server_ts: MilliSecondsSinceUnixEpoch,\n\n /// Additional key-value pairs not signed by the homeserver.\n pub unsigned: Unsigned,\n}\n\n/// A redaction of an event.\n#[derive(Clone, Debug, Default, Deserialize, Serialize, EventContent)]\n#[cfg_attr(not(feature = \"unstable-exhaustive-types\"), non_exhaustive)]\n#[ruma_event(type = \"m.room.redaction\", kind = Message)]\npub struct RedactionEventContent {\n /// The reason for the redaction, if any.\n #[serde(skip_serializing_if = \"Option::is_none\")]\n pub reason: Option,\n}\n\nimpl RedactionEventContent {\n /// Creates an empty `RedactionEventContent`.\n pub fn new() -> Self {\n Self::default()\n }\n\n /// Creates a new `RedactionEventContent` with the given reason.\n pub fn with_reason(reason: String) -> Self {\n Self { reason: Some(reason) }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2987,"cells":{"blob_id":{"kind":"string","value":"072a8fb46341d51bd070b776ebd1071a560ab6dc"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"KrutNA/huffman-coding"},"path":{"kind":"string","value":"/src/queue.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":462,"string":"462"},"score":{"kind":"number","value":2.640625,"string":"2.640625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use crate::types::node::*;\n\nuse std::collections::BinaryHeap;\n\npub fn update_with_data(heap_buffer: &mut [u32], data: &[u8]) {\n for &byte in data.iter() {\n\theap_buffer[byte as usize] += 1;\n }\n}\n\npub fn convert_to_heap(\n heap_buffer: &mut [u32]\n)\n -> BinaryHeap\n{\n heap_buffer.iter().enumerate().filter_map(|(data, &priority)| {\n\tif priority > 0 { Some(Element::new_with_priority(data as u8, priority)) }\n\telse { None }\n }).collect()\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2988,"cells":{"blob_id":{"kind":"string","value":"2706201ef1c85ac4eb4e84369f6783e76f71263d"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"KadoBOT/exercism-rust"},"path":{"kind":"string","value":"/diamond/src/lib.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":705,"string":"705"},"score":{"kind":"number","value":3.203125,"string":"3.203125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"pub fn get_diamond(c: char) -> Vec {\n let distance = ((c as u8) - b'A') as usize;\n let mut result = vec![\" \".repeat(distance + distance + 1); distance + distance + 1];\n let size = result.len();\n\n let mut replace_char = |idx: usize, pos: usize, ch: char| {\n result[idx].replace_range(pos..=pos, &ch.to_string());\n };\n\n let mut replace_row = |idx: usize, n: usize| {\n replace_char(idx, distance - n, (b'A' + n as u8) as char);\n replace_char(idx, distance + n, (b'A' + n as u8) as char);\n };\n\n (0..=distance).for_each(|n| {\n let tail = (size - n) - 1;\n replace_row(n as usize, n);\n replace_row(tail as usize, n);\n });\n result\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2989,"cells":{"blob_id":{"kind":"string","value":"a988a03a0c59f16e3b29b0bf32f34af8acf6ac10"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"andrew-johnson-4/rdxl_internals"},"path":{"kind":"string","value":"/src/xtext_crumb.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2887,"string":"2,887"},"score":{"kind":"number","value":2.5625,"string":"2.5625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT","Apache-2.0"],"string":"[\n \"MIT\",\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"\n// Copyright 2020, The rdxl Project Developers.\n// Dual Licensed under the MIT license and the Apache 2.0 license,\n// see the LICENSE file or \n// also see LICENSE2 file or \n\nuse quote::{quote_spanned, ToTokens};\nuse proc_macro2::{Span, Literal};\nuse syn::parse::{Parse, ParseStream, Result};\nuse syn::{Token};\nuse syn::token::{Bracket,Brace};\n\nuse crate::core::{TokenAsLiteral};\nuse crate::xtext::{XtextTag,XtextExpr,BracketedExpr,XtextClass};\n\npub enum XtextCrumb {\n S(String, Span),\n T(XtextTag),\n E(XtextExpr),\n F(BracketedExpr),\n C(XtextClass)\n}\n\nimpl XtextCrumb {\n pub fn span(&self) -> Span {\n match self {\n XtextCrumb::S(_,sp) => { sp.clone() }\n XtextCrumb::T(t) => { t.outer_span.clone() }\n XtextCrumb::E(e) => { e.brace_token1.span.clone() }\n XtextCrumb::F(f) => { f.span() }\n XtextCrumb::C(c) => { c.open.span.join(c.close.span).unwrap_or(c.open.span) }\n }\n }\n pub fn parse_outer(input: ParseStream) -> Result> {\n let mut cs = vec!();\n while !input.is_empty() &&\n !(input.peek(Token![<]) && input.peek2(Token![/])) {\n let c: XtextCrumb = input.parse()?;\n cs.push(c);\n }\n Ok(cs)\n }\n}\n\nimpl Parse for XtextCrumb {\n fn parse(input: ParseStream) -> Result {\n if input.peek(Token![<]) && input.peek2(Token![!]) {\n let c: XtextClass = input.parse()?;\n Ok(XtextCrumb::C(c))\n } else if input.peek(Token![<]) {\n let t: XtextTag = input.parse()?;\n Ok(XtextCrumb::T(t))\n } else if input.peek(Bracket) {\n let f: BracketedExpr = BracketedExpr::parse(\"markup\".to_string(),input)?;\n Ok(XtextCrumb::F(f))\n } else if input.peek(Brace) {\n let e: XtextExpr = input.parse()?;\n Ok(XtextCrumb::E(e))\n } else {\n let t: TokenAsLiteral = input.parse()?;\n Ok(XtextCrumb::S(t.token_literal, t.span))\n }\n }\n}\n\nimpl ToTokens for XtextCrumb {\n fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {\n match self {\n XtextCrumb::S(s,span) => {\n let l = Literal::string(&s);\n (quote_spanned!{span.clone()=>\n stream.push_str(#l);\n }).to_tokens(tokens);\n },\n XtextCrumb::T(t) => {\n t.to_tokens(tokens);\n }\n XtextCrumb::E(e) => {\n e.to_tokens(tokens);\n }\n XtextCrumb::F(e) => {\n e.to_tokens(tokens);\n }\n XtextCrumb::C(c) => {\n let span = c.span();\n (quote_spanned!{span=>\n stream.push_str(&#c.to_string());\n }).to_tokens(tokens);\n }\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2990,"cells":{"blob_id":{"kind":"string","value":"35e07ed8d1c382e5e625ba0beb0438033033b0fe"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"doytsujin/yew"},"path":{"kind":"string","value":"/packages/yew/src/functional/hooks/use_transitive_state/feat_ssr.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2278,"string":"2,278"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0","MIT"],"string":"[\n \"Apache-2.0\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"//! The server-side rendering variant.\n\nuse std::cell::RefCell;\nuse std::rc::Rc;\n\nuse base64ct::{Base64, Encoding};\nuse serde::de::DeserializeOwned;\nuse serde::Serialize;\n\nuse crate::functional::{Hook, HookContext, PreparedState};\nuse crate::suspense::SuspensionResult;\n\npub(super) struct TransitiveStateBase\nwhere\n D: Serialize + DeserializeOwned + PartialEq + 'static,\n T: Serialize + DeserializeOwned + 'static,\n F: 'static + FnOnce(Rc) -> T,\n{\n pub state_fn: RefCell>,\n pub deps: Rc,\n}\n\nimpl PreparedState for TransitiveStateBase\nwhere\n D: Serialize + DeserializeOwned + PartialEq + 'static,\n T: Serialize + DeserializeOwned + 'static,\n F: 'static + FnOnce(Rc) -> T,\n{\n fn prepare(&self) -> String {\n let f = self.state_fn.borrow_mut().take().unwrap();\n let state = f(self.deps.clone());\n\n let state = bincode::serialize(&(Some(&state), Some(&*self.deps)))\n .expect(\"failed to prepare state\");\n\n Base64::encode_string(&state)\n }\n}\n\n#[doc(hidden)]\npub fn use_transitive_state(\n f: F,\n deps: D,\n) -> impl Hook>>>\nwhere\n D: Serialize + DeserializeOwned + PartialEq + 'static,\n T: Serialize + DeserializeOwned + 'static,\n F: 'static + FnOnce(Rc) -> T,\n{\n struct HookProvider\n where\n D: Serialize + DeserializeOwned + PartialEq + 'static,\n T: Serialize + DeserializeOwned + 'static,\n F: 'static + FnOnce(Rc) -> T,\n {\n deps: D,\n f: F,\n }\n\n impl Hook for HookProvider\n where\n D: Serialize + DeserializeOwned + PartialEq + 'static,\n T: Serialize + DeserializeOwned + 'static,\n F: 'static + FnOnce(Rc) -> T,\n {\n type Output = SuspensionResult>>;\n\n fn run(self, ctx: &mut HookContext) -> Self::Output {\n let f = self.f;\n\n ctx.next_prepared_state(move |_re_render, _| -> TransitiveStateBase {\n TransitiveStateBase {\n state_fn: Some(f).into(),\n deps: self.deps.into(),\n }\n });\n\n Ok(None)\n }\n }\n\n HookProvider:: { deps, f }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2991,"cells":{"blob_id":{"kind":"string","value":"802004b243938e1da6cda1e4bfff6b4a6aab2d05"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"dollarkillerx/Learn-RUST-again"},"path":{"kind":"string","value":"/day2_4/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":695,"string":"695"},"score":{"kind":"number","value":3.453125,"string":"3.453125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"fn main() {\n hello1();\n hello2();\n}\n\nstruct User;\ntrait Hel {\n fn hello(&self) -> String;\n}\ntrait Hum {\n fn hello(&self);\n fn hello_world(&self, you: T);\n}\nstruct DK;\nimpl Hel for DK {\n fn hello(&self) -> String {\n \"hello DK\".to_string()\n }\n}\n\nimpl Hum for User {\n fn hello(&self) {\n println!(\"Hello Hum\");\n }\n\n fn hello_world(&self, you: T) {\n println!(\"{}\",you.hello());\n }\n}\n\nfn hello1() {\n let a = User;\n status_test(a);\n}\n\nfn hello2() {\n let a = User;\n dyn_test(&a);\n}\n\nfn status_test(u: T) {\n let b = DK;\n u.hello_world(b);\n}\n\nfn dyn_test(c: &dyn Hum) {\n let b = DK;\n c.hello_world(b);\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2992,"cells":{"blob_id":{"kind":"string","value":"1bc54ef27643c5b481231dd66aa5edd12898efb6"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"ScarboroughCoral/Notes"},"path":{"kind":"string","value":"/剑指Offer/面试题56 - I. 数组中数字出现的次数.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":421,"string":"421"},"score":{"kind":"number","value":3.265625,"string":"3.265625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"impl Solution {\r\n pub fn single_numbers(nums: Vec) -> Vec {\r\n let mut r=0;\r\n for x in &nums{\r\n r^=x;\r\n }\r\n let mut d=1;\r\n while (d&r)==0{\r\n d<<=1;\r\n }\r\n let mut a=0;\r\n let mut b=0;\r\n for x in &nums{\r\n if x&d==0{\r\n a^=x;\r\n }\r\n else{\r\n b^=x;\r\n }\r\n }\r\n return vec![a,b];\r\n }\r\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2993,"cells":{"blob_id":{"kind":"string","value":"e81986963f4f3f3a4fd322b1288ef3f58d4e9e99"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"ens-ds23/ensembl-client"},"path":{"kind":"string","value":"/src/assets/browser/app/src/controller/output/report.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":7288,"string":"7,288"},"score":{"kind":"number","value":2.703125,"string":"2.703125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::collections::HashMap;\nuse std::sync::{ Arc, Mutex };\n\nuse controller::global::{ App, AppRunner };\nuse controller::output::OutputAction;\n\nuse serde_json::Map as JSONMap;\nuse serde_json::Value as JSONValue;\nuse serde_json::Number as JSONNumber;\n\n#[derive(Clone)]\n#[allow(unused)]\npub enum StatusJigsawType {\n Number,\n String,\n Boolean\n}\n\n#[derive(Clone)]\n#[allow(unused)]\npub enum StatusJigsaw {\n Atom(String,StatusJigsawType),\n Array(Vec),\n Object(HashMap)\n}\n\nstruct StatusOutput {\n last_value: Option,\n jigsaw: StatusJigsaw,\n last_sent: Option,\n send_every: Option \n}\n\nimpl StatusOutput {\n fn new(jigsaw: StatusJigsaw) -> StatusOutput {\n StatusOutput {\n jigsaw,\n last_sent: None,\n send_every: Some(0.),\n last_value: None,\n }\n }\n\n fn is_send_now(&self, t: f64) -> bool {\n if let Some(interval) = self.send_every {\n if interval == 0. { return true; }\n if let Some(last_sent) = self.last_sent {\n if t - last_sent > interval { return true; }\n } else {\n return true;\n }\n }\n return false;\n }\n}\n\nlazy_static! {\n static ref REPORT_CONFIG:\n Vec<(&'static str,StatusJigsaw,Option)> = vec!{\n (\"location\",StatusJigsaw::Array(vec!{\n StatusJigsaw::Atom(\"stick\".to_string(),StatusJigsawType::String),\n StatusJigsaw::Atom(\"start\".to_string(),StatusJigsawType::Number),\n StatusJigsaw::Atom(\"end\".to_string(),StatusJigsawType::Number),\n }),Some(500.)),\n (\"bumper\",StatusJigsaw::Array(vec!{\n StatusJigsaw::Atom(\"bumper-top\".to_string(),StatusJigsawType::Boolean),\n StatusJigsaw::Atom(\"bumper-bottom\".to_string(),StatusJigsawType::Boolean),\n StatusJigsaw::Atom(\"bumper-out\".to_string(),StatusJigsawType::Boolean),\n StatusJigsaw::Atom(\"bumper-in\".to_string(),StatusJigsawType::Boolean),\n StatusJigsaw::Atom(\"bumper-left\".to_string(),StatusJigsawType::Boolean),\n StatusJigsaw::Atom(\"bumper-right\".to_string(),StatusJigsawType::Boolean),\n }),Some(500.))\n };\n}\n\n\npub struct ReportImpl {\n pieces: HashMap,\n outputs: HashMap\n}\n\nimpl ReportImpl {\n pub fn new() -> ReportImpl {\n let out = ReportImpl {\n pieces: HashMap::::new(),\n outputs: HashMap::::new()\n };\n out\n }\n \n fn get_piece(&mut self, key: &str) -> Option {\n self.pieces.get(key).map(|s| s.clone())\n }\n\n fn get_output(&mut self, key: &str) -> Option<&mut StatusOutput> {\n self.outputs.get_mut(key)\n }\n \n fn add_output(&mut self, key: &str, jigsaw: StatusJigsaw) {\n self.outputs.insert(key.to_string(),StatusOutput::new(jigsaw));\n }\n \n pub fn set_status(&mut self, key: &str, value: &str) {\n self.pieces.insert(key.to_string(),value.to_string());\n }\n\n pub fn set_interval(&mut self, key: &str, interval: Option) {\n if let Some(ref mut p) = self.get_output(key) {\n p.send_every = interval;\n }\n }\n\n fn make_number(&self, data: &str) -> JSONValue {\n data.parse::().ok()\n .and_then(|v| JSONNumber::from_f64(v) )\n .map(|v| JSONValue::Number(v) )\n .unwrap_or(JSONValue::Null)\n }\n\n fn make_bool(&self, data: &str) -> JSONValue {\n data.parse::().ok()\n .map(|v| JSONValue::Bool(v))\n .unwrap_or(JSONValue::Null)\n }\n\n fn make_atom(&self, key: &str, type_: &StatusJigsawType) -> Option {\n let v = self.pieces.get(key);\n if let Some(ref v) = v {\n Some(match type_ {\n StatusJigsawType::Number => self.make_number(v),\n StatusJigsawType::String => JSONValue::String(v.to_string()),\n StatusJigsawType::Boolean => self.make_bool(v)\n })\n } else {\n None\n }\n }\n\n fn make_array(&self, values: &Vec) -> Option {\n let mut out = Vec::::new();\n for v in values {\n if let Some(value) = self.make_value(v) { \n out.push(value);\n } else {\n return None;\n }\n }\n Some(JSONValue::Array(out))\n }\n\n fn make_object(&self, values: &HashMap) -> Option {\n let mut out = JSONMap::::new();\n for (k,v) in values {\n if let Some(value) = self.make_value(v) {\n out.insert(k.to_string(),value);\n } else {\n return None;\n }\n }\n Some(JSONValue::Object(out))\n }\n\n fn make_value(&self, j: &StatusJigsaw) -> Option {\n match j {\n StatusJigsaw::Atom(key,type_) => self.make_atom(key,type_),\n StatusJigsaw::Array(values) => self.make_array(values),\n StatusJigsaw::Object(values) => self.make_object(values)\n }\n }\n\n fn new_report(&mut self, t: f64) -> Option {\n let mut out = JSONMap::::new();\n for (k,s) in &self.outputs {\n if let Some(value) = self.make_value(&s.jigsaw) {\n if let Some(ref last_value) = s.last_value {\n if last_value == &value { continue; }\n }\n if s.is_send_now(t) {\n out.insert(k.to_string(),value.clone());\n }\n }\n }\n for (k,v) in &out {\n if let Some(ref mut p) = self.outputs.get_mut(k) {\n p.last_value = Some(v.clone());\n p.last_sent = Some(t);\n }\n }\n if out.len() > 0 {\n Some(JSONValue::Object(out))\n } else {\n None\n }\n } \n}\n\n#[derive(Clone)]\npub struct Report(Arc>);\n\nimpl Report {\n pub fn new(ar: &mut AppRunner) -> Report {\n let mut out = Report(Arc::new(Mutex::new(ReportImpl::new())));\n for (k,j,v) in REPORT_CONFIG.iter() {\n {\n let mut imp = out.0.lock().unwrap();\n imp.add_output(k,j.clone());\n }\n out.set_interval(k,*v);\n }\n ar.add_timer(enclose! { (out) move |app,t| {\n if let Some(report) = out.new_report(t) {\n vec!{\n OutputAction::SendCustomEvent(\"bpane-out\".to_string(),report)\n }\n } else { vec!{} }\n }},None);\n out\n }\n \n pub fn set_status(&self, key: &str, value: &str) {\n let mut imp = self.0.lock().unwrap();\n imp.set_status(key,value);\n } \n\n pub fn set_status_bool(&self, key: &str, value: bool) {\n self.set_status(key,&value.to_string());\n } \n \n pub fn set_interval(&mut self, key: &str, interval: Option) {\n let mut imp = self.0.lock().unwrap();\n imp.set_interval(key,interval);\n }\n \n pub fn new_report(&self, t: f64) -> Option {\n self.0.lock().unwrap().new_report(t)\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2994,"cells":{"blob_id":{"kind":"string","value":"7cbe3f3c5c78b20de4c23dc0199e9d3f80a2c69e"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"pormeu/openbrush-contracts"},"path":{"kind":"string","value":"/examples/reentrancy-guard/flip_on_me/lib.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":708,"string":"708"},"score":{"kind":"number","value":2.65625,"string":"2.65625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"#![cfg_attr(not(feature = \"std\"), no_std)]\n\n#[ink_lang::contract]\npub mod flip_on_me {\n use ink_env::call::FromAccountId;\n use my_flipper_guard::my_flipper_guard::MyFlipper;\n\n #[ink(storage)]\n #[derive(Default)]\n pub struct FlipOnMe {}\n\n impl FlipOnMe {\n #[ink(constructor)]\n pub fn new() -> Self {\n Self::default()\n }\n\n #[ink(message)]\n pub fn flip_on_me(&mut self) {\n let caller = self.env().caller();\n // This method does a cross-contract call to caller contract and calls the `flip` method.\n let mut flipper: MyFlipper = FromAccountId::from_account_id(caller);\n flipper.flip();\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2995,"cells":{"blob_id":{"kind":"string","value":"7fd1fbd2faf430e8d8dfed2219562371e2ef46d0"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"RaymondK99/advent_of_code_2020_rs"},"path":{"kind":"string","value":"/src/util/day_02.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2057,"string":"2,057"},"score":{"kind":"number","value":3.421875,"string":"3.421875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use super::Part;\n\npub fn solve(input : String, part: Part) -> String {\n\n let list = input.lines()\n .map(|line| parse_line(line))\n .collect();\n\n let result = match part {\n Part::Part1 => part1(list),\n Part::Part2 => part2(list)\n };\n\n format!(\"{}\",result)\n}\n\nfn parse_line(input:&str) -> (usize,usize,char,&str) {\n let cols:Vec<&str> = input.split(|c| c == ' ' || c == ':' || c == '-' ).collect();\n let min = cols[0].parse().unwrap();\n let max = cols[1].parse().unwrap();\n let pattern = cols[2].as_bytes()[0] as char;\n let password = cols[4];\n\n (min,max,pattern,password)\n}\n\n\nfn part1(list:Vec<(usize,usize,char,&str)>) -> usize {\n list.iter().filter( |&(min,max,ch,input)| {\n let cnt = input.chars().filter(|c| *c == *ch).count();\n cnt >= *min && cnt <= *max\n }).count()\n}\n\nfn part2(list:Vec<(usize,usize,char,&str)>) -> usize {\n list.iter().filter( |&(index1,index2,ch,input)| {\n let ch1 = input.as_bytes()[index1-1] as char;\n let ch2 = input.as_bytes()[index2-1] as char;\n (*ch == ch1) ^ (*ch == ch2)\n }).count()}\n\n\n#[cfg(test)]\nmod tests {\n // Note this useful idiom: importing names from outer (for mod tests) scope.\n use super::*;\n use util::Part::{Part1, Part2};\n\n\n #[test]\n fn test_parse() {\n let input = \"1-3 a: abcde\";\n assert_eq!((1,3,'a',\"abcde\"), parse_line(input));\n }\n\n #[test]\n fn test1() {\n let input = \"1-3 a: abcde\n1-3 b: cdefg\n2-9 c: ccccccccc\";\n\n assert_eq!(\"2\", solve(input.to_string(),Part1));\n }\n\n #[test]\n fn test_part1() {\n let input = include_str!(\"../../input_02.txt\");\n\n assert_eq!(\"548\", solve(input.to_string(), Part1));\n }\n\n #[test]\n fn test2() {\n let input = \"1-3 a: abcde\n1-3 b: cdefg\n2-9 c: ccccccccc\";\n\n assert_eq!(\"1\", solve(input.to_string(),Part2));\n }\n\n #[test]\n fn test_part2() {\n let input = include_str!(\"../../input_02.txt\");\n\n assert_eq!(\"502\", solve(input.to_string(), Part2));\n }\n\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2996,"cells":{"blob_id":{"kind":"string","value":"974f376bbe0dfc6d2fe87d7bde6b2462456dd29a"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"YoshikawaMasashi/toid"},"path":{"kind":"string","value":"/src/high_layer_trial/phrase_operation/split_by_condition.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":680,"string":"680"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use super::super::super::data::music_info::{Note, Phrase};\n\npub fn split_by_condition(\n phrase: Phrase,\n condition: Vec,\n) -> (Phrase, Phrase) {\n let mut true_phrase = Phrase::new();\n let mut false_phrase = Phrase::new();\n true_phrase = true_phrase.set_length(phrase.length);\n false_phrase = false_phrase.set_length(phrase.length);\n\n for (note, &cond) in phrase.note_vec().iter().zip(condition.iter()) {\n if cond {\n true_phrase = true_phrase.add_note(note.clone());\n } else {\n false_phrase = false_phrase.add_note(note.clone());\n }\n }\n\n (true_phrase, false_phrase)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2997,"cells":{"blob_id":{"kind":"string","value":"e221920e5dca5c1739194e031e0a40581847066d"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"RevelationOfTuring/Rust-exercise"},"path":{"kind":"string","value":"/src/error_handling_result_early_returns.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1265,"string":"1,265"},"score":{"kind":"number","value":4.09375,"string":"4.09375"},"int_score":{"kind":"number","value":4,"string":"4"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"/*\n 我们可以显式地使用组合算子处理了错误。\n 另一种处理错误的方式是使用 `match 语句` 和 `提前返回`(early return)的结合。\n\n 也就是说:\n 如果发生错误,我们可以`停止`函数的执行然后返回错误。\n 这样的代码更好写,更易读。\n*/\n#[cfg(test)]\nmod tests {\n use std::num::ParseIntError;\n\n // 如果遇到\n fn multiply(first_num_str: &str, second_num_str: &str) -> Result {\n let n1 = match first_num_str.parse::() {\n Ok(i) => i,\n // 提前返回,如果出了错误\n Err(e) => return Err(e),\n };\n\n let n2 = match second_num_str.parse::() {\n Ok(i) => i,\n Err(e) => return Err(e),\n };\n\n // 正确的返回\n Ok(n1 * n2)\n }\n\n fn print_result(result: Result) {\n match result {\n Ok(i) => println!(\"{}\", i),\n Err(e) => println!(\"Error: {}\", e),\n }\n }\n\n #[test]\n fn test_error_handling_result_early_returns() {\n // 正常现象\n print_result(multiply(\"10\", \"11\"));\n // 返回错误(提前返回)\n print_result(multiply(\"michael.w\", \"11\"));\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2998,"cells":{"blob_id":{"kind":"string","value":"a6f6c1b0a2a2212631a11f9881158a39ee17b1a3"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"villor/rustia"},"path":{"kind":"string","value":"/crates/proxy/src/game.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1857,"string":"1,857"},"score":{"kind":"number","value":2.859375,"string":"2.859375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":[],"string":"[]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use bytes::BytesMut;\nuse protocol::{FrameType, packet::ClientPacket};\n\nuse crate::{Origin, ProxyConnection, ProxyEventHandler};\n\n/// Event handler that will detect a game protocol handshake and enable XTEA with the correct key\n#[derive(Default)]\npub struct GameHandshaker;\n\nimpl GameHandshaker {\n pub fn new() -> Self { Self::default() }\n pub fn new_boxed() -> Box {\n Box::new(Self::new())\n }\n}\n\nimpl ProxyEventHandler for GameHandshaker {\n fn on_new_connection(&self, connection: &mut ProxyConnection) -> anyhow::Result<()> {\n // Because nonce is weird\n connection.set_frame_type(FrameType::LengthPrefixed);\n Ok(())\n }\n\n fn on_frame(&self, connection: &mut ProxyConnection, from: Origin, frame: BytesMut) -> anyhow::Result {\n if connection.first_frame() { // Nonce from server\n connection.set_frame_type(FrameType::Raw);\n } else if connection.current_frame_id() == 1 { // First frame from client\n match from {\n Origin::Client => {\n let mut frame = frame.clone(); // clone really needed? BytesMut is very non-intuitive, Frame-abstraction?\n match ClientPacket::read_from(&mut frame)? {\n ClientPacket::GameLogin(login_packet) => {\n connection.set_frame_type(FrameType::XTEA(login_packet.xtea_key));\n },\n packet => {\n anyhow::bail!(format!(\"Wrong first packet from client, expected GameLogin, got {:?}\", packet));\n },\n };\n },\n Origin::Server => {\n anyhow::bail!(\"Unexpected frame order, client should send the second frame.\");\n }\n }\n }\n Ok(frame)\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":2999,"cells":{"blob_id":{"kind":"string","value":"7f5f0a9ae08b396e66daa292f60f500d7d3265cb"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"FreskyZ/fff-lang"},"path":{"kind":"string","value":"/src/vm/builtin_impl.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":48766,"string":"48,766"},"score":{"kind":"number","value":2.671875,"string":"2.671875"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0"],"string":"[\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"\r\n// Builtin methods implementation\r\n\r\nuse std::str::FromStr;\r\nuse std::fmt;\r\n\r\nuse lexical::SeperatorKind;\r\n\r\nuse codegen::FnName;\r\nuse codegen::ItemID;\r\nuse codegen::Type;\r\nuse codegen::Operand;\r\nuse codegen::TypeCollection;\r\n\r\nuse super::runtime::Runtime;\r\nuse super::runtime::RuntimeValue;\r\n\r\n// Based on the assumption that runtime will not meet invalid, return ItemID::Invalid for index out of bound\r\nfn prep_param_type(typeids: &Vec, index: usize) -> Option {\r\n if index >= typeids.len() {\r\n None\r\n } else {\r\n Some(typeids[index].as_option().unwrap()) // assume unwrap able\r\n }\r\n}\r\nfn prep_param(params: &Vec, index: usize) -> Option<&Operand> {\r\n if index >= params.len() {\r\n None\r\n } else {\r\n Some(&params[index])\r\n }\r\n}\r\n\r\nfn read_int_from_stdin() -> T where T: FromStr, ::Err: fmt::Debug {\r\n use std::io;\r\n\r\n let mut line = String::new();\r\n io::stdin().read_line(&mut line).expect(\"Failed to read line\");\r\n line.trim().parse().expect(\"Wanted a number\")\r\n}\r\n\r\nfn str_begin_with(source: &str, pattern: &str) -> bool {\r\n\r\n let mut source_chars = source.chars();\r\n let mut pattern_chars = pattern.chars();\r\n\r\n loop {\r\n match (source_chars.next(), pattern_chars.next()) {\r\n (Some(ch1), Some(ch2)) => if ch1 != ch2 { return false; }, // else continue\r\n (_, _) => return true,\r\n }\r\n }\r\n}\r\n\r\npub fn dispatch_builtin(fn_sign: (FnName, Vec), params: &Vec, types: &TypeCollection, rt: &mut Runtime) -> RuntimeValue {\r\n use super::runtime::RuntimeValue::*;\r\n\r\n let fn_name = fn_sign.0;\r\n let param_types = fn_sign.1;\r\n\r\n macro_rules! native_forward_2 {\r\n ($param0: expr, $param1: expr, $pat: pat => $stmt: block) => (match (rt.index($param0), rt.index($param1)) {\r\n $pat => $stmt,\r\n _ => unreachable!()\r\n })\r\n }\r\n macro_rules! native_forward_1 {\r\n ($param0: expr, $pat: pat => $stmt: block) => (match rt.index($param0) {\r\n $pat => $stmt\r\n _ => unreachable!()\r\n })\r\n }\r\n macro_rules! native_forward_mut_1 {\r\n ($param0: expr, $pat: pat => $stmt: block) => (match rt.index_mut($param0) {\r\n $pat => $stmt\r\n _ => unreachable!()\r\n })\r\n }\r\n\r\n // Global\r\n match (&fn_name, prep_param_type(&param_types, 0), prep_param_type(&param_types, 1), prep_param(&params, 0), prep_param(&params, 1)) {\r\n (&FnName::Ident(ref ident_name), param_type0, param_type1, param0, param1) => match (ident_name.as_ref(), param_type0, param_type1, param0, param1) {\r\n (\"write\", Some(13), None, Some(ref operand), None) => { print!(\"{}\", rt.index(operand).get_str_lit()); return RuntimeValue::Unit; }\r\n (\"writeln\", Some(13), None, Some(ref operand), None) => { println!(\"{}\", rt.index(operand).get_str_lit()); return RuntimeValue::Unit; }\r\n (\"read_i32\", None, None, None, None) => return RuntimeValue::Int(read_int_from_stdin::() as u64),\r\n (\"read_u64\", None, None, None, None) => return RuntimeValue::Int(read_int_from_stdin::()), \r\n _ => (),\r\n },\r\n _ => (),\r\n }\r\n\r\n // Builtin type\r\n match (&fn_name, prep_param_type(&param_types, 0), prep_param_type(&param_types, 1), prep_param(&params, 0), prep_param(&params, 1)) {\r\n\r\n // Integral Add\r\n (&FnName::Operator(SeperatorKind::Add), Some(1), Some(1), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::Add), Some(2), Some(2), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Add), Some(3), Some(3), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Add), Some(4), Some(4), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Add), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Add), Some(6), Some(6), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Add), Some(7), Some(7), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Add), Some(8), Some(8), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 + value1); } },\r\n\r\n // Integral Sub\r\n (&FnName::Operator(SeperatorKind::Sub), Some(1), Some(1), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::Sub), Some(2), Some(2), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Sub), Some(3), Some(3), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Sub), Some(4), Some(4), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Sub), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Sub), Some(6), Some(6), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Sub), Some(7), Some(7), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Sub), Some(8), Some(8), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 - value1); } },\r\n\r\n // Integral Mul\r\n (&FnName::Operator(SeperatorKind::Mul), Some(1), Some(1), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::Mul), Some(2), Some(2), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Mul), Some(3), Some(3), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Mul), Some(4), Some(4), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Mul), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Mul), Some(6), Some(6), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Mul), Some(7), Some(7), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Mul), Some(8), Some(8), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 * value1); } },\r\n\r\n // Integral Div\r\n (&FnName::Operator(SeperatorKind::Div), Some(1), Some(1), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::Div), Some(2), Some(2), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Div), Some(3), Some(3), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Div), Some(4), Some(4), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Div), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Div), Some(6), Some(6), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Div), Some(7), Some(7), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Div), Some(8), Some(8), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 / value1); } },\r\n\r\n // Integral Rem\r\n (&FnName::Operator(SeperatorKind::Rem), Some(1), Some(1), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::Rem), Some(2), Some(2), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Rem), Some(3), Some(3), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Rem), Some(4), Some(4), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Rem), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Rem), Some(6), Some(6), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Rem), Some(7), Some(7), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Rem), Some(8), Some(8), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 % value1); } },\r\n\r\n // Integral ShiftLeft\r\n (&FnName::Operator(SeperatorKind::ShiftLeft), Some(1), Some(5), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::ShiftLeft), Some(2), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::ShiftLeft), Some(3), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::ShiftLeft), Some(4), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::ShiftLeft), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::ShiftLeft), Some(6), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::ShiftLeft), Some(7), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::ShiftLeft), Some(8), Some(5), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 << value1); } },\r\n\r\n // Integral ShiftRight\r\n (&FnName::Operator(SeperatorKind::ShiftRight), Some(1), Some(5), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::ShiftRight), Some(2), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::ShiftRight), Some(3), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::ShiftRight), Some(4), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::ShiftRight), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::ShiftRight), Some(6), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::ShiftRight), Some(7), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::ShiftRight), Some(8), Some(5), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 >> value1); } },\r\n\r\n // Integral BitAnd\r\n (&FnName::Operator(SeperatorKind::BitAnd), Some(1), Some(1), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::BitAnd), Some(2), Some(2), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitAnd), Some(3), Some(3), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitAnd), Some(4), Some(4), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitAnd), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitAnd), Some(6), Some(6), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitAnd), Some(7), Some(7), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitAnd), Some(8), Some(8), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 & value1); } },\r\n\r\n // Integral BitOr\r\n (&FnName::Operator(SeperatorKind::BitOr), Some(1), Some(1), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::BitOr), Some(2), Some(2), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitOr), Some(3), Some(3), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitOr), Some(4), Some(4), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitOr), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitOr), Some(6), Some(6), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitOr), Some(7), Some(7), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitOr), Some(8), Some(8), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 | value1); } },\r\n\r\n // Integral BitXor\r\n (&FnName::Operator(SeperatorKind::BitXor), Some(1), Some(1), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::BitXor), Some(2), Some(2), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitXor), Some(3), Some(3), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitXor), Some(4), Some(4), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitXor), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitXor), Some(6), Some(6), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitXor), Some(7), Some(7), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::BitXor), Some(8), Some(8), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 ^ value1); } },\r\n\r\n\r\n // Integral Equal\r\n (&FnName::Operator(SeperatorKind::Equal), Some(1), Some(1), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::Equal), Some(2), Some(2), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Equal), Some(3), Some(3), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Equal), Some(4), Some(4), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Equal), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Equal), Some(6), Some(6), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Equal), Some(7), Some(7), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Equal), Some(8), Some(8), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 == value1); } },\r\n\r\n // Integral NotEqual\r\n (&FnName::Operator(SeperatorKind::NotEqual), Some(1), Some(1), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::NotEqual), Some(2), Some(2), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::NotEqual), Some(3), Some(3), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::NotEqual), Some(4), Some(4), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::NotEqual), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::NotEqual), Some(6), Some(6), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::NotEqual), Some(7), Some(7), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::NotEqual), Some(8), Some(8), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 != value1); } },\r\n\r\n // Integral GreatEqual\r\n (&FnName::Operator(SeperatorKind::GreatEqual), Some(1), Some(1), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::GreatEqual), Some(2), Some(2), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::GreatEqual), Some(3), Some(3), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::GreatEqual), Some(4), Some(4), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::GreatEqual), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::GreatEqual), Some(6), Some(6), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::GreatEqual), Some(7), Some(7), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::GreatEqual), Some(8), Some(8), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 >= value1); } },\r\n\r\n // Integral LessEqual\r\n (&FnName::Operator(SeperatorKind::LessEqual), Some(1), Some(1), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::LessEqual), Some(2), Some(2), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::LessEqual), Some(3), Some(3), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::LessEqual), Some(4), Some(4), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::LessEqual), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::LessEqual), Some(6), Some(6), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::LessEqual), Some(7), Some(7), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::LessEqual), Some(8), Some(8), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 <= value1); } },\r\n\r\n // Integral Great\r\n (&FnName::Operator(SeperatorKind::Great), Some(1), Some(1), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::Great), Some(2), Some(2), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Great), Some(3), Some(3), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Great), Some(4), Some(4), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Great), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Great), Some(6), Some(6), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Great), Some(7), Some(7), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Great), Some(8), Some(8), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 > value1); } },\r\n\r\n // Integral Less\r\n (&FnName::Operator(SeperatorKind::Less), Some(1), Some(1), Some(ref param0), Some(ref param1)) \r\n | (&FnName::Operator(SeperatorKind::Less), Some(2), Some(2), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Less), Some(3), Some(3), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Less), Some(4), Some(4), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Less), Some(5), Some(5), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Less), Some(6), Some(6), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Less), Some(7), Some(7), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Less), Some(8), Some(8), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 < value1); } },\r\n\r\n // Integral BitNot\r\n (&FnName::Operator(SeperatorKind::BitNot), Some(1), None, Some(ref param0), None) \r\n | (&FnName::Operator(SeperatorKind::BitNot), Some(2), None, Some(ref param0), None)\r\n | (&FnName::Operator(SeperatorKind::BitNot), Some(3), None, Some(ref param0), None)\r\n | (&FnName::Operator(SeperatorKind::BitNot), Some(4), None, Some(ref param0), None)\r\n | (&FnName::Operator(SeperatorKind::BitNot), Some(5), None, Some(ref param0), None)\r\n | (&FnName::Operator(SeperatorKind::BitNot), Some(6), None, Some(ref param0), None)\r\n | (&FnName::Operator(SeperatorKind::BitNot), Some(7), None, Some(ref param0), None)\r\n | (&FnName::Operator(SeperatorKind::BitNot), Some(8), None, Some(ref param0), None) \r\n => native_forward_1!{ param0, Int(value) => { return Int(!value); } },\r\n\r\n // // Integral Increase\r\n // (&FnName::Operator(SeperatorKind::Increase), Some(1), None, Some(ref param0), None) \r\n // | (&FnName::Operator(SeperatorKind::Increase), Some(2), None, Some(ref param0), None)\r\n // | (&FnName::Operator(SeperatorKind::Increase), Some(3), None, Some(ref param0), None)\r\n // | (&FnName::Operator(SeperatorKind::Increase), Some(4), None, Some(ref param0), None)\r\n // | (&FnName::Operator(SeperatorKind::Increase), Some(5), None, Some(ref param0), None)\r\n // | (&FnName::Operator(SeperatorKind::Increase), Some(6), None, Some(ref param0), None)\r\n // | (&FnName::Operator(SeperatorKind::Increase), Some(7), None, Some(ref param0), None)\r\n // | (&FnName::Operator(SeperatorKind::Increase), Some(8), None, Some(ref param0), None) \r\n // => native_forward_mut_1!{ param0, &mut Int(ref mut value) => { *value += 1; return Unit; } },\r\n\r\n // // Integral Decrease\r\n // (&FnName::Operator(SeperatorKind::Decrease), Some(1), None, Some(ref param0), None) \r\n // | (&FnName::Operator(SeperatorKind::Decrease), Some(2), None, Some(ref param0), None)\r\n // | (&FnName::Operator(SeperatorKind::Decrease), Some(3), None, Some(ref param0), None)\r\n // | (&FnName::Operator(SeperatorKind::Decrease), Some(4), None, Some(ref param0), None)\r\n // | (&FnName::Operator(SeperatorKind::Decrease), Some(5), None, Some(ref param0), None)\r\n // | (&FnName::Operator(SeperatorKind::Decrease), Some(6), None, Some(ref param0), None)\r\n // | (&FnName::Operator(SeperatorKind::Decrease), Some(7), None, Some(ref param0), None)\r\n // | (&FnName::Operator(SeperatorKind::Decrease), Some(8), None, Some(ref param0), None)\r\n // => native_forward_mut_1!{ param0, &mut Int(ref mut value) => { *value -= 1; return Unit; } },\r\n\r\n // Integral Cast to integral\r\n (&FnName::Cast(1), Some(1), None, Some(ref param0), None) \r\n | (&FnName::Cast(2), Some(1), None, Some(ref param0), None) \r\n | (&FnName::Cast(3), Some(1), None, Some(ref param0), None) \r\n | (&FnName::Cast(4), Some(1), None, Some(ref param0), None) \r\n | (&FnName::Cast(5), Some(1), None, Some(ref param0), None) \r\n | (&FnName::Cast(6), Some(1), None, Some(ref param0), None) \r\n | (&FnName::Cast(7), Some(1), None, Some(ref param0), None) \r\n | (&FnName::Cast(8), Some(1), None, Some(ref param0), None) \r\n | (&FnName::Cast(1), Some(2), None, Some(ref param0), None) \r\n | (&FnName::Cast(2), Some(2), None, Some(ref param0), None) \r\n | (&FnName::Cast(3), Some(2), None, Some(ref param0), None) \r\n | (&FnName::Cast(4), Some(2), None, Some(ref param0), None) \r\n | (&FnName::Cast(5), Some(2), None, Some(ref param0), None) \r\n | (&FnName::Cast(6), Some(2), None, Some(ref param0), None) \r\n | (&FnName::Cast(7), Some(2), None, Some(ref param0), None) \r\n | (&FnName::Cast(8), Some(2), None, Some(ref param0), None) \r\n | (&FnName::Cast(1), Some(3), None, Some(ref param0), None) \r\n | (&FnName::Cast(2), Some(3), None, Some(ref param0), None) \r\n | (&FnName::Cast(3), Some(3), None, Some(ref param0), None) \r\n | (&FnName::Cast(4), Some(3), None, Some(ref param0), None) \r\n | (&FnName::Cast(5), Some(3), None, Some(ref param0), None) \r\n | (&FnName::Cast(6), Some(3), None, Some(ref param0), None) \r\n | (&FnName::Cast(7), Some(3), None, Some(ref param0), None) \r\n | (&FnName::Cast(8), Some(3), None, Some(ref param0), None) \r\n | (&FnName::Cast(1), Some(4), None, Some(ref param0), None) \r\n | (&FnName::Cast(2), Some(4), None, Some(ref param0), None) \r\n | (&FnName::Cast(3), Some(4), None, Some(ref param0), None) \r\n | (&FnName::Cast(4), Some(4), None, Some(ref param0), None) \r\n | (&FnName::Cast(5), Some(4), None, Some(ref param0), None) \r\n | (&FnName::Cast(6), Some(4), None, Some(ref param0), None) \r\n | (&FnName::Cast(7), Some(4), None, Some(ref param0), None) \r\n | (&FnName::Cast(8), Some(4), None, Some(ref param0), None) \r\n | (&FnName::Cast(1), Some(5), None, Some(ref param0), None) \r\n | (&FnName::Cast(2), Some(5), None, Some(ref param0), None) \r\n | (&FnName::Cast(3), Some(5), None, Some(ref param0), None) \r\n | (&FnName::Cast(4), Some(5), None, Some(ref param0), None) \r\n | (&FnName::Cast(5), Some(5), None, Some(ref param0), None) \r\n | (&FnName::Cast(6), Some(5), None, Some(ref param0), None) \r\n | (&FnName::Cast(7), Some(5), None, Some(ref param0), None) \r\n | (&FnName::Cast(8), Some(5), None, Some(ref param0), None) \r\n | (&FnName::Cast(1), Some(6), None, Some(ref param0), None) \r\n | (&FnName::Cast(2), Some(6), None, Some(ref param0), None) \r\n | (&FnName::Cast(3), Some(6), None, Some(ref param0), None) \r\n | (&FnName::Cast(4), Some(6), None, Some(ref param0), None) \r\n | (&FnName::Cast(5), Some(6), None, Some(ref param0), None) \r\n | (&FnName::Cast(6), Some(6), None, Some(ref param0), None) \r\n | (&FnName::Cast(7), Some(6), None, Some(ref param0), None) \r\n | (&FnName::Cast(8), Some(6), None, Some(ref param0), None) \r\n | (&FnName::Cast(1), Some(7), None, Some(ref param0), None) \r\n | (&FnName::Cast(2), Some(7), None, Some(ref param0), None) \r\n | (&FnName::Cast(3), Some(7), None, Some(ref param0), None) \r\n | (&FnName::Cast(4), Some(7), None, Some(ref param0), None) \r\n | (&FnName::Cast(5), Some(7), None, Some(ref param0), None) \r\n | (&FnName::Cast(6), Some(7), None, Some(ref param0), None) \r\n | (&FnName::Cast(7), Some(7), None, Some(ref param0), None) \r\n | (&FnName::Cast(8), Some(7), None, Some(ref param0), None) \r\n | (&FnName::Cast(1), Some(8), None, Some(ref param0), None) \r\n | (&FnName::Cast(2), Some(8), None, Some(ref param0), None) \r\n | (&FnName::Cast(3), Some(8), None, Some(ref param0), None) \r\n | (&FnName::Cast(4), Some(8), None, Some(ref param0), None) \r\n | (&FnName::Cast(5), Some(8), None, Some(ref param0), None) \r\n | (&FnName::Cast(6), Some(8), None, Some(ref param0), None) \r\n | (&FnName::Cast(7), Some(8), None, Some(ref param0), None) \r\n | (&FnName::Cast(8), Some(8), None, Some(ref param0), None)\r\n => native_forward_1!{ param0, Int(value) => { return Int(value); } },\r\n\r\n // Integral cast to float\r\n (&FnName::Cast(10), Some(1), None, Some(ref param0), None) \r\n | (&FnName::Cast(10), Some(2), None, Some(ref param0), None) \r\n | (&FnName::Cast(10), Some(3), None, Some(ref param0), None) \r\n | (&FnName::Cast(10), Some(4), None, Some(ref param0), None) \r\n | (&FnName::Cast(10), Some(5), None, Some(ref param0), None) \r\n | (&FnName::Cast(10), Some(6), None, Some(ref param0), None) \r\n | (&FnName::Cast(10), Some(7), None, Some(ref param0), None) \r\n | (&FnName::Cast(10), Some(8), None, Some(ref param0), None)\r\n => native_forward_1!{ param0, Int(value) => { return Float(value as f64); } },\r\n \r\n \r\n // Float Add\r\n (&FnName::Operator(SeperatorKind::Add), Some(9), Some(9), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Add), Some(10), Some(10), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Float(value0 + value1); } },\r\n (&FnName::Operator(SeperatorKind::Sub), Some(9), Some(9), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Sub), Some(10), Some(10), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Float(value0 - value1); } },\r\n (&FnName::Operator(SeperatorKind::Mul), Some(9), Some(9), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Mul), Some(10), Some(10), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Float(value0 * value1); } },\r\n (&FnName::Operator(SeperatorKind::Div), Some(9), Some(9), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Div), Some(10), Some(10), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Float(value0 / value1); } },\r\n\r\n // Float Compare\r\n (&FnName::Operator(SeperatorKind::Equal), Some(9), Some(9), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Equal), Some(10), Some(10), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 == value1); } },\r\n (&FnName::Operator(SeperatorKind::NotEqual), Some(9), Some(9), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::NotEqual), Some(10), Some(10), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 != value1); } },\r\n (&FnName::Operator(SeperatorKind::GreatEqual), Some(9), Some(9), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::GreatEqual), Some(10), Some(10), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 >= value1); } },\r\n (&FnName::Operator(SeperatorKind::LessEqual), Some(9), Some(9), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::LessEqual), Some(10), Some(10), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 <= value1); } },\r\n (&FnName::Operator(SeperatorKind::Great), Some(9), Some(9), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Great), Some(10), Some(10), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 > value1); } },\r\n (&FnName::Operator(SeperatorKind::Less), Some(9), Some(9), Some(ref param0), Some(ref param1))\r\n | (&FnName::Operator(SeperatorKind::Less), Some(10), Some(10), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 < value1); } },\r\n\r\n // Float cast to float\r\n (&FnName::Cast(9), Some(9), None, Some(ref param0), None) \r\n | (&FnName::Cast(10), Some(9), None, Some(ref param0), None) \r\n | (&FnName::Cast(9), Some(10), None, Some(ref param0), None) \r\n | (&FnName::Cast(10), Some(10), None, Some(ref param0), None)\r\n => native_forward_1!{ param0, Float(value) => { return Float(value); } },\r\n // Float cast to integral\r\n (&FnName::Cast(8), Some(9), None, Some(ref param0), None) \r\n | (&FnName::Cast(8), Some(10), None, Some(ref param0), None)\r\n => native_forward_1!{ param0, Float(value) => { return Int(value as u64); } },\r\n\r\n // Char Compare\r\n (&FnName::Operator(SeperatorKind::Equal), Some(11), Some(11), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 == value1); } },\r\n (&FnName::Operator(SeperatorKind::NotEqual), Some(11), Some(11), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 != value1); } },\r\n (&FnName::Operator(SeperatorKind::GreatEqual), Some(11), Some(11), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 >= value1); } },\r\n (&FnName::Operator(SeperatorKind::LessEqual), Some(11), Some(11), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 <= value1); } },\r\n (&FnName::Operator(SeperatorKind::Great), Some(11), Some(11), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 > value1); } },\r\n (&FnName::Operator(SeperatorKind::Less), Some(11), Some(11), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 < value1); } },\r\n\r\n // Char cast\r\n (&FnName::Cast(6), Some(11), None, Some(ref param0), None) \r\n => native_forward_1!{ param0, Char(value) => { return RuntimeValue::Int(value as u64); } },\r\n\r\n // Bool\r\n (&FnName::Operator(SeperatorKind::Equal), Some(12), Some(12), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Bool(value0), Bool(value1)) => { return Bool(value0 == value1); } },\r\n (&FnName::Operator(SeperatorKind::NotEqual), Some(12), Some(12), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Bool(value0), Bool(value1)) => { return Bool(value0 != value1); } },\r\n (&FnName::Operator(SeperatorKind::LogicalAnd), Some(12), Some(12), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Bool(value0), Bool(value1)) => { return Bool(value0 && value1); } },\r\n (&FnName::Operator(SeperatorKind::LogicalOr), Some(12), Some(12), Some(ref param0), Some(ref param1)) \r\n => native_forward_2!{ param0, param1, (Bool(value0), Bool(value1)) => { return Bool(value0 || value1); } },\r\n (&FnName::Operator(SeperatorKind::LogicalNot), Some(12), None, Some(ref param0), None) \r\n => native_forward_1!{ param0, Bool(value) => { return Bool(!value); } },\r\n\r\n // Str\r\n (&FnName::Operator(SeperatorKind::Add), Some(13), Some(13), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Str(value0), Str(value1)) => { return Str(value0 + &value1); } },\r\n (&FnName::Operator(SeperatorKind::Equal), Some(13), Some(13), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Str(value0), Str(value1)) => { return Bool(value0 == value1); } },\r\n (&FnName::Operator(SeperatorKind::NotEqual), Some(13), Some(13), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Str(value0), Str(value1)) => { return Bool(value0 != value1); } },\r\n\r\n // Special ident dispatcher\r\n (&FnName::Ident(ref ident_name), param_type0, param_type1, param0, param1) => match (ident_name.as_ref(), param_type0, param_type1, param0, param1) {\r\n\r\n // Integral is_odd\r\n (\"is_odd\", Some(1), None, Some(ref param0), None) \r\n | (\"is_odd\", Some(2), None, Some(ref param0), None) \r\n | (\"is_odd\", Some(3), None, Some(ref param0), None) \r\n | (\"is_odd\", Some(4), None, Some(ref param0), None) \r\n | (\"is_odd\", Some(5), None, Some(ref param0), None) \r\n | (\"is_odd\", Some(6), None, Some(ref param0), None) \r\n | (\"is_odd\", Some(7), None, Some(ref param0), None) \r\n | (\"is_odd\", Some(8), None, Some(ref param0), None) \r\n => native_forward_1!{ param0, Int(value) => { return Bool((value & 1) == 0); } },\r\n \r\n // Integral to_string\r\n (\"to_string\", Some(1), None, Some(ref param0), None) \r\n | (\"to_string\", Some(2), None, Some(ref param0), None) \r\n | (\"to_string\", Some(3), None, Some(ref param0), None) \r\n | (\"to_string\", Some(4), None, Some(ref param0), None) \r\n | (\"to_string\", Some(5), None, Some(ref param0), None) \r\n | (\"to_string\", Some(6), None, Some(ref param0), None) \r\n | (\"to_string\", Some(7), None, Some(ref param0), None) \r\n | (\"to_string\", Some(8), None, Some(ref param0), None)\r\n => native_forward_1!{ param0, Int(value) => { return Str(format!(\"{}\", value)); } },\r\n\r\n // Float to_string\r\n (\"to_string\", Some(9), None, Some(ref param0), None) \r\n | (\"to_string\", Some(10), None, Some(ref param0), None) \r\n => native_forward_1!{ param0, Float(value) => { return Str(format!(\"{}\", value)); } },\r\n\r\n // Char to_string\r\n (\"to_string\", Some(11), None, Some(ref param0), None)\r\n => native_forward_1!{ param0, Char(value) => { return Str(format!(\"{}\", value)); } },\r\n\r\n // String\r\n (\"length\", Some(13), None, Some(ref param0), None)\r\n => native_forward_1!{ param0, Str(value) => { return Int(value.len() as u64); } },\r\n (\"get_index\", Some(13), Some(5), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Str(value0), Int(value1)) => { return Char(value0.chars().nth(value1 as usize).unwrap()); } },\r\n (\"get_index\", Some(13), Some(8), Some(ref param0), Some(ref param1))\r\n => native_forward_2!{ param0, param1, (Str(value0), Int(value1)) => { return Char(value0.chars().nth(value1 as usize).unwrap()); } },\r\n\r\n (_, _, _, _, _) => (),\r\n },\r\n\r\n (_, _, _, _, _) => (),\r\n }\r\n\r\n // Builtin template type global\r\n if let &FnName::Ident(ref fn_name) = &fn_name {\r\n\r\n if fn_name == \"?new_tuple\" { // ?new_tuple(aaa, bbb, ccc) -> (aaa, bbb, ccc)\r\n let mut rt_values = Vec::new();\r\n for param in params {\r\n rt_values.push(rt.index(param));\r\n }\r\n return RuntimeValue::Tuple(rt_values); \r\n\r\n } else if fn_name == \"?new_array\" { // ?new_array(value, size) -> [value]\r\n // Currently 5 and 8 are all 8 at runtime, no more need to check\r\n if let RuntimeValue::Int(item_init_size) = rt.index(&params[1]) {\r\n let item_init_value = rt.index(&params[0]);\r\n\r\n let mut array_items = Vec::new();\r\n for _ in 0..item_init_size {\r\n array_items.push(item_init_value.clone());\r\n }\r\n return RuntimeValue::ArrayRef(rt.allocate_heap(RuntimeValue::Array(array_items)));\r\n }\r\n\r\n } else if str_begin_with(fn_name, \"?new_array_\") { // ?new_array_xxx() -> [xxx]\r\n return RuntimeValue::ArrayRef(rt.allocate_heap(RuntimeValue::Array(Vec::new())));\r\n\r\n } else if str_begin_with(fn_name, \"set_item\") {\r\n let mut temp_id_str = String::new();\r\n for i in 8..fn_name.len() {\r\n temp_id_str.push(fn_name.chars().nth(i).unwrap());\r\n }\r\n let item_id = usize::from_str(&temp_id_str).unwrap();\r\n if params.len() == 2 {\r\n let new_value = rt.index(&params[1]);\r\n match rt.index_mut(&params[0]) {\r\n &mut RuntimeValue::Tuple(ref mut items) => { items[item_id] = new_value; return RuntimeValue::Unit; }\r\n _ => unreachable!()\r\n }\r\n } else {\r\n unreachable!()\r\n }\r\n }\r\n }\r\n\r\n // Builtin template type instance\r\n if let Some(real_typeid) = prep_param_type(&param_types, 0) {\r\n match types.get_by_idx(real_typeid) {\r\n &Type::Base(_) => unreachable!(),\r\n &Type::Array(_item_real_typeid) => {\r\n match (&fn_name, \r\n prep_param_type(&param_types, 0), prep_param_type(&param_types, 1), prep_param_type(&param_types, 2), \r\n prep_param(&params, 0), prep_param(&params, 1), prep_param(&params, 2)) {\r\n\r\n (&FnName::Operator(SeperatorKind::Equal), _, _, _, Some(ref param0), Some(ref param1), None) => {\r\n match (rt.index(param0), rt.index(param1)) {\r\n (RuntimeValue::ArrayRef(heap_index1), RuntimeValue::ArrayRef(heap_index2)) => {\r\n let (array1_clone, array2_clone) = match (&rt.heap[heap_index1], &rt.heap[heap_index2]) {\r\n (&RuntimeValue::Array(ref array1), &RuntimeValue::Array(ref array2)) => (array1.clone(), array2.clone()),\r\n _ => unreachable!(),\r\n };\r\n\r\n if array1_clone.len() != array2_clone.len() {\r\n return RuntimeValue::Bool(false);\r\n } else {\r\n let mut ret_val = true;\r\n for i in 0..array1_clone.len() {\r\n ret_val = ret_val && (array1_clone[i] == array2_clone[i]); // because cannot decide part of heap's operand, that's all\r\n }\r\n return RuntimeValue::Bool(ret_val);\r\n }\r\n }\r\n _ => unreachable!()\r\n }\r\n }\r\n (&FnName::Operator(SeperatorKind::NotEqual), _, _, _, Some(ref param0), Some(ref param1), None) => {\r\n match (rt.index(param0), rt.index(param1)) {\r\n (RuntimeValue::ArrayRef(heap_index1), RuntimeValue::ArrayRef(heap_index2)) => {\r\n let (array1_clone, array2_clone) = match (&rt.heap[heap_index1], &rt.heap[heap_index2]) {\r\n (&RuntimeValue::Array(ref array1), &RuntimeValue::Array(ref array2)) => (array1.clone(), array2.clone()),\r\n _ => unreachable!(),\r\n };\r\n\r\n if array1_clone.len() != array2_clone.len() {\r\n return RuntimeValue::Bool(true);\r\n } else {\r\n let mut ret_val = false;\r\n for i in 0..array1_clone.len() {\r\n ret_val = ret_val || (array1_clone[i] != array2_clone[i]);\r\n }\r\n return RuntimeValue::Bool(ret_val);\r\n }\r\n }\r\n _ => unreachable!()\r\n }\r\n }\r\n\r\n (&FnName::Ident(ref ident_name), param_type0, param_type1, param_type2, param0, param1, param2) => match (ident_name.as_ref(), param_type0, param_type1, param_type2, param0, param1, param2) {\r\n (\"set_index\", _, Some(5), _, Some(ref param0), Some(ref param1), Some(ref param2)) \r\n | (\"set_index\", _, Some(8), _, Some(ref param0), Some(ref param1), Some(ref param2)) => {\r\n match (rt.index(param0), rt.index(param1), rt.index(param2)) {\r\n (RuntimeValue::ArrayRef(heap_index), RuntimeValue::Int(array_index), new_value) => {\r\n match &mut rt.heap[heap_index as usize] {\r\n &mut RuntimeValue::Array(ref mut array) => { array[array_index as usize] = new_value.clone(); return RuntimeValue::Unit; }\r\n _ => unreachable!()\r\n }\r\n }\r\n _ => unreachable!()\r\n }\r\n }\r\n (\"get_index\", _, Some(5), None, Some(ref param0), Some(ref param1), None)\r\n | (\"get_index\", _, Some(8), None, Some(ref param0), Some(ref param1), None) => {\r\n match (rt.index(param0), rt.index(param1)) {\r\n (RuntimeValue::ArrayRef(heap_index), RuntimeValue::Int(array_index)) => {\r\n match &mut rt.heap[heap_index as usize] {\r\n &mut RuntimeValue::Array(ref mut array) => return array[array_index as usize].clone(),\r\n _ => unreachable!()\r\n }\r\n }\r\n _ => unreachable!()\r\n }\r\n }\r\n (\"push\", _, _, None, Some(ref param0), Some(ref param1), None) => {\r\n match (rt.index(param0), rt.index(param1)) {\r\n (RuntimeValue::ArrayRef(heap_index), new_value) => {\r\n match &mut rt.heap[heap_index as usize] {\r\n &mut RuntimeValue::Array(ref mut array) => { array.push(new_value.clone()); return RuntimeValue::Unit; }\r\n _ => unreachable!()\r\n }\r\n }\r\n _ => unreachable!()\r\n }\r\n }\r\n (\"pop\", _, None, None, Some(ref param0), None, None) => {\r\n match rt.index(param0) {\r\n RuntimeValue::ArrayRef(heap_index) => {\r\n match &mut rt.heap[heap_index as usize] {\r\n &mut RuntimeValue::Array(ref mut array) => return array.pop().unwrap(),\r\n _ => unreachable!()\r\n }\r\n }\r\n _ => unreachable!()\r\n }\r\n }\r\n (\"length\", _, None, None, Some(ref param0), None, None) => {\r\n match rt.index(param0) {\r\n RuntimeValue::ArrayRef(heap_index) => {\r\n match &mut rt.heap[heap_index as usize] {\r\n &mut RuntimeValue::Array(ref mut array) => return RuntimeValue::Int(array.len() as u64),\r\n _ => unreachable!()\r\n }\r\n }\r\n _ => unreachable!()\r\n }\r\n }\r\n _ => unreachable!(),\r\n },\r\n _ => unreachable!(),\r\n }\r\n }\r\n &Type::Tuple(ref _item_real_typeids) => {\r\n match (&fn_name, prep_param_type(&param_types, 0), prep_param_type(&param_types, 1), prep_param(&params, 0), prep_param(&params, 1)) {\r\n (&FnName::Operator(SeperatorKind::Equal), _, _, Some(ref param0), Some(ref param1)) => {\r\n match (rt.index(param0), rt.index(param1)) {\r\n (RuntimeValue::Tuple(values1), RuntimeValue::Tuple(values2)) => {\r\n let mut ret_val = true;\r\n for i in 0..values1.len() {\r\n ret_val = ret_val && values1[i] == values2[i];\r\n }\r\n return RuntimeValue::Bool(ret_val);\r\n }\r\n _ => unreachable!()\r\n }\r\n }\r\n (&FnName::Operator(SeperatorKind::NotEqual), _, _, Some(ref param0), Some(ref param1)) => {\r\n match (rt.index(param0), rt.index(param1)) {\r\n (RuntimeValue::Tuple(values1), RuntimeValue::Tuple(values2)) => {\r\n let mut ret_val = false;\r\n for i in 0..values1.len() {\r\n ret_val = ret_val || values1[i] != values2[i];\r\n }\r\n return RuntimeValue::Bool(ret_val);\r\n }\r\n _ => unreachable!()\r\n }\r\n }\r\n _ => unreachable!()\r\n }\r\n }\r\n }\r\n }\r\n\r\n unreachable!()\r\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":29,"numItemsPerPage":100,"numTotalItems":1135379,"offset":2900,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NzYzODQ2NSwic3ViIjoiL2RhdGFzZXRzL2hvbmdsaXU5OTAzL3N0YWNrX2VkdV9ydXN0IiwiZXhwIjoxNzU3NjQyMDY1LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.FNiEf3garEtuPsV3fFvQL7bLfxBxT3pYzSUhrwen9DfS7JPCJP0PBnUYDYUOgPtRBEwz7Y83d3jNtE_m-ig-BA","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
140
path
stringlengths
5
183
src_encoding
stringclasses
6 values
length_bytes
int64
12
5.32M
score
float64
2.52
4.94
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
12
5.32M
download_success
bool
1 class
7854f0d243425d917f19d5b06fb07b00e228a64a
Rust
SnoozeTime/game-off-2019
/src/states/gameover.rs
UTF-8
3,391
3.046875
3
[]
no_license
use crate::{ event::{AppEvent, MyEvent}, states::MyTrans, util::delete_hierarchy, }; use amethyst::{ ecs::prelude::Entity, input::{is_close_requested, is_key_down}, prelude::*, ui::{UiCreator, UiEvent, UiEventType, UiFinder}, winit::VirtualKeyCode, }; use log::info; const RETRY_BUTTON_ID: &str = "retry"; const EXIT_TO_MAIN_MENU_BUTTON_ID: &str = "exit_to_main_menu"; const EXIT_BUTTON_ID: &str = "exit"; /// Just display a text and then propose to start again or go back to main menu #[derive(Debug, Default)] pub struct GameOverState { root: Option<Entity>, // Buttons entities are created on_start and destroy on_stop() retry_button: Option<Entity>, exit_to_main_menu_button: Option<Entity>, exit_button: Option<Entity>, } impl State<GameData<'static, 'static>, MyEvent> for GameOverState { fn on_start(&mut self, data: StateData<GameData>) { info!("Start gameover state"); let world = data.world; self.root = Some(world.exec(|mut creator: UiCreator<'_>| creator.create("ui/gameover.ron", ()))); } fn on_stop(&mut self, data: StateData<GameData>) { if let Some(handler) = self.root { delete_hierarchy(handler, data.world).expect("Failed to remove GameOverScreen"); } self.root = None; } fn handle_event(&mut self, _: StateData<GameData>, event: MyEvent) -> MyTrans { match &event { MyEvent::Window(event) => { if is_close_requested(&event) || is_key_down(&event, VirtualKeyCode::Escape) { info!("[Trans::Quit] Quitting Application!"); Trans::Quit } else { Trans::None } } MyEvent::Ui(UiEvent { event_type: UiEventType::Click, target, }) => { if Some(*target) == self.retry_button { info!("[Trans::Switch] Switching to Game!"); Trans::Switch(Box::new(crate::states::GameState::default())) } else if Some(*target) == self.exit_button { info!("[Trans::Quit] Quitting Application!"); Trans::Quit } else { Trans::None } } MyEvent::App(e) => { if let AppEvent::NewDialog { dialog: sentences, .. } = e { Trans::Push(Box::new(crate::states::DialogState::new(sentences.clone()))) } else { Trans::None } } _ => Trans::None, } } /// Will get the entities for the UI elements from UiFinder. fn update(&mut self, data: StateData<GameData>) -> MyTrans { data.data.update(&data.world); if self.retry_button.is_none() || self.exit_to_main_menu_button.is_none() || self.exit_button.is_none() { data.world.exec(|ui_finder: UiFinder<'_>| { self.retry_button = ui_finder.find(RETRY_BUTTON_ID); self.exit_button = ui_finder.find(EXIT_BUTTON_ID); self.exit_to_main_menu_button = ui_finder.find(EXIT_TO_MAIN_MENU_BUTTON_ID); }); } MyTrans::None } }
true
cae742176261447b0c1a2ff334fe9f14c465df71
Rust
cocagne/aspen-server
/src/crl/sweeper/log_file.rs
UTF-8
14,047
2.625
3
[]
no_license
use std::collections::{HashMap, HashSet}; use std::fmt; use std::ffi::CString; use std::io::{Result, Error, ErrorKind}; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use libc; use log::{error, info, warn}; use crate::{Data, ArcDataSlice}; use super::*; pub(super) struct LogFile { file_path: Box<PathBuf>, pub file_id: FileId, fd: libc::c_int, pub len: usize, pub max_size: usize, pub file_uuid: uuid::Uuid } impl Drop for LogFile { fn drop(&mut self) { unsafe { libc::close(self.fd); } } } impl fmt::Display for LogFile { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "CRL Sweeper File: {}", self.file_path.as_path().display()) } } #[cfg(target_os="linux")] fn open_synchronous_fd(path: &CString) -> libc::c_int { const O_DIRECT: libc::c_int = 0x4000; const O_DSYNC: libc::c_int = 4000; unsafe { libc::open(path.as_ptr(), libc::O_CREAT | libc::O_RDWR | O_DIRECT | O_DSYNC) } } #[cfg(target_os="macos")] fn open_synchronous_fd(path: &CString) -> libc::c_int { const F_NOCACHE: libc::c_int = 0x30; unsafe { let mut fd = libc::open(path.as_ptr(), libc::O_CREAT | libc::O_RDWR); if fd > 0 { if libc::fchmod(fd, 0o644) < 0 { fd = -1; } } if fd > 0 { if libc::fcntl(fd, F_NOCACHE, 1) < 0 { fd = -1; } } fd } } #[cfg(not(any(target_os="linux", target_os="macos")))] fn open_synchronous_fd(path: &CString) -> libc::c_int { unsafe { libc::open(path.as_ptr(), libc::O_CREAT | libc::O_RDWR) } } impl LogFile { fn new( directory: &Path, file_id: FileId, max_file_size: usize) -> Result<(LogFile, Option<(LogEntrySerialNumber, usize)>)> { let f = format!("{}", file_id.0); let p = directory.join(f); let fp = p.as_path(); let fd = open_synchronous_fd(&CString::new(fp.as_os_str().as_bytes()).unwrap()); if fd < 0 { error!("Failed to open CRL file {}", fp.display()); return Err(Error::last_os_error()); } let mut size = seek(fd, 0, libc::SEEK_END)?; if size < (16 + STATIC_ENTRY_SIZE as usize) { // Initialize seek(fd, 0, libc::SEEK_SET)?; unsafe { libc::ftruncate(fd, 0); } let u = uuid::Uuid::new_v4(); write_bytes(fd, &u.as_bytes()[..])?; } let file_uuid = pread_uuid(fd, 0)?; size = seek(fd, 0, libc::SEEK_END)?; let last = find_last_valid_entry(fd, size, &file_uuid)?; let lf = LogFile{ file_path: Box::new(p), file_id, fd, len: size as usize, max_size: max_file_size, file_uuid }; Ok((lf, last)) } fn read(&self, offset: usize, nbytes: usize) -> Result<Data> { let mut v = Vec::<u8>::with_capacity(nbytes); if nbytes > 0 { v.resize(nbytes, 0); pread_bytes(self.fd, &mut v[..], offset)?; } Ok(Data::new(v)) } pub(super) fn write(&mut self, data: &Vec<ArcDataSlice>) -> Result<()> { let wsize: usize = data.iter().map(|d| d.len()).sum(); unsafe { let iov: Vec<libc::iovec> = data.iter().map( |d| { let p: *const u8 = &d.as_bytes()[0]; libc::iovec { iov_base: p as *mut libc::c_void, iov_len: d.len() } }).collect(); loop { if libc::writev(self.fd, &iov[0], data.len() as libc::c_int) >= 0 { break; } else { let err = Error::last_os_error(); match err.kind() { ErrorKind::Interrupted => (), _ => return { warn!("Unexpected error occured during CRL file write: {}", err); Err(err) } } } } if !( cfg!(target_os="linux") || cfg!(target_os="macos") ) { libc::fsync(self.fd); } } self.len += wsize; Ok(()) } pub(super) fn recycle(&mut self) -> Result<()> { info!("Recycling {}", self); seek(self.fd, 0, libc::SEEK_SET)?; unsafe { libc::ftruncate(self.fd, 0); } self.file_uuid = uuid::Uuid::new_v4(); self.len = 16; write_bytes(self.fd, &self.file_uuid.as_bytes()[..])?; Ok(()) } } fn pread_bytes(fd: libc::c_int, s: &mut [u8], offset: usize) -> Result<()> { if s.len() == 0 { Ok(()) } else { let p: *mut u8 = &mut s[0]; unsafe { if libc::pread(fd, p as *mut libc::c_void, s.len(), offset as libc::off_t) < 0 { Err(Error::last_os_error()) } else { Ok(()) } } } } fn pread_uuid(fd: libc::c_int, offset: usize) -> Result<uuid::Uuid> { let mut buf: [u8; 16] = [0; 16]; pread_bytes(fd, &mut buf[..], offset)?; Ok(uuid::Uuid::from_bytes(buf)) } fn write_bytes(fd: libc::c_int, s: &[u8]) -> Result<()> { let p: *const u8 = &s[0]; unsafe { if libc::write(fd, p as *const libc::c_void, s.len()) < 0 { return Err(Error::last_os_error()); } libc::fsync(fd); } Ok(()) } fn seek(fd: libc::c_int, offset: i64, whence: libc::c_int) -> Result<usize> { unsafe { let sz = libc::lseek(fd, offset, whence); if sz < 0 { Err(Error::last_os_error()) } else { Ok(sz as usize) } } } fn find_last_valid_entry( fd: libc::c_int, file_size: usize, file_uuid: &uuid::Uuid) -> Result<Option<(LogEntrySerialNumber, usize)>> { let mut offset = file_size - (file_size % 4096); let mut last = None; while offset > 32 && last.is_none() { let test_uuid = pread_uuid(fd, offset - 16)?; if test_uuid == *file_uuid { let entry_offset = offset - STATIC_ENTRY_SIZE as usize; let mut serial_bytes: [u8; 8] = [0; 8]; pread_bytes(fd, &mut serial_bytes[..], entry_offset)?; let serial = u64::from_le_bytes(serial_bytes); last = Some((LogEntrySerialNumber(serial), entry_offset)); break; } offset -= 4096; } //println!("LAST: {:?} file size {} offset {}", last, file_size, (file_size - (file_size % 4096))); Ok(last) } pub(super) fn recover( crl_directory: &Path, max_file_size: usize, num_streams: usize) -> Result<RecoveredCrlState> { let mut raw_files = Vec::<(LogFile, Option<(LogEntrySerialNumber, usize)>)>::new(); for i in 0 .. num_streams * 3 { let f = LogFile::new(crl_directory, FileId(i as u16), max_file_size)?; raw_files.push(f); } let mut last: Option<(FileId, LogEntrySerialNumber, usize)> = None; for t in &raw_files { if let Some((serial, offset)) = &t.1 { if let Some((_, cur_serial, _)) = &last { if serial > cur_serial { last = Some((t.0.file_id, *serial, *offset)); } } else { last = Some((t.0.file_id, *serial, *offset)) } } } let mut files: Vec<(LogFile, Option<LogEntrySerialNumber>)> = Vec::new(); for t in raw_files { files.push((t.0, t.1.map(|x| x.0))); } let mut tx: Vec<RecoveredTx> = Vec::new(); let mut alloc: Vec<RecoveredAlloc> = Vec::new(); let mut last_entry_serial = LogEntrySerialNumber(0); let mut last_entry_location = FileLocation { file_id: FileId(0), offset: 0, length: 0 }; if let Some((last_file_id, last_serial, last_offset)) = last { last_entry_serial = last_serial; last_entry_location = FileLocation { file_id: last_file_id, offset: last_offset as u64, length: STATIC_ENTRY_SIZE as u32 }; let mut transactions: HashMap<TxId, RecoveringTx> = HashMap::new(); let mut allocations: HashMap<TxId, RecoveringAlloc> = HashMap::new(); let mut deleted_tx: HashSet<TxId> = HashSet::new(); let mut deleted_alloc: HashSet<TxId> = HashSet::new(); let mut file_id = last_file_id; let mut entry_serial = last_serial; let mut entry_block_offset = last_offset; let earliest_serial_needed = { let mut d = files[last_file_id.0 as usize].0.read(last_offset, STATIC_ENTRY_SIZE as usize)?; let entry = encoding::decode_entry(&mut d)?; LogEntrySerialNumber(entry.earliest_needed) }; while entry_serial >= earliest_serial_needed { let file = &files[file_id.0 as usize].0; let mut d = file.read(entry_block_offset, STATIC_ENTRY_SIZE as usize)?; let mut entry = encoding::decode_entry(&mut d)?; entry_serial = entry.serial; //println!("Reading Entry {:?} entry_block_offset {} entry offset {}", entry_serial, entry_block_offset, entry.entry_offset); let entry_data_size = entry_block_offset - entry.entry_offset as usize; let mut entry_data = file.read(entry.entry_offset as usize, entry_data_size)?; encoding::load_entry_data(&mut entry_data, &mut entry, entry_serial)?; for txid in &entry.tx_deletions { deleted_tx.insert(*txid); } for txid in &entry.alloc_deletions { deleted_alloc.insert(*txid); } for rtx in entry.transactions { if ! deleted_tx.contains(&rtx.id) && ! transactions.contains_key(&rtx.id) { transactions.insert(rtx.id, rtx); } } for ra in entry.allocations { if ! deleted_alloc.contains(&ra.id) && ! allocations.contains_key(&ra.id) { allocations.insert(ra.id, ra); } } if entry.previous_entry_location.offset < 16 { break; // Cannot have an offset of 0 (first 16 bytes of the file are the UUID) } file_id = entry.previous_entry_location.file_id; entry_block_offset = entry.previous_entry_location.offset as usize; } let get_data = |file_location: &FileLocation| -> Result<ArcData> { let d = files[file_location.file_id.0 as usize].0.read(file_location.offset as usize, file_location.length as usize)?; Ok(d.into()) }; let get_slice = |file_location: &FileLocation| -> Result<ArcDataSlice> { let d = get_data(file_location)?; Ok(d.into()) }; for (txid, rtx) in transactions { let mut ou: Vec<transaction::ObjectUpdate> = Vec::with_capacity(rtx.object_updates.len()); for t in &rtx.object_updates { ou.push(transaction::ObjectUpdate { object_id: object::Id(t.0), data: get_slice(&t.1)? }); } tx.push( RecoveredTx { id: txid, txd_location: rtx.serialized_transaction_description, serialized_transaction_description: get_data(&rtx.serialized_transaction_description)?, object_updates: ou, update_locations: rtx.object_updates, tx_disposition: rtx.tx_disposition, paxos_state: rtx.paxos_state, last_entry_serial: rtx.last_entry_serial }); } for (txid, ra) in allocations { alloc.push(RecoveredAlloc{ id: txid, store_pointer: ra.store_pointer, object_id: ra.object_id, kind: ra.kind, size: ra.size, data_location: ra.data, data: get_data(&ra.data)?, refcount: ra.refcount, timestamp: ra.timestamp, serialized_revision_guard: ra.serialized_revision_guard, last_entry_serial: ra.last_entry_serial }); } }; Ok(RecoveredCrlState { log_files: files, transactions: tx, allocations: alloc, last_entry_serial, last_entry_location }) } #[cfg(test)] mod tests { use tempdir::TempDir; use super::*; #[test] fn initialization() { let t = TempDir::new("test").unwrap(); let (l, o) = LogFile::new(t.path(), FileId(0), 50).unwrap(); let u = l.file_uuid; assert!(o.is_none()); assert_eq!(l.len, 16); let ru = pread_uuid(l.fd, 0).unwrap(); assert_eq!(u, ru); unsafe { let n = libc::lseek(l.fd, 0, libc::SEEK_END); assert_eq!(n, 16); } } #[test] fn recycle() { let t = TempDir::new("test").unwrap(); let (mut l, o) = LogFile::new(t.path(), FileId(0), 50).unwrap(); let u = l.file_uuid; assert!(o.is_none()); assert_eq!(l.len, 16); let ru = pread_uuid(l.fd, 0).unwrap(); assert_eq!(u, ru); write_bytes(l.fd, &[1u8,2u8,3u8,4u8]).unwrap(); unsafe { let n = libc::lseek(l.fd, 0, libc::SEEK_END); assert_eq!(n, 20); } l.recycle().unwrap(); let ru = pread_uuid(l.fd, 0).unwrap(); assert_ne!(u, ru); assert_eq!(l.file_uuid, ru); unsafe { let n = libc::lseek(l.fd, 0, libc::SEEK_END); assert_eq!(n, 16); } } }
true
cd010b754bd21998db42eedafe1721e592bca7ca
Rust
zaeleus/noodles
/noodles-bam/src/lazy/record/cigar.rs
UTF-8
1,097
2.671875
3
[ "MIT" ]
permissive
use std::io; use noodles_sam as sam; /// Raw BAM record CIGAR operations. #[derive(Debug, Eq, PartialEq)] pub struct Cigar<'a>(&'a [u8]); impl<'a> Cigar<'a> { pub(super) fn new(src: &'a [u8]) -> Self { Self(src) } /// Returns whether there are any CIGAR operations. pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Returns the number of CIGAR operations. /// /// This is _not_ the length of the buffer. pub fn len(&self) -> usize { self.0.len() / 4 } } impl<'a> AsRef<[u8]> for Cigar<'a> { fn as_ref(&self) -> &[u8] { self.0 } } impl<'a> TryFrom<Cigar<'a>> for sam::record::Cigar { type Error = io::Error; fn try_from(bam_cigar: Cigar<'a>) -> Result<Self, Self::Error> { use crate::record::codec::decoder::get_cigar; let mut src = bam_cigar.0; let mut cigar = Self::default(); let op_count = bam_cigar.len(); get_cigar(&mut src, &mut cigar, op_count) .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; Ok(cigar) } }
true
7e266acac341196b63ca004e859f739310f9aca1
Rust
zeta1999/titik
/src/widget/image_control.rs
UTF-8
2,075
3.140625
3
[ "MIT" ]
permissive
use crate::{ buffer::Buffer, widget::traits::ImageTrait, Cmd, LayoutTree, Widget, }; use image::{ self, DynamicImage, }; use std::{ any::Any, fmt, marker::PhantomData, }; use stretch::style::Style; /// Image widget, supported formats: jpg, png pub struct Image<MSG> { image: DynamicImage, /// the width of cells used for this image width: Option<f32>, /// the height of unit cells, will be divided by 2 when used for computing /// style layout height: Option<f32>, id: Option<String>, _phantom_msg: PhantomData<MSG>, } impl<MSG> Image<MSG> { /// create a new image widget pub fn new(bytes: Vec<u8>) -> Self { let image = Image { image: image::load_from_memory(&bytes) .expect("unable to load from memory"), width: None, height: None, id: None, _phantom_msg: PhantomData, }; image } } impl<MSG> ImageTrait for Image<MSG> { fn width(&self) -> Option<f32> { self.width } fn height(&self) -> Option<f32> { self.height } fn image(&self) -> &DynamicImage { &self.image } } impl<MSG> Widget<MSG> for Image<MSG> where MSG: 'static, { fn style(&self) -> Style { self.image_style() } /// draw this button to the buffer, with the given computed layout fn draw(&mut self, buf: &mut Buffer, layout_tree: &LayoutTree) -> Vec<Cmd> { self.draw_image(buf, layout_tree) } fn as_any(&self) -> &dyn Any { self } fn as_any_mut(&mut self) -> &mut dyn Any { self } fn set_size(&mut self, width: Option<f32>, height: Option<f32>) { self.width = width; self.height = height; } fn set_id(&mut self, id: &str) { self.id = Some(id.to_string()); } fn get_id(&self) -> &Option<String> { &self.id } } impl<MSG> fmt::Debug for Image<MSG> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Image") } }
true
221abfa7d36998dcdf0fed4b4e38b3c378632c0b
Rust
mattiasgronlund/cubemx-db-decoder
/src/cubemx_db/ip/bsp_dependency.rs
UTF-8
1,710
2.890625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
use super::Condition; use crate::{ decode::{AttributeMap, Decode}, error::Unexpected, Config, Error, }; #[derive(Debug)] pub struct BspDependency { pub name: String, pub comment: String, pub bsp_ip_name: String, pub bsp_mode_name: Option<String>, pub user_name: Option<String>, pub api: Option<String>, pub component: Option<String>, pub condition: Vec<Condition>, } impl Decode for BspDependency { type Object = BspDependency; fn decode(config: Config, node: roxmltree::Node) -> Result<Self::Object, Error> { let mut attributes = AttributeMap::from(node, config); let mut condition = Vec::new(); for child in node.children() { match child.node_type() { roxmltree::NodeType::Element => match child.tag_name().name() { "Condition" => condition.push(Condition::decode(config, child)?), _ => Unexpected::element(config, &node, &child)?, }, roxmltree::NodeType::Text => Unexpected::text(config, &node, &child)?, _ => {} } } let result = BspDependency { name: attributes.take_required("Name")?, comment: attributes.take_required("Comment")?, bsp_ip_name: attributes.take_required("BspIpName")?, bsp_mode_name: attributes.take_optional("BspModeName"), user_name: attributes.take_optional("UserName"), api: attributes.take_optional("Api"), component: attributes.take_optional("Component"), condition, }; attributes.report_unexpected_if_not_empty()?; Ok(result) } }
true
94559e67a219d06cf3409cb5cd5b8878ca6f99e4
Rust
rust-lang/rustfmt
/tests/source/cfg_if/detect/os/freebsd/auxvec.rs
UTF-8
2,795
2.796875
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! Parses ELF auxiliary vectors. #![cfg_attr(any(target_arch = "arm", target_arch = "powerpc64"), allow(dead_code))] /// Key to access the CPU Hardware capabilities bitfield. pub(crate) const AT_HWCAP: usize = 25; /// Key to access the CPU Hardware capabilities 2 bitfield. pub(crate) const AT_HWCAP2: usize = 26; /// Cache HWCAP bitfields of the ELF Auxiliary Vector. /// /// If an entry cannot be read all the bits in the bitfield are set to zero. /// This should be interpreted as all the features being disabled. #[derive(Debug, Copy, Clone)] pub(crate) struct AuxVec { pub hwcap: usize, pub hwcap2: usize, } /// ELF Auxiliary Vector /// /// The auxiliary vector is a memory region in a running ELF program's stack /// composed of (key: usize, value: usize) pairs. /// /// The keys used in the aux vector are platform dependent. For FreeBSD, they are /// defined in [sys/elf_common.h][elf_common_h]. The hardware capabilities of a given /// CPU can be queried with the `AT_HWCAP` and `AT_HWCAP2` keys. /// /// Note that run-time feature detection is not invoked for features that can /// be detected at compile-time. /// /// [elf_common.h]: https://svnweb.freebsd.org/base/release/12.0.0/sys/sys/elf_common.h?revision=341707 pub(crate) fn auxv() -> Result<AuxVec, ()> { if let Ok(hwcap) = archauxv(AT_HWCAP) { if let Ok(hwcap2) = archauxv(AT_HWCAP2) { if hwcap != 0 && hwcap2 != 0 { return Ok(AuxVec { hwcap, hwcap2 }); } } } Err(()) } /// Tries to read the `key` from the auxiliary vector. fn archauxv(key: usize) -> Result<usize, ()> { use crate::mem; #[derive (Copy, Clone)] #[repr(C)] pub struct Elf_Auxinfo { pub a_type: usize, pub a_un: unnamed, } #[derive (Copy, Clone)] #[repr(C)] pub union unnamed { pub a_val: libc::c_long, pub a_ptr: *mut libc::c_void, pub a_fcn: Option<unsafe extern "C" fn() -> ()>, } let mut auxv: [Elf_Auxinfo; 27] = [Elf_Auxinfo{a_type: 0, a_un: unnamed{a_val: 0,},}; 27]; let mut len: libc::c_uint = mem::size_of_val(&auxv) as libc::c_uint; unsafe { let mut mib = [libc::CTL_KERN, libc::KERN_PROC, libc::KERN_PROC_AUXV, libc::getpid()]; let ret = libc::sysctl(mib.as_mut_ptr(), mib.len() as u32, &mut auxv as *mut _ as *mut _, &mut len as *mut _ as *mut _, 0 as *mut libc::c_void, 0, ); if ret != -1 { for i in 0..auxv.len() { if auxv[i].a_type == key { return Ok(auxv[i].a_un.a_val as usize); } } } } return Ok(0); }
true
76ef40415e911edbaeac5c53ffd27e73fae782fe
Rust
seanjensengrey/rust-copperline
/src/run.rs
UTF-8
3,187
3.25
3
[ "MIT" ]
permissive
use error::Error; use edit::{EditCtx, EditResult, edit}; use builder::Builder; use parser::{parse_cursor_pos, ParseError, ParseSuccess}; pub trait RunIO { fn write(&mut self, Vec<u8>) -> Result<(), Error>; fn read_byte(&mut self) -> Result<u8, Error>; fn prompt(&mut self, w: Vec<u8>) -> Result<u8, Error> { try!(self.write(w)); self.read_byte() } } fn query_cursor_pos(io: &mut RunIO) -> Result<(u64, u64), Error> { let mut line = Builder::new(); line.ask_cursor_pos(); try!(io.write(line.build())); let mut seq = vec![]; loop { match parse_cursor_pos(&seq) { Ok(ParseSuccess(pos, _)) => { return Ok(pos); }, Err(ParseError::Error(_)) => { return Err(Error::ParseError); }, Err(ParseError::Incomplete) => { let byte = try!(io.read_byte()); seq.push(byte); } } } } fn protect_newline(io: &mut RunIO) -> Result<(), Error> { let (x, _) = try!(query_cursor_pos(io)); if x > 1 { let mut line = Builder::new(); line.invert_color(); line.append("%\n"); line.reset_color(); try!(io.write(line.build())); } Ok(()) } fn run_edit<'a>(mut ctx: EditCtx<'a>, io: &mut RunIO) -> Result<String, Error> { loop { match edit(&mut ctx) { EditResult::Cont(line) => { ctx.fill(try!(io.prompt(line))); }, EditResult::Halt(res) => { return res; } } } } pub fn run<'a>(ctx: EditCtx<'a>, io: &mut RunIO) -> Result<String, Error> { try!(protect_newline(io)); run_edit(ctx, io) } #[cfg(test)] mod test { use encoding::all::ASCII; use super::super::error::Error; use super::super::edit::EditCtx; use super::super::history::History; use super::{RunIO, run_edit}; pub struct TestIO { input: Vec<u8>, output: Vec<u8> } impl RunIO for TestIO { fn write(&mut self, w: Vec<u8>) -> Result<(), Error> { self.output.extend(w); Ok(()) } fn read_byte(&mut self) -> Result<u8, Error> { if self.input.len() > 0 { Ok(self.input.remove(0)) } else { Err(Error::EndOfFile) } } } #[test] fn error_eof_on_empty_input() { let mut io = TestIO { input: vec![], output: vec![] }; let h = History::new(); let ctx = EditCtx::new("foo> ", &h, ASCII); assert_eq!(run_edit(ctx, &mut io), Err(Error::EndOfFile)); } #[test] fn ok_empty_after_return() { let mut io = TestIO { input: vec![13], output: vec![] }; let h = History::new(); let ctx = EditCtx::new("foo> ", &h, ASCII); assert_eq!(run_edit(ctx, &mut io), Ok("".to_string())); } #[test] fn ok_ascii_after_return() { let mut io = TestIO { input: vec![65, 66, 67, 13], output: vec![] }; let h = History::new(); let ctx = EditCtx::new("foo> ", &h, ASCII); assert_eq!(run_edit(ctx, &mut io), Ok("ABC".to_string())); } }
true
b457c3384046d00e733c9e51404764c445d0053d
Rust
schell/todo_finder
/todo_finder_lib/src/parser.rs
UTF-8
11,540
2.890625
3
[ "MIT" ]
permissive
use nom::{bytes::complete as bytes, character::complete as character, combinator, IResult}; use super::{ finder::FileSearcher, github::{GitHubIssue, GitHubPatch}, }; use serde::Deserialize; use std::{collections::HashMap, fs::File, io::prelude::*, path::Path}; pub mod issue; pub mod langs; pub mod source; use issue::GitHubTodoLocation; use source::ParsedTodo; /// Eat a whole line and optionally its ending but don't return that ending. pub fn take_to_eol(i: &str) -> IResult<&str, &str> { let (i, ln) = bytes::take_till(|c| c == '\r' || c == '\n')(i)?; let (i, _) = combinator::opt(character::line_ending)(i)?; Ok((i, ln)) } #[derive(Debug, Deserialize, Clone)] pub enum IssueProvider { GitHub, } #[derive(Debug, Clone)] pub enum ParsingSource { MarkdownFile, SourceCode, IssueAt(IssueProvider), } #[derive(Debug, Clone)] pub struct IssueHead<K> { pub title: String, pub assignees: Vec<String>, pub external_id: K, } #[derive(Debug, Clone, PartialEq)] pub struct IssueBody<T> { pub descs_and_srcs: Vec<(Vec<String>, T)>, pub branches: Vec<String>, } impl IssueBody<FileTodoLocation> { pub fn to_github_string( &self, cwd: &str, owner: &str, repo: &str, checkout: &str, ) -> Result<String, String> { let mut lines: Vec<String> = vec![]; for (desc_lines, loc) in self.descs_and_srcs.iter() { let desc = desc_lines.clone().join("\n"); let link = loc.to_github_link(cwd, owner, repo, checkout)?; lines.push(vec![desc, link].join("\n")); } Ok(lines.join("\n")) } } #[derive(Debug, Clone)] pub struct Issue<ExternalId, TodoLocation: PartialEq + Eq> { pub head: IssueHead<ExternalId>, pub body: IssueBody<TodoLocation>, } impl<ExId, Loc: PartialEq + Eq> Issue<ExId, Loc> { pub fn new(id: ExId, title: String) -> Self { Issue { head: IssueHead { title, assignees: vec![], external_id: id, }, body: IssueBody { descs_and_srcs: vec![], branches: vec![], }, } } } #[derive(Debug, Clone)] pub struct IssueMap<ExternalId, TodoLocation: PartialEq + Eq> { pub parsed_from: ParsingSource, pub todos: HashMap<String, Issue<ExternalId, TodoLocation>>, } /// A todo location in the local filesystem. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct FileTodoLocation { pub file: String, pub src_span: (usize, Option<usize>), } impl FileTodoLocation { /// ```rust /// use todo_finder_lib::parser::FileTodoLocation; /// /// let loc = FileTodoLocation { /// file: "/total/path/src/file.rs".into(), /// src_span: (666, Some(1337)), /// }; /// /// let string = loc /// .to_github_link("/total/path", "schell", "my_repo", "1234567890") /// .unwrap(); /// /// assert_eq!( /// &string, /// "https://github.com/schell/my_repo/blob/1234567890/src/file.rs#L666-L1337" /// ); /// ``` pub fn to_github_link( &self, cwd: &str, owner: &str, repo: &str, checkout: &str, ) -> Result<String, String> { let path: &Path = Path::new(&self.file); let relative: &Path = path .strip_prefix(cwd) .map_err(|e| format!("could not relativize path {:#?}: {}", path, e))?; let file_and_range = vec![ format!("{}", relative.display()), format!("#L{}", self.src_span.0), if let Some(end) = self.src_span.1 { format!("-L{}", end) } else { String::new() }, ] .concat(); let parts = vec![ "https://github.com", owner, repo, "blob", checkout, &file_and_range, ]; Ok(parts.join("/")) } } impl<K, V: Eq> IssueMap<K, V> { pub fn new(parsed_from: ParsingSource) -> IssueMap<K, V> { IssueMap { parsed_from, todos: HashMap::new(), } } } impl IssueMap<u64, GitHubTodoLocation> { pub fn new_github_todos() -> Self { IssueMap { parsed_from: ParsingSource::IssueAt(IssueProvider::GitHub), todos: HashMap::new(), } } pub fn add_issue(&mut self, github_issue: &GitHubIssue) { if let Ok((_, body)) = issue::issue_body(&github_issue.body) { let mut issue = Issue::new(github_issue.number, github_issue.title.clone()); issue.body = body; self.todos.insert(github_issue.title.clone(), issue); } } pub fn prepare_patch(&self, local: IssueMap<(), FileTodoLocation>) -> GitHubPatch { let mut create = IssueMap::new_source_todos(); let mut edit: IssueMap<u64, FileTodoLocation> = IssueMap::new(ParsingSource::SourceCode); let mut dont_delete = vec![]; for (title, local_issue) in local.todos.into_iter() { if let Some(remote_issue) = self.todos.get(&title) { // They both have it let id = remote_issue.head.external_id.clone(); dont_delete.push(id); let issue = Issue { head: remote_issue.head.clone(), body: local_issue.body, }; edit.todos.insert(title, issue); } else { // Must be created create.todos.insert(title, local_issue); } } let delete = self .todos .values() .filter_map(|issue| { let id = issue.head.external_id; if dont_delete.contains(&id) { None } else { Some(id) } }) .collect::<Vec<_>>(); return GitHubPatch { create, edit, delete, }; } } impl IssueMap<(), FileTodoLocation> { pub fn new_source_todos() -> Self { IssueMap { parsed_from: ParsingSource::SourceCode, todos: HashMap::new(), } } pub fn distinct_len(&self) -> usize { self.todos.len() } pub fn add_parsed_todo(&mut self, todo: &ParsedTodo, loc: FileTodoLocation) { let title = todo.title.to_string(); let issue = self .todos .entry(title.clone()) .or_insert(Issue::new((), title)); if let Some(assignee) = todo.assignee.map(|s| s.to_string()) { if !issue.head.assignees.contains(&assignee) { issue.head.assignees.push(assignee); } } let desc_lines = todo .desc_lines .iter() .map(|s| s.to_string()) .collect::<Vec<_>>(); issue.body.descs_and_srcs.push((desc_lines, loc)); } pub fn from_files_in_directory( dir: &str, excludes: &Vec<String>, ) -> Result<IssueMap<(), FileTodoLocation>, String> { let possible_todos = FileSearcher::find(dir, excludes)?; let mut todos = IssueMap::new_source_todos(); let language_map = langs::language_map(); for possible_todo in possible_todos.into_iter() { let path = Path::new(&possible_todo.file); // Get our parser for this extension let ext: Option<_> = path.extension(); if ext.is_none() { continue; } let ext: &str = ext .expect("impossible!") .to_str() .expect("could not get extension as str"); let languages = language_map.get(ext); if languages.is_none() { // TODO: Deadletter the file name as unsupported println!("possible TODO found in unsupported file: {:#?}", path); continue; } let languages = languages.expect("impossible!"); // Open the file and load the contents let mut file = File::open(path) .map_err(|e| format!("could not open file: {}\n{}", path.display(), e))?; let mut contents = String::new(); file.read_to_string(&mut contents) .map_err(|e| format!("could not read file {:#?}: {}", path, e))?; let mut current_line = 1; let mut i = contents.as_str(); for line in possible_todo.lines_to_search.into_iter() { // Seek to the correct line... while line > current_line { let (j, _) = take_to_eol(i).map_err(|e| format!("couldn't take line:\n{}", e))?; i = j; current_line += 1; } // Try parsing in each language until we get a match for language in languages.iter() { let parser_config = language.as_todo_parser_config(); let parser = source::parse_todo(parser_config); if let Ok((j, parsed_todo)) = parser(i) { let num_lines = i.trim_end_matches(j).lines().fold(0, |n, _| n + 1); let loc = FileTodoLocation { file: possible_todo.file.to_string(), src_span: ( line, if num_lines > 1 { Some(line + num_lines - 1) } else { None }, ), }; todos.add_parsed_todo(&parsed_todo, loc); } } } } Ok(todos) } pub fn as_markdown(&self) -> String { let num_distinct = self.todos.len(); let num_locs = self .todos .values() .fold(0, |n, todo| n + todo.body.descs_and_srcs.len()); let mut lines = vec![]; lines.push("# TODOs".into()); lines.push(format!( "Found {} distinct TODOs in {} file locations.\n", num_distinct, num_locs )); let mut todos = self.todos.clone().into_iter().collect::<Vec<_>>(); todos.sort_by(|a, b| a.0.cmp(&b.0)); for ((title, issue), n) in todos.into_iter().zip(1..) { lines.push(format!("{}. {}", n, title)); for (descs, loc) in issue.body.descs_and_srcs.into_iter() { for line in descs.into_iter() { lines.push(format!(" {}", line)); } lines.push(format!( " file://{} ({})", loc.file, if let Some(end) = loc.src_span.1 { format!("lines {} - {}", loc.src_span.0, end) } else { format!("line {}", loc.src_span.0) }, )); lines.push("".into()); } if issue.head.assignees.len() > 0 { lines.push(format!( " assignees: {}\n", issue.head.assignees.join(", ") )); } } lines.join("\n") } }
true
190c6d70bc4a674d56a1a39ad3ac39e9ecf2a32a
Rust
gaotianyu1350/rCore_audio
/crate/thread/src/scheduler/o1.rs
UTF-8
1,673
3.484375
3
[ "MIT", "Apache-2.0" ]
permissive
//! O(1) scheduler introduced in Linux 2.6 //! //! Two queues are maintained, one is active, another is inactive. //! Take the first task from the active queue to run. When it is empty, swap active and inactive queues. use super::*; pub struct O1Scheduler { inner: Mutex<O1SchedulerInner>, } struct O1SchedulerInner { active_queue: usize, queues: [Vec<Tid>; 2], } impl Scheduler for O1Scheduler { fn push(&self, tid: usize) { self.inner.lock().push(tid); } fn pop(&self, _cpu_id: usize) -> Option<usize> { self.inner.lock().pop() } fn tick(&self, current_tid: usize) -> bool { self.inner.lock().tick(current_tid) } fn set_priority(&self, _tid: usize, _priority: u8) {} } impl O1Scheduler { pub fn new() -> Self { let inner = O1SchedulerInner { active_queue: 0, queues: [Vec::new(), Vec::new()], }; O1Scheduler { inner: Mutex::new(inner), } } } impl O1SchedulerInner { fn push(&mut self, tid: Tid) { let inactive_queue = 1 - self.active_queue; self.queues[inactive_queue].push(tid); trace!("o1 push {}", tid - 1); } fn pop(&mut self) -> Option<Tid> { let ret = match self.queues[self.active_queue].pop() { Some(tid) => return Some(tid), None => { // active queue is empty, swap 'em self.active_queue = 1 - self.active_queue; self.queues[self.active_queue].pop() } }; trace!("o1 pop {:?}", ret); ret } fn tick(&mut self, _current: Tid) -> bool { true } }
true
be1f3ec769de5dda41154a14246a8370e7bd9a90
Rust
arosspope/advent-of-code
/aoc_2020/src/day2.rs
UTF-8
1,771
3.4375
3
[ "Apache-2.0", "MIT" ]
permissive
//Day 2: Password Philosophy // #[derive(Debug, PartialEq)] pub struct PasswordPolicy { character: char, max: usize, min: usize, } #[derive(Debug, PartialEq)] pub struct PasswordEntry { policy: PasswordPolicy, password: String } #[aoc_generator(day2)] pub fn input_passwords(input: &str) -> Vec<PasswordEntry> { input.lines().map(|l| PasswordEntry { policy: PasswordPolicy { character: l.split(" ").nth(1).unwrap().chars().nth(0).unwrap(), min: l.split(" ").nth(0).unwrap().split('-').nth(0).unwrap().parse().unwrap(), max: l.split(" ").nth(0).unwrap().split('-').nth(1).unwrap().parse().unwrap(), }, password: l.split(" ").nth(2).unwrap().to_string(), // String::from("abc"), }).collect() } #[aoc(day2, part1)] pub fn part1(input: &[PasswordEntry]) -> isize { let mut valid = 0; for entry in input.iter() { let count = entry.password.matches(entry.policy.character).count(); if count >= entry.policy.min && count <= entry.policy.max { valid += 1; } } valid } #[aoc(day2, part2)] pub fn part2(input: &[PasswordEntry]) -> isize { let mut valid = 0; for entry in input.iter() { let pos0_matches = entry.password.chars().nth(entry.policy.min - 1).unwrap() == entry.policy.character; let pos1_matches = entry.password.chars().nth(entry.policy.max - 1).unwrap() == entry.policy.character; if pos0_matches ^ pos1_matches { valid += 1; } } valid } #[cfg(test)] mod tests { use super::{part1, part2, input_passwords}; #[test] fn sample2() { assert_eq!(part2(&input_passwords(&"1-3 a: abcde\n1-3 b: cdefg\n2-9 c: ccccccccc")), 1) } }
true
2d8843b4a2f5d130c42e3d83cc0b3513518d4cff
Rust
frehberg/rtps-rs
/src/structure/locator_kind.rs
UTF-8
1,296
2.53125
3
[ "Apache-2.0" ]
permissive
#[derive(Clone, Debug, Eq, PartialEq, Readable, Writable)] pub struct LocatorKind_t { value: i32, } impl LocatorKind_t { pub const LOCATOR_KIND_INVALID: LocatorKind_t = LocatorKind_t { value: -1 }; pub const LOCATOR_KIND_RESERVED: LocatorKind_t = LocatorKind_t { value: 0 }; pub const LOCATOR_KIND_UDPv4: LocatorKind_t = LocatorKind_t { value: 1 }; pub const LOCATOR_KIND_UDPv6: LocatorKind_t = LocatorKind_t { value: 2 }; } #[cfg(test)] mod tests { use super::*; serialization_test!( type = LocatorKind_t, { locator_kind_invalid, LocatorKind_t::LOCATOR_KIND_INVALID, le = [0xFF, 0xFF, 0xFF, 0xFF], be = [0xFF, 0xFF, 0xFF, 0xFF] }, { locator_kind_reserved, LocatorKind_t::LOCATOR_KIND_RESERVED, le = [0x00, 0x00, 0x00, 0x00], be = [0x00, 0x00, 0x00, 0x00] }, { locator_kind_udpv4, LocatorKind_t::LOCATOR_KIND_UDPv4, le = [0x01, 0x00, 0x00, 0x00], be = [0x00, 0x00, 0x00, 0x01] }, { locator_kind_udpv6, LocatorKind_t::LOCATOR_KIND_UDPv6, le = [0x02, 0x00, 0x00, 0x00], be = [0x00, 0x00, 0x00, 0x02] } ); }
true
0e12ee80148bc53d228c2e684528c76a5f20dc7b
Rust
tjni/offstage
/tests/repository.rs
UTF-8
2,535
3
3
[ "Apache-2.0" ]
permissive
use anyhow::{anyhow, Result}; use git2::{Commit, ErrorCode, Repository, Signature}; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use std::slice; pub const README: &str = "README"; pub const LICENSE: &str = "LICENSE"; pub struct TestRepository { repository: Repository, } impl TestRepository { pub fn new<P: AsRef<Path>>(working_dir: P) -> Result<Self> { let repository = Repository::init(&working_dir)?; Ok(Self { repository }) } pub fn initial_commit(&mut self) -> Result<()> { let readme = self.create_readme()?; self.stage_path(&readme)?; self.commit("Initial commit.") } pub fn create_readme(&self) -> Result<PathBuf> { let path = self.get_working_dir()?.join(README); writeln!(File::create(&path)?, "An example README.")?; Ok(path) } pub fn create_license(&self) -> Result<PathBuf> { let path = self.get_working_dir()?.join(LICENSE); writeln!(File::create(&path)?, "Free as in freedom.")?; Ok(path) } pub fn stage_path<P: AsRef<Path>>(&mut self, path: P) -> Result<()> { let working_dir = self.get_working_dir()?; let relative_path = path.as_ref().strip_prefix(working_dir)?; let mut index = self.repository.index()?; index.add_path(relative_path)?; index.write()?; Ok(()) } pub fn commit(&mut self, message: &str) -> Result<()> { let index = self.repository.index()?.write_tree()?; let signature = Self::get_signature()?; let head_commit = match self.repository.head() { Ok(head) => Ok(Some(head.peel_to_commit()?)), Err(error) if error.code() == ErrorCode::UnbornBranch => Ok(None), Err(error) => Err(error), }?; let head_commit_ref = head_commit.as_ref(); let parents = match head_commit_ref { Some(ref commit) => slice::from_ref(commit), None => &[] as &[&Commit], }; self.repository.commit( Some("HEAD"), &signature, &signature, message, &self.repository.find_tree(index)?, parents, )?; Ok(()) } fn get_working_dir(&self) -> Result<&Path> { self.repository .workdir() .ok_or_else(|| anyhow!("Could not find the working directory.")) } fn get_signature<'a>() -> Result<Signature<'a>> { Ok(Signature::now("me", "[email protected]")?) } }
true
bfd8e04a874ea866f13cc650c980f72c1b70bda9
Rust
jjgz/server
/src/net.rs
UTF-8
13,740
3.03125
3
[]
no_license
use std::io::{Read, Write}; use std::sync::mpsc::{channel, TryRecvError, Sender}; use std::time; use std::sync::{Mutex, Arc}; use std::thread; use std::net::TcpStream; use serde_json; use rnet::Netmessage; struct Crc8 { crc: u16, } impl Crc8 { fn new() -> Crc8 { Crc8 { crc: 0 } } fn add_byte(&mut self, byte: u8) { self.crc ^= (byte as u16) << 8; for _ in 0..8 { if self.crc & 0x8000 != 0 { self.crc ^= 0x1070 << 3; } self.crc <<= 1; } } fn finish(self) -> u8 { (self.crc >> 8) as u8 } } struct Message { buffer: Vec<u8>, } #[derive(Debug, Clone)] enum MessageError { TooBig, TooSmall, } impl Message { fn new() -> Message { Message { buffer: Vec::new() } } fn from_netmessage(nm: &Netmessage) -> Vec<u8> { let mut message = Message::new(); message.add_message(nm); message.finish() .expect(&format!("Error: Failed to create message from netmessage: {:?}", nm)) } fn append<I>(&mut self, i: I) where I: IntoIterator<Item = u8> { self.buffer.extend(i); } fn add_message(&mut self, message: &Netmessage) { let s = serde_json::to_string(message) .unwrap_or_else(|e| panic!("Failed to serialize JSON: {}", e)); self.append(s.bytes()); } fn finish(mut self) -> Result<Vec<u8>, MessageError> { if self.buffer.len() > 256 { Err(MessageError::TooBig) } else if self.buffer.len() == 0 { Err(MessageError::TooSmall) } else { let byte_len = (self.buffer.len() - 1) as u8; // Create CRC. let mut crc = Crc8::new(); // Add the length byte to the CRC. crc.add_byte(byte_len); // Add the payload to the CRC. for b in &self.buffer { crc.add_byte(*b); } // Add the magic sequence, CRC, and length to the message payload. let mut v = vec![128, 37, 35, 46, crc.finish(), byte_len]; // Add the entire payload. v.append(&mut self.buffer); Ok(v) } } } pub type PSender = Arc<Mutex<Option<Sender<Netmessage>>>>; fn route_message(ps: &PSender, m: Netmessage) { match *ps.lock().unwrap() { Some(ref c) => { match c.send(m.clone()) { Ok(_) => {} Err(e) => { println!("Error: Failed to send message on disconnected channel: {}", e); println!("Message: {:?}", m); } } } None => { println!("Warning: Attempted to send a request before the module connected."); println!("Message: {:?}", m); } } } pub fn handle_client(mut stream: TcpStream, geordon_sender: PSender, josh_sender: PSender, joe_sender: PSender, zach_sender: PSender, debug_geordon_sender: PSender, debug_josh_sender: PSender, debug_joe_sender: PSender, debug_zach_sender: PSender) { println!("New connection."); // The Wifly always sends this 7-byte sequence on connection. let mut initialbuff = [0u8; 7]; stream.read_exact(&mut initialbuff).unwrap(); if initialbuff != [42, 72, 69, 76, 76, 79, 42] { panic!("Didn't get magic values!"); } else { println!("Got magic values, continuing."); } let json_iter = match stream.try_clone() { Ok(s) => serde_json::StreamDeserializer::<Netmessage, _>::new(s.bytes()), Err(e) => panic!("Unable to clone TCP stream: {}", e), }; // Create a channel for sending back the Netmessages. let (sender, receiver) = channel(); // Perform the JSON reading in a separate thread. thread::spawn(move || { for nmessage in json_iter { sender.send(nmessage) .unwrap_or_else(|e| panic!("Failed to send nmessage: {}", e)); } }); // Create the Heartbeat message. let heartbeat = Message::from_netmessage(&Netmessage::Heartbeat); // Create the RequestNetstats message. let request_netstats = Message::from_netmessage(&Netmessage::ReqNetstats); // Create the RequestName message. let request_name = Message::from_netmessage(&Netmessage::ReqName); println!("##################"); // Create the time. let mut prev_heartbeat = time::Instant::now(); let mut prev_request_netstats = time::Instant::now(); let mut prev_req_name = time::Instant::now(); let mut self_receiver = None; let mut self_name = None; loop { // Perform a non-blocking read from the stream. match receiver.try_recv() { Ok(Ok(m)) => { match m { Netmessage::NameGeordon => { let chan = channel::<Netmessage>(); self_receiver = Some(chan.1); *geordon_sender.lock().unwrap() = Some(chan.0); self_name = Some(Netmessage::NameGeordon); println!("Geordon robot identified."); } Netmessage::NameJoe => { let chan = channel(); self_receiver = Some(chan.1); *joe_sender.lock().unwrap() = Some(chan.0); self_name = Some(Netmessage::NameJoe); println!("Joe robot identified."); } Netmessage::NameJosh => { let chan = channel(); self_receiver = Some(chan.1); *josh_sender.lock().unwrap() = Some(chan.0); self_name = Some(Netmessage::NameJosh); println!("It's Josh bitch."); } Netmessage::NameZach => { let chan = channel(); self_receiver = Some(chan.1); *zach_sender.lock().unwrap() = Some(chan.0); self_name = Some(Netmessage::NameZach); println!("Zach robot identified."); } Netmessage::NameDebugGeordon => { let chan = channel::<Netmessage>(); self_receiver = Some(chan.1); *debug_geordon_sender.lock().unwrap() = Some(chan.0); self_name = Some(Netmessage::NameDebugGeordon); println!("Debug Geordon robot identified."); } Netmessage::NameDebugJoe => { let chan = channel(); self_receiver = Some(chan.1); *debug_joe_sender.lock().unwrap() = Some(chan.0); self_name = Some(Netmessage::NameDebugJoe); println!("Debug Joe robot identified."); } Netmessage::NameDebugJosh => { let chan = channel(); self_receiver = Some(chan.1); *debug_josh_sender.lock().unwrap() = Some(chan.0); self_name = Some(Netmessage::NameDebugJosh); println!("It's Debug Josh bitch."); } Netmessage::NameDebugZach => { let chan = channel(); self_receiver = Some(chan.1); *debug_zach_sender.lock().unwrap() = Some(chan.0); self_name = Some(Netmessage::NameDebugZach); println!("Debug Zach robot identified."); } m @ Netmessage::Initialize{..} => { route_message(&josh_sender, m.clone()); route_message(&joe_sender, m.clone()); route_message(&geordon_sender, m.clone()); route_message(&zach_sender, m); } m @ Netmessage::PDebugJosh(..) | m @ Netmessage::ADebugJosh(..) | m @ Netmessage::RDebugJosh(..) | m @ Netmessage::GReqGrabbed | m @ Netmessage::DReqDropped | m @ Netmessage::HDebugJosh(..) => { route_message(&debug_josh_sender, m); } m @ Netmessage::ReqMovement | m @ Netmessage::DebugJoeUltra(..) | m @ Netmessage::DebugJoeTread(..) | m @ Netmessage::GDStartAlign | m @ Netmessage::Assumed(..) | m @ Netmessage::Proximity{..} => { route_message(&joe_sender, m); } m @ Netmessage::Movement(..) => { route_message(&debug_joe_sender, m.clone()); route_message(&debug_geordon_sender, m.clone()); route_message(&geordon_sender, m); } m @ Netmessage::DebugJoeDistance(..) | m @ Netmessage::DebugJoeOC(..) => { route_message(&debug_joe_sender, m); } m @ Netmessage::TestMove(..) | m @ Netmessage::TestRotate(..) | m @ Netmessage::ReqTestReset | m @ Netmessage::Stopped(..) | m @ Netmessage::ReqInPosition | m @ Netmessage::Targets(..) | m @ Netmessage::HalfRow(..) | m @ Netmessage::EdgeDetect(..) | m @ Netmessage::EdgeDropped(..) | m @ Netmessage::Distance(..) | m @ Netmessage::Grabbed(..) | m @ Netmessage::TestRow(..) | m @ Netmessage::Dropped(..) | m @ Netmessage::JCHalfRow(..)=> { route_message(&josh_sender, m); } m @ Netmessage::GDReqHalfRow(..) | m @ Netmessage::ReqHalfRow(..) | m @ Netmessage::ReqTargets | m @ Netmessage::GDReqPing | m @ Netmessage::ReqStopped | m @ Netmessage::GDBuild | m @ Netmessage::ReqAssumed | m @ Netmessage::GDFinish | m @ Netmessage::ReqProximity => { route_message(&geordon_sender, m); } m @ Netmessage::GDAligned => { route_message(&geordon_sender, m.clone()); route_message(&joe_sender, m); } m @ Netmessage::InPosition(..) | m @ Netmessage::ReqEdgeDetectLeft | m @ Netmessage::ReqEdgeDetectRight | m @ Netmessage::ReqEdgeDropped | m @ Netmessage::ReqDistance | m @ Netmessage::ReqGrabbed | m @ Netmessage::ReqDropped => { route_message(&zach_sender, m); } m @ Netmessage::DebugGeordon(..) | m @ Netmessage::GDPing | m @ Netmessage::GDHalfRow(..) => { route_message(&debug_geordon_sender, m); } m => { println!("{}: {:?}", self_name.as_ref() .map(|o| o.bot_name()) .unwrap_or(String::from("Unnamed")), m); } } } Ok(Err(e)) => panic!("Closing: Got invalid JSON: {}", e), Err(TryRecvError::Empty) => {} Err(TryRecvError::Disconnected) => panic!("Receiver disconnected."), } // Perform a non-blocking read from the stream. if let Some(ref sr) = self_receiver { match sr.try_recv() { Ok(m) => { stream.write_all(&Message::from_netmessage(&m)[..]) .unwrap_or_else(|e| { panic!("Failed to route message from other bot: {}", e) }); } Err(TryRecvError::Empty) => {} Err(TryRecvError::Disconnected) => panic!("Self receiver disconnected."), } } let currtime = time::Instant::now(); if currtime - prev_heartbeat > time::Duration::from_secs(1) { prev_heartbeat = currtime; // Send Heartbeat. stream.write_all(&heartbeat[..]) .unwrap_or_else(|e| panic!("Failed to send Heartbeat: {}", e)); } if currtime - prev_request_netstats > time::Duration::from_secs(5) { prev_request_netstats = currtime; // Send RequestNetstats. stream.write_all(&request_netstats[..]) .unwrap_or_else(|e| panic!("Failed to send RequestNetstats: {}", e)); } if self_receiver.is_none() && currtime - prev_req_name > time::Duration::from_millis(100) { prev_req_name = currtime; // Send RequestNetstats. stream.write_all(&request_name[..]) .unwrap_or_else(|e| panic!("Failed to send ReqName: {}", e)); } stream.flush().unwrap(); } }
true
b898a0f053240a76a48f9fc04b601b28e3b8f7c0
Rust
CoiroTomas/voronoi
/src/main.rs
UTF-8
3,844
2.578125
3
[ "MIT" ]
permissive
#![windows_subsystem = "windows"] extern crate piston; extern crate piston_window; extern crate image; use piston_window::*; use std::path::Path; static COLOURS : [[u8;4]; 16] = [[255, 255, 255, 255], [0, 255, 255, 255], [255, 0, 255, 255], [255, 255, 0, 255], [192, 192, 192, 255], [255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [128, 128, 128, 255], [0, 128, 128, 255], [128, 0, 128, 255], [128, 128, 0, 255], [0, 0, 0, 255], [128, 0, 0, 255], [0, 128, 0, 255], [0, 0, 128, 255]]; static WIDTH : u32 = 500; static HEIGHT : u32 = 500; fn main() { let mut window: PistonWindow = WindowSettings::new("Voronoi", [WIDTH, HEIGHT]) .exit_on_esc(true) .resizable(false) .build() .unwrap(); let mut voronoi = Voronoi::new(); voronoi.open_window(&mut window); } struct Voronoi { points : Vec<(u32, u32)>, distance_fn : u8, dotted : bool, } impl Voronoi { pub fn new() -> Self { Self { points: Vec::new(), distance_fn: 0, dotted: true } } pub fn open_window(&mut self, window: &mut PistonWindow) -> () { let mut cursor = [0.0, 0.0]; while let Some(e) = window.next() { if let Some(_) = e.render_args() { self.draw_screen(window, &e); } if let Some(Button::Mouse(_button)) = e.press_args() { self.add_point((cursor[0] as u32, cursor[1] as u32)); } if let Some(Button::Keyboard(key)) = e.press_args() { match key { Key::R => self.reset(), Key::S => self.save(), Key::D => self.change_dotted(), Key::Left => self.distance_fn = if self.distance_fn==0 { 2 } else { self.distance_fn - 1 }, Key::Right => self.distance_fn = (self.distance_fn + 1) % 3, _ => (), } } e.mouse_cursor(|pos| { cursor = pos; }); } } pub fn change_dotted(&mut self) { self.dotted = !self.dotted; } pub fn add_point(&mut self, point : (u32, u32)) { self.points.push(point); } pub fn reset(&mut self) { self.points = Vec::new(); self.distance_fn = 0; } pub fn save(&mut self) { let mut path_string = "Voronoi-1.png".to_string(); let mut path = Path::new(&path_string); let mut i = 2; while path.exists() { path_string = format!("Voronoi-{}.png", i); path = Path::new(&path_string); i += 1; } self.get_screen().save(path); } pub fn get_screen(&self) -> image::ImageBuffer<image::Rgba<u8>, std::vec::Vec<u8>> { let mut buffer_image = image::ImageBuffer::new(WIDTH, HEIGHT); for i in 0..(WIDTH*HEIGHT) { let y: u32 = (i / WIDTH) as u32; let x: u32 = (i % WIDTH) as u32; let closest = self.closest_point((x, y)); buffer_image.put_pixel(x, y, image::Rgba(COLOURS[closest])); } return buffer_image; } pub fn closest_point(&self, (x, y): (u32, u32)) -> usize { let mut closest = 0; let mut distance = f64::MAX; for ((w, z), i) in self.points.iter().zip(0..(self.points.len())) { let new_distance = self.distance(x, y, *w, *z); if new_distance < distance { closest = i; distance = new_distance; } } if self.dotted { if distance < 3.0 { 12 } else {closest % COLOURS.len()} } else { closest % COLOURS.len() } } pub fn distance(&self, x: u32, y: u32, w: u32, z: u32) -> f64 { match self.distance_fn { 0 => (((x as i32 - w as i32).pow(2) + (y as i32 - z as i32).pow(2)) as f64).sqrt(), 1 => ((x as i32 - w as i32).abs() + (y as i32 - z as i32).abs()) as f64, 2 => ((x as i32 - w as i32).abs().max((y as i32 - z as i32).abs())) as f64, _ => 1.0, } } pub fn draw_screen(&self, window: &mut PistonWindow, event: &Event) { let buffer_image = self.get_screen(); let texture = Texture::from_image( &mut window.create_texture_context(), &buffer_image, &TextureSettings::new(), ).unwrap(); window.draw_2d(event, |_c, g, _| { image(&texture, _c.transform, g); }); } }
true
aff514c685d46defd045eda63d0fb352c62c93e5
Rust
bouzuya/rust-atcoder
/cargo-atcoder/contests/past202010-open/src/bin/d.rs
UTF-8
699
3.015625
3
[]
no_license
use proconio::input; use proconio::marker::Chars; use std::cmp::max; fn main() { input! { n: usize, s: Chars, }; let mut counts = vec![0]; for i in 0..n { match s[i] { '.' => { let l = counts.len(); counts[l - 1] += 1; } '#' => { counts.push(0); } _ => unreachable!(), } } let l = counts.len(); let count_l = counts[0]; let count_m = *counts[1..l - 1].iter().max().unwrap_or(&0); let count_r = counts[l - 1]; let l = count_l; let r = count_r + max(0, count_m - (count_l + count_r)); println!("{} {}", l, r); }
true
d8c581f00820fad6ad4b850d72e6990e9b8e4767
Rust
aticu/pre
/proc-macro/src/extern_crate.rs
UTF-8
11,093
2.859375
3
[ "MIT", "Apache-2.0" ]
permissive
//! Provides handling of `extern_crate` attributes. //! //! # What the generated code looks like //! //! ```rust,ignore //! #[pre::extern_crate(std)] //! mod pre_std { //! mod ptr { //! #[pre(valid_ptr(src, r))] //! unsafe fn read<T>(src: *const T) -> T; //! //! impl<T> NonNull<T> { //! #[pre(!ptr.is_null())] //! const unsafe fn new_unchecked(ptr: *mut T) -> NonNull<T>; //! } //! } //! } //! ``` //! //! turns into //! //! ```rust,ignore //! #[doc = "..."] //! mod pre_std { //! #[allow(unused_imports)] //! use pre::pre; //! #[allow(unused_imports)] //! #[doc(no_inline)] //! pub(crate) use std::*; //! //! #[doc = "..."] //! pub(crate) mod ptr { //! #[allow(unused_imports)] //! use pre::pre; //! #[allow(unused_imports)] //! #[doc(no_inline)] //! pub(crate) use std::ptr::*; //! //! #[doc = "..."] //! #[pre(!ptr.is_null())] //! #[pre(no_doc)] //! #[pre(no_debug_assert)] //! #[inline(always)] //! #[allow(non_snake_case)] //! pub(crate) fn NonNull__impl__new_unchecked__() {} //! //! #[pre(valid_ptr(src, r))] //! #[inline(always)] //! pub(crate) unsafe fn read<T>(src: *const T) -> T { //! std::ptr::read(src) //! } //! } //! } //! ``` use proc_macro2::{Span, TokenStream}; use quote::{quote, quote_spanned, TokenStreamExt}; use std::fmt; use syn::{ braced, parse::{Parse, ParseStream}, spanned::Spanned, token::Brace, Attribute, FnArg, ForeignItemFn, Ident, ItemUse, Path, PathArguments, PathSegment, Token, Visibility, }; use crate::{ documentation::{generate_extern_crate_fn_docs, generate_module_docs}, helpers::{visit_matching_attrs_parsed_mut, AttributeAction, CRATE_NAME}, pre_attr::PreAttr, }; pub(crate) use impl_block::{impl_block_stub_name, ImplBlock}; mod impl_block; /// The parsed version of the `extern_crate` attribute content. pub(crate) struct ExternCrateAttr { /// The path of the crate/module to which function calls will be forwarded. path: Path, } impl fmt::Display for ExternCrateAttr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "#[extern_crate(")?; if self.path.leading_colon.is_some() { write!(f, "::")?; } for segment in &self.path.segments { write!(f, "{}", segment.ident)?; } write!(f, ")]") } } impl Parse for ExternCrateAttr { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(ExternCrateAttr { path: input.call(Path::parse_mod_style)?, }) } } /// A parsed `extern_crate` annotated module. pub(crate) struct Module { /// The attributes on the module. attrs: Vec<Attribute>, /// The visibility on the module. visibility: Visibility, /// The `mod` token. mod_token: Token![mod], /// The name of the module. ident: Ident, /// The braces surrounding the content. braces: Brace, /// The impl blocks contained in the module. impl_blocks: Vec<ImplBlock>, /// The imports contained in the module. imports: Vec<ItemUse>, /// The functions contained in the module. functions: Vec<ForeignItemFn>, /// The submodules contained in the module. modules: Vec<Module>, } impl fmt::Display for Module { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.original_token_stream()) } } impl Spanned for Module { fn span(&self) -> Span { self.visibility .span() .join(self.braces.span) .unwrap_or(self.braces.span) } } impl Parse for Module { fn parse(input: ParseStream) -> syn::Result<Self> { let attrs = input.call(Attribute::parse_outer)?; let visibility = input.parse()?; let mod_token = input.parse()?; let ident = input.parse()?; let content; let braces = braced!(content in input); let mut impl_blocks = Vec::new(); let mut imports = Vec::new(); let mut functions = Vec::new(); let mut modules = Vec::new(); while !content.is_empty() { if content.peek(Token![impl]) { impl_blocks.push(content.parse()?); } else if <ItemUse as Parse>::parse(&content.fork()).is_ok() { imports.push(content.parse()?); } else if <ForeignItemFn as Parse>::parse(&content.fork()).is_ok() { functions.push(content.parse()?); } else { modules.push(content.parse().map_err(|err| { syn::Error::new( err.span(), "expected a module, a function signature, an impl block or a use statement", ) })?); } } Ok(Module { attrs, visibility, mod_token, ident, braces, impl_blocks, imports, functions, modules, }) } } impl Module { /// Renders this `extern_crate` annotated module to its final result. pub(crate) fn render(&self, attr: ExternCrateAttr) -> TokenStream { let mut tokens = TokenStream::new(); self.render_inner(attr.path, &mut tokens, None, &self.ident); tokens } /// A helper function to generate the final token stream. /// /// This allows passing the top level visibility and the updated path into recursive calls. fn render_inner( &self, mut path: Path, tokens: &mut TokenStream, visibility: Option<&TokenStream>, top_level_module: &Ident, ) { if visibility.is_some() { // Update the path only in recursive calls. path.segments.push(PathSegment { ident: self.ident.clone(), arguments: PathArguments::None, }); } let mut attrs = self.attrs.clone(); let mut render_docs = true; visit_matching_attrs_parsed_mut(&mut attrs, "pre", |attr| match attr.content() { PreAttr::NoDoc(_) => { render_docs = false; AttributeAction::Remove } _ => AttributeAction::Keep, }); if render_docs { let docs = generate_module_docs(self, &path); tokens.append_all(quote! { #docs }); } tokens.append_all(attrs); let visibility = if let Some(visibility) = visibility { // We're in a recursive call. // Use the visibility passed to us. tokens.append_all(quote! { #visibility }); visibility.clone() } else { // We're in the outermost call. // Use the original visibility and decide which visibility to use in recursive calls. let local_vis = &self.visibility; tokens.append_all(quote! { #local_vis }); if let Visibility::Public(pub_keyword) = local_vis { quote! { #pub_keyword } } else { let span = match local_vis { Visibility::Inherited => self.mod_token.span(), _ => local_vis.span(), }; quote_spanned! { span=> pub(crate) } } }; let mod_token = self.mod_token; tokens.append_all(quote! { #mod_token }); tokens.append(self.ident.clone()); let mut brace_content = TokenStream::new(); let crate_name = Ident::new(&CRATE_NAME, Span::call_site()); brace_content.append_all(quote! { #[allow(unused_imports)] #[doc(no_inline)] #visibility use #path::*; #[allow(unused_imports)] use #crate_name::pre; }); for impl_block in &self.impl_blocks { impl_block.render(&mut brace_content, &path, &visibility, top_level_module); } for import in &self.imports { brace_content.append_all(quote! { #import }); } for function in &self.functions { render_function(function, &mut brace_content, &path, &visibility); } for module in &self.modules { module.render_inner( path.clone(), &mut brace_content, Some(&visibility), top_level_module, ); } tokens.append_all(quote_spanned! { self.braces.span=> { #brace_content } }); } /// Generates a token stream that is semantically equivalent to the original token stream. /// /// This should only be used for debug purposes. fn original_token_stream(&self) -> TokenStream { let mut stream = TokenStream::new(); stream.append_all(&self.attrs); let vis = &self.visibility; stream.append_all(quote! { #vis }); stream.append_all(quote! { mod }); stream.append(self.ident.clone()); let mut content = TokenStream::new(); content.append_all( self.impl_blocks .iter() .map(|impl_block| impl_block.original_token_stream()), ); content.append_all(&self.imports); content.append_all(&self.functions); content.append_all(self.modules.iter().map(|m| m.original_token_stream())); stream.append_all(quote! { { #content } }); stream } } /// Generates the code for a function inside a `extern_crate` module. fn render_function( function: &ForeignItemFn, tokens: &mut TokenStream, path: &Path, visibility: &TokenStream, ) { tokens.append_all(&function.attrs); let doc_header = generate_extern_crate_fn_docs(path, &function.sig, function.span()); tokens.append_all(quote! { #doc_header }); tokens.append_all(quote_spanned! { function.span()=> #[inline(always)] }); tokens.append_all(visibility.clone().into_iter().map(|mut token| { token.set_span(function.span()); token })); let signature = &function.sig; tokens.append_all(quote! { #signature }); let mut path = path.clone(); path.segments.push(PathSegment { ident: function.sig.ident.clone(), arguments: PathArguments::None, }); // Update the spans of the `::` tokens to lie in the function for punct in path .segments .pairs_mut() .map(|p| p.into_tuple().1) .flatten() { punct.spans = [function.span(); 2]; } let mut args_list = TokenStream::new(); args_list.append_separated( function.sig.inputs.iter().map(|arg| match arg { FnArg::Receiver(_) => unreachable!("receiver is not valid in a function argument list"), FnArg::Typed(pat) => &pat.pat, }), quote_spanned! { function.span()=> , }, ); tokens.append_all(quote_spanned! { function.span()=> { #path(#args_list) } }); }
true
c3e7161eb645b6b2524066710a7d016f7b2a007e
Rust
chroussel/hdfs-cli
/walk/src/err.rs
UTF-8
575
2.625
3
[]
no_license
#[derive(Debug)] pub enum Error { IoError(std::io::Error), PathConversionError(std::ffi::OsString), PatternError(glob::PatternError), NoPathDefined, PathFormatError, } impl From<std::io::Error> for Error { fn from(err: std::io::Error) -> Self { Error::IoError(err) } } impl From<std::ffi::OsString> for Error { fn from(err: std::ffi::OsString) -> Self { Error::PathConversionError(err) } } impl From<glob::PatternError> for Error { fn from(err: glob::PatternError) -> Self { Error::PatternError(err) } }
true
d53362f508c65b559b3470a0f8eab72975f99112
Rust
AntonGepting/tmux-interface-rs
/src/formats/formats_output.rs
UTF-8
46,302
2.59375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
use super::VariableOutput; #[cfg(feature = "tmux_2_5")] use crate::SessionStack; #[cfg(feature = "tmux_1_6")] use crate::{Layout, PaneTabs, WindowFlags}; #[derive(Debug)] pub struct FormatsOutput<'a> { pub separator: char, pub variables: Vec<VariableOutput<'a>>, } impl<'a> Default for FormatsOutput<'a> { fn default() -> Self { FormatsOutput { separator: '\'', variables: Vec::new(), } } } impl<'a> FormatsOutput<'a> { pub fn new() -> Self { Default::default() } /// set separator character pub fn separator(&mut self, c: char) -> &mut Self { self.separator = c; self } /// append with variable pub fn push(&mut self, variable: VariableOutput<'a>) { self.variables.push(variable) } // TODO: check vec same size, return type? // XXX: mb from_string for default format too? pub fn from_string_ext(s: &str, format: &'a mut FormatsOutput<'a>) { let v: Vec<&str> = s.split(format.separator).collect(); for (i, variable) in v.iter().enumerate() { VariableOutput::from_string_ext(variable, &mut format.variables[i]); } } // pub fn custom_string(String) pub fn custom_usize(String) // tmux variables /// `alternate_on` - if pane is in alternate screen #[cfg(feature = "tmux_1_8")] pub fn alternate_on(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::AlternateOn(v)); self } /// `alternate_saved_x` - Saved cursor X in alternate screen #[cfg(feature = "tmux_1_8")] pub fn alternate_saved_x(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::AlternateSavedX(v)); self } /// `alternate_saved_y` - Saved cursor Y in alternate screen #[cfg(feature = "tmux_1_8")] pub fn alternate_saved_y(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::AlternateSavedY(v)); self } // Buffer /// `buffer_created` - Time buffer created #[cfg(feature = "tmux_2_6")] pub fn buffer_created(&mut self, v: &'a mut Option<u128>) -> &mut Self { self.push(VariableOutput::BufferCreated(v)); self } /// `buffer_name` - Name of buffer #[cfg(feature = "tmux_2_3")] pub fn buffer_name(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::BufferName(v)); self } /// `buffer_sample` - First 50 characters from the specified buffer #[cfg(feature = "tmux_1_7")] pub fn buffer_sample(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::BufferSample(v)); self } /// `buffer_size` - Size of the specified buffer in bytes #[cfg(feature = "tmux_1_7")] pub fn buffer_size(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::BufferSize(v)); self } // Client /// `client_activity` - Integer time client last had activity #[cfg(feature = "tmux_1_6")] pub fn client_activity(&mut self, v: &'a mut Option<u128>) -> &mut Self { self.push(VariableOutput::ClientActivity(v)); self } /// `client_cell_height` - Height of each client cell in pixels #[cfg(feature = "tmux_3_1")] pub fn client_cell_height(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::ClientCellHeight(v)); self } /// `client_cell_width` - Width of each client cell in pixels #[cfg(feature = "tmux_3_1")] pub fn client_cell_width(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::ClientCellWidth(v)); self } /// `client_activity_string` - Option<String> time client last had activity #[cfg(all(feature = "tmux_1_6", not(feature = "tmux_2_2")))] pub fn client_activity_string(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::ClientActivityString(v)); self } /// `client_created` - Integer time client created #[cfg(feature = "tmux_1_6")] pub fn client_created(&mut self, v: &'a mut Option<u128>) -> &mut Self { self.push(VariableOutput::ClientCreated(v)); self } /// `client_created_string` - Option<String> time client created #[cfg(all(feature = "tmux_1_6", not(feature = "tmux_2_2")))] pub fn client_created_string(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::ClientCreatedString(v)); self } /// `client_control_mode` - 1 if client is in control mode #[cfg(feature = "tmux_2_1")] pub fn client_control_mode(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::ClientControlMode(v)); self } /// `client_discarded` - Bytes discarded when client behind #[cfg(feature = "tmux_2_1")] pub fn client_discarded(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::ClientDiscarded(v)); self } /// `client_cwd` - Working directory of client #[cfg(all(feature = "tmux_1_6", not(feature = "tmux_1_9")))] pub fn client_cwd(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::ClientCwd(v)); self } /// `client_height` - Height of client #[cfg(feature = "tmux_1_6")] pub fn client_height(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::ClientHeight(v)); self } /// `client_key_table` - Current key table #[cfg(feature = "tmux_2_2")] pub fn client_key_table(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::ClientKeyTable(v)); self } /// `client_last_session` - Name of the client's last session #[cfg(feature = "tmux_1_8")] pub fn client_last_session(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::ClientLastSession(v)); self } /// `client_name` - Name of client #[cfg(feature = "tmux_2_4")] pub fn client_name(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::ClientName(v)); self } /// `client_pid` - PID of client process #[cfg(feature = "tmux_2_1")] pub fn client_pid(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::ClientPid(v)); self } /// `client_prefix` - 1 if prefix key has been pressed #[cfg(feature = "tmux_1_8")] pub fn client_prefix(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::ClientPrefix(v)); self } /// `client_readonly` - 1 if client is readonly #[cfg(feature = "tmux_1_6")] pub fn client_readonly(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::ClientReadonly(v)); self } /// `client_session` - Name of the client's session #[cfg(feature = "tmux_1_8")] pub fn client_session(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::ClientSession(v)); self } /// `client_termname` - Terminal name of client #[cfg(feature = "tmux_1_6")] pub fn client_termname(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::ClientTermname(v)); self } /// `client_termtype` - Terminal type of client #[cfg(all(feature = "tmux_2_4", not(feature = "tmux_3_1")))] pub fn client_termtype(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::ClientTermtype(v)); self } /// `client_tty` - Pseudo terminal of client #[cfg(feature = "tmux_1_6")] pub fn client_tty(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::ClientTty(v)); self } /// `client_utf8` - 1 if client supports UTF-8 #[cfg(feature = "tmux_1_6")] pub fn client_utf8(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::ClientUtf8(v)); self } /// `client_width` - Width of client #[cfg(feature = "tmux_1_6")] pub fn client_width(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::ClientWidth(v)); self } /// `client_written` - Bytes written to client #[cfg(feature = "tmux_2_4")] pub fn client_written(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::ClientWritten(v)); self } // Command /// `command_hooked` - Name of command hooked, if any #[cfg(feature = "tmux_2_3")] pub fn command_hooked(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::CommandHooked(v)); self } /// `command_name` - Name of command in use, if any #[cfg(all(feature = "tmux_2_2", not(feature = "tmux_2_4")))] pub fn command_name(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::CommandName(v)); self } /// `command` - Name of command in use, if any #[cfg(feature = "tmux_2_4")] pub fn command(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::Command(v)); self } /// `command_list_name` - Command name if listing commands #[cfg(feature = "tmux_2_3")] pub fn command_list_name(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::CommandListName(v)); self } /// `command_list_alias` - Command alias if listing commands #[cfg(feature = "tmux_2_3")] pub fn command_list_alias(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::CommandListAlias(v)); self } /// `command_list_usage` - Command usage if listing commands #[cfg(feature = "tmux_2_3")] pub fn command_list_usage(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::CommandListUsage(v)); self } // Cursor /// `cursor_flag` - Pane cursor flag #[cfg(feature = "tmux_1_8")] pub fn cursor_flag(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::CursorFlag(v)); self } /// `cursor_character` - Character at cursor in pane #[cfg(feature = "tmux_2_9")] pub fn cursor_character(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::CursorCharacter(v)); self } /// `cursor_x` - Cursor X position in pane #[cfg(feature = "tmux_1_8")] pub fn cursor_x(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::CursorX(v)); self } /// `cursor_y` - Cursor Y position in pane #[cfg(feature = "tmux_1_8")] pub fn cursor_y(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::CursorY(v)); self } /// `copy_cursor_line` - Line the cursor is on in copy mode #[cfg(feature = "tmux_3_1")] pub fn copy_cursor_line(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::CopyCursorLine(v)); self } /// `copy_cursor_word` - Word under cursor in copy mode #[cfg(feature = "tmux_3_1")] pub fn copy_cursor_word(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::CopyCursorWord(v)); self } /// `copy_cursor_x` - Cursor X position in copy mode #[cfg(feature = "tmux_3_1")] pub fn copy_cursor_x(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::CopyCursorX(v)); self } /// `copy_cursor_y` - Cursor Y position in copy mode #[cfg(feature = "tmux_3_1")] pub fn copy_cursor_y(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::CopyCursorY(v)); self } /// `current_file` - Current configuration file #[cfg(feature = "tmux_3_2")] pub fn current_file(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::CurrentFile(v)); self } // history /// `history_bytes` Number of bytes in window history #[cfg(feature = "tmux_1_7")] pub fn histoty_bytes(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::HistotyBytes(v)); self } /// `history_limit` Maximum window history lines #[cfg(feature = "tmux_1_7")] pub fn history_limit(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::HistotyLimit(v)); self } /// `history_size` Size of history in bytes #[cfg(feature = "tmux_1_7")] pub fn history_size(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::HistorySize(v)); self } // hook /// `hook` - Name of running hook, if any #[cfg(feature = "tmux_2_4")] pub fn hook(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::Hook(v)); self } /// `hook_pane` - ID of pane where hook was run, if any #[cfg(feature = "tmux_2_4")] pub fn hook_pane(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::HookPane(v)); self } /// `hook_session` - ID of session where hook was run, if any #[cfg(feature = "tmux_2_4")] pub fn hook_session(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::HookSession(v)); self } /// `hook_session_name` - Name of session where hook was run, if any #[cfg(feature = "tmux_2_4")] pub fn hook_session_name(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::HookSessionName(v)); self } /// `hook_window` - ID of window where hook was run, if any #[cfg(feature = "tmux_2_4")] pub fn hook_window(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::HookWindow(v)); self } /// `hook_window_name` - Name of window where hook was run, if any #[cfg(feature = "tmux_2_4")] pub fn hook_window_name(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::HookWindowName(v)); self } // host /// `host` - Hostname of local host #[cfg(feature = "tmux_1_6")] pub fn host(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::Host(v)); self } /// `host_short` - #h Hostname of local host (no domain name) #[cfg(feature = "tmux_1_9")] pub fn host_short(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::HostShort(v)); self } /// `insert_flag` - Pane insert flag #[cfg(feature = "tmux_1_8")] pub fn insert_flag(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::InsertFlag(v)); self } /// `keypad_cursor_flag` - Pane keypad cursor flag #[cfg(feature = "tmux_1_8")] pub fn keypad_cursor_flag(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::KeypadCursorFlag(v)); self } /// `keypad_flag` - Pane keypad flag #[cfg(feature = "tmux_1_8")] pub fn keypad_flag(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::KeypadFlag(v)); self } /// `line` - Line number in the list #[cfg(feature = "tmux_1_6")] pub fn line(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::Line(v)); self } // `mouse_all_flag` - Pane mouse all flag //#[cfg(feature = "tmux_3_0")] //pub fn mouse_all_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self { //self.push(VariableOutput::MouseAllFlag(v)); //self //} /// `mouse_any_flag` - Pane mouse any flag #[cfg(feature = "tmux_1_8")] pub fn mouse_any_flag(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::MouseAnyFlag(v)); self } /// `mouse_button_flag` - Pane mouse button flag #[cfg(feature = "tmux_1_8")] pub fn mouse_button_flag(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::MouseButtonFlag(v)); self } /// `mouse_line` - Line under mouse, if any #[cfg(feature = "tmux_3_0")] pub fn mouse_line(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::MouseLine(v)); self } /// `sgr_flag` - Pane mouse SGR flag #[cfg(feature = "tmux_3_0")] pub fn sgr_line(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::MouseSgrFlag(v)); self } /// `mouse_standard_flag` - Pane mouse standard flag #[cfg(feature = "tmux_1_8")] pub fn mouse_standard_flag(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::MouseStandardFlag(v)); self } /// `mouse_utf8_flag` - Pane mouse UTF-8 flag #[cfg(all(feature = "tmux_1_8", not(feature = "tmux_2_2"), feature = "tmux_3_0"))] pub fn mouse_utf8_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::MouseUtf8Flag(v)); self } /// `mouse_all_flag` - Pane mouse all flag #[cfg(feature = "tmux_2_4")] pub fn mouse_all_flag(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::MouseAllFlag(v)); self } /// `mouse_word` - Word under mouse, if any #[cfg(feature = "tmux_3_0")] pub fn mouse_word(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::MouseWord(v)); self } /// `mouse_x` - Mouse X position, if any #[cfg(feature = "tmux_3_0")] pub fn mouse_x(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::MouseX(v)); self } /// `mouse_y` - Mouse Y position, if any #[cfg(feature = "tmux_3_0")] pub fn mouse_y(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::MouseY(v)); self } /// `origin_flag` - Pane origin flag #[cfg(feature = "tmux_3_0")] pub fn origin_flag(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::OriginFlag(v)); self } // pane /// `pane_active` - 1 if active pane #[cfg(feature = "tmux_1_6")] pub fn pane_active(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::PaneActive(v)); self } /// `pane_at_bottom` - 1 if pane is at the bottom of window #[cfg(feature = "tmux_2_6")] pub fn pane_at_bottom(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::PaneAtBottom(v)); self } /// `pane_at_left` - 1 if pane is at the left of window #[cfg(feature = "tmux_2_6")] pub fn pane_at_left(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::PaneAtLeft(v)); self } /// `pane_at_right` - 1 if pane is at the right of window #[cfg(feature = "tmux_2_6")] pub fn pane_at_right(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::PaneAtRight(v)); self } /// `pane_at_top` - 1 if pane is at the top of window #[cfg(feature = "tmux_2_6")] pub fn pane_at_top(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::PaneAtTop(v)); self } /// `pane_bottom` - Bottom of pane #[cfg(feature = "tmux_2_0")] pub fn pane_bottom(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::PaneBottom(v)); self } /// `pane_current_command` - Current command if available #[cfg(feature = "tmux_1_8")] pub fn pane_current_command(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::PaneCurrentCommand(v)); self } /// `pane_current_path` - Current path if available #[cfg(feature = "tmux_1_7")] pub fn pane_current_path(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::PaneCurrentPath(v)); self } /// `pane_dead` - 1 if pane is dead #[cfg(feature = "tmux_1_6")] pub fn pane_dead(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::PaneDead(v)); self } /// `pane_dead_status` - Exit status of process in dead pane #[cfg(feature = "tmux_2_0")] pub fn pane_dead_status(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::PaneDeadStatus(v)); self } /// `pane_format` - 1 if format is for a pane #[cfg(feature = "tmux_2_6")] pub fn pane_format(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::PaneFormat(v)); self } /// `pane_height` - Height of pane #[cfg(feature = "tmux_1_6")] pub fn pane_height(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::PaneHeight(v)); self } /// `pane_id` - #D Unique pane ID #[cfg(feature = "tmux_1_6")] pub fn pane_id(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::PaneId(v)); self } /// `pane_in_mode` - 1 if pane is in a mode #[cfg(feature = "tmux_1_8")] pub fn pane_in_mode(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::PaneInMode(v)); self } /// `pane_index` - #P Index of pane #[cfg(feature = "tmux_1_7")] pub fn pane_index(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::PaneIndex(v)); self } /// `pane_input_off` - 1 if input to pane is disabled #[cfg(feature = "tmux_2_0")] pub fn pane_input_off(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::PaneInputOff(v)); self } /// `pane_left` - Left of pane #[cfg(feature = "tmux_2_0")] pub fn pane_left(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::PaneLeft(v)); self } /// `pane_marked` - 1 if this is the marked pane #[cfg(feature = "tmux_3_0")] pub fn pane_marked(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::PaneMarked(v)); self } /// `pane_marked_set` - 1 if a marked pane is set #[cfg(feature = "tmux_3_0")] pub fn pane_marked_set(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::PaneMarkedSet(v)); self } /// `pane_mode` - Name of pane mode, if any #[cfg(feature = "tmux_2_5")] pub fn pane_mode(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::PaneMode(v)); self } /// `pane_path` - #T Path of pane (can be set by application) #[cfg(feature = "tmux_3_1")] pub fn pane_path(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::PanePath(v)); self } /// `pane_pid` - PID of first process in pane #[cfg(feature = "tmux_1_6")] pub fn pane_pid(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::PanePid(v)); self } /// `pane_pipe` - 1 if pane is being piped #[cfg(feature = "tmux_2_6")] pub fn pane_pipe(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::PanePipe(v)); self } /// `pane_right` - Right of pane #[cfg(feature = "tmux_2_0")] pub fn pane_right(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::PaneRight(v)); self } /// `pane_search_string` - Last search `Option<String>` in copy mode #[cfg(feature = "tmux_2_5")] pub fn pane_search_string(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::PaneSearchString(v)); self } /// `pane_start_command` - Command pane started with #[cfg(feature = "tmux_1_6")] pub fn pane_start_command(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::PaneStartCommand(v)); self } /// `pane_start_path` - Path pane started with #[cfg(all(feature = "tmux_1_6", not(feature = "tmux_2_0")))] pub fn pane_start_path(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::PaneStartPath(v)); self } /// `pane_synchronized` - 1 if pane is synchronized #[cfg(feature = "tmux_1_9")] pub fn pane_synchronized(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::PaneSynchronized(v)); self } /// `pane_tabs` - Pane tab positions #[cfg(feature = "tmux_1_8")] pub fn pane_tabs(&mut self, v: &'a mut Option<PaneTabs>) -> &mut Self { self.push(VariableOutput::PaneTabs(v)); self } /// `pane_title` - #T Title of pane (can be set by application) #[cfg(feature = "tmux_1_6")] pub fn pane_title(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::PaneTitle(v)); self } /// `pane_top` - Top of pane #[cfg(feature = "tmux_2_0")] pub fn pane_top(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::PaneTop(v)); self } /// `pane_tty` - Pseudo terminal of pane #[cfg(feature = "tmux_1_6")] pub fn pane_tty(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::PaneTty(v)); self } /// `pane_width` - Width of pane #[cfg(feature = "tmux_1_6")] pub fn pane_width(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::PaneWidth(v)); self } /// `saved_cursor_x` - Saved cursor X in pane #[cfg(any(feature = "tmux_1_8", not(feature = "tmux_2_1")))] pub fn saved_cursor_x(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SavedCursorX(v)); self } /// `saved_cursor_y` - Saved cursor Y in pane #[cfg(any(feature = "tmux_1_8", not(feature = "tmux_2_1")))] pub fn saved_cursor_y(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SavedCursorY(v)); self } /// `pid` - Server PID #[cfg(feature = "tmux_2_1")] pub fn pid(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::Pid(v)); self } /// `rectangle_toggle` - 1 if rectangle selection is activated #[cfg(feature = "tmux_2_7")] pub fn rectangle_toggle(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::RectangleToggle(v)); self } /// `scroll_position` - Scroll position in copy mode #[cfg(feature = "tmux_2_2")] pub fn scroll_position(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::ScrollPosition(v)); self } /// `scroll_region_lower` - Bottom of scroll region in pane #[cfg(feature = "tmux_1_8")] pub fn scroll_region_lower(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::ScrollRegionLower(v)); self } /// `scroll_region_upper` - Top of scroll region in pane #[cfg(feature = "tmux_1_8")] pub fn scroll_region_upper(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::ScrollRegionUpper(v)); self } /// `selection_active` - 1 if selection started and changes with the curso #[cfg(feature = "tmux_3_1")] pub fn selection_active(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::SelectionActive(v)); self } /// `selection_end_x` - X position of the end of the selection #[cfg(feature = "tmux_3_1")] pub fn selection_end_x(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SelectionEndX(v)); self } /// `selection_end_y` - Y position of the end of the selection #[cfg(feature = "tmux_3_1")] pub fn selection_end_y(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SelectionEndY(v)); self } /// `selection_present` - 1 if selection started in copy mode #[cfg(feature = "tmux_2_6")] pub fn selection_present(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::SelectionPresent(v)); self } /// `selection_start_x` - X position of the start of the selection #[cfg(feature = "tmux_3_1")] pub fn selection_start_x(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SelectionStartX(v)); self } /// `selection_start_y` - Y position of the start of the selection #[cfg(feature = "tmux_3_1")] pub fn selection_start_y(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SelectionStartY(v)); self } // Session /// `session_activity` - Time of session last activity #[cfg(feature = "tmux_2_1")] pub fn session_activity(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SessionActivity(v)); self } /// `session_activity_string` - Option<String> time of session last activity #[cfg(all(feature = "tmux_2_1", not(feature = "tmux_2_2")))] pub fn session_activity_string(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::SessionActivityString(v)); self } /// `session_alerts` - List of window indexes with alerts #[cfg(feature = "tmux_2_1")] pub fn session_alerts(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::SessionAlerts(v)); self } /// `session_attached` - Number of clients session is attached to #[cfg(feature = "tmux_1_6")] pub fn session_attached(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SessionAttached(v)); self } /// `session_attached_list` - List of clients session is attached to #[cfg(feature = "tmux_3_1")] pub fn session_attached_list(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SessionAttachedList(v)); self } /// `session_created` - Time session created #[cfg(feature = "tmux_1_6")] pub fn session_created(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SessionCreated(v)); self } /// `session_created_string` - Option<String> time session created #[cfg(all(feature = "tmux_1_6", not(feature = "tmux_2_2")))] pub fn session_created_string(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::SessionCreatedString(v)); self } /// `session_format` - 1 if format is for a session (not assuming the current) #[cfg(feature = "tmux_2_6")] pub fn session_format(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::SessionFormat(v)); self } /// `session_group` - Name of session group #[cfg(feature = "tmux_1_6")] pub fn session_group(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::SessionGroup(v)); self } /// `session_group_attached` - Number of clients sessions in group are attached > #[cfg(feature = "tmux_3_1")] pub fn session_group_attached(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SessionGroupAttached(v)); self } /// `session_group_attached_list` - List of clients sessions in group are attached to #[cfg(feature = "tmux_3_1")] pub fn session_group_attached_list(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::SessionGroupAttachedList(v)); self } /// `session_group_list` - List of sessions in group #[cfg(feature = "tmux_2_7")] pub fn session_group_list(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::SessionGroupList(v)); self } /// `session_group_many_attached` - 1 if multiple clients attached to sessions in gro #[cfg(feature = "tmux_3_1")] pub fn session_group_many_attached(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::SessionGroupManyAttached(v)); self } /// `session_group_size` - Size of session group #[cfg(feature = "tmux_2_7")] pub fn session_group_size(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::SessionGroupSize(v)); self } /// `session_grouped` - 1 if session in a group #[cfg(feature = "tmux_1_6")] pub fn session_grouped(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::SessionGrouped(v)); self } /// `session_height` - Height of session #[cfg(all(feature = "tmux_1_6", not(feature = "tmux_2_9")))] pub fn session_height(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SessionHeight(v)); self } /// `session_width` - Width of session #[cfg(all(feature = "tmux_1_6", not(feature = "tmux_2_9")))] pub fn session_width(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SessionWidth(v)); self } /// `session_id` - Unique session ID #[cfg(feature = "tmux_1_8")] pub fn session_id(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SessionId(v)); self } /// `session_last_attached` - Time session last attached #[cfg(feature = "tmux_2_1")] pub fn session_last_attached(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SessionLastAttached(v)); self } /// `session_last_attached_string` - Option<String> time session last attached #[cfg(all(feature = "tmux_2_1", not(feature = "tmux_2_2")))] pub fn session_last_attached_string(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::SessionLastAttachedString(v)); self } /// `session_many_attached` - 1 if multiple clients attached #[cfg(feature = "tmux_2_0")] pub fn session_many_attached(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::SessionManyAttached(v)); self } /// `session_name` - #S Name of session #[cfg(feature = "tmux_1_6")] pub fn session_name(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::SessionName(v)); self } /// `session_stack` - Window indexes in most recent order #[cfg(feature = "tmux_2_5")] pub fn session_stack(&mut self, v: &'a mut Option<SessionStack>) -> &mut Self { self.push(VariableOutput::SessionStack(v)); self } /// `session_windows` - Number of windows in session #[cfg(feature = "tmux_1_6")] pub fn session_windows(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::SessionWindows(v)); self } /// `socket_path` - Server socket path #[cfg(feature = "tmux_2_2")] pub fn socket_path(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::SocketPath(v)); self } /// `start_time` - Server start time #[cfg(feature = "tmux_2_2")] pub fn start_time(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::StartTime(v)); self } /// `version` - Server version #[cfg(feature = "tmux_2_4")] pub fn version(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::Version(v)); self } // Window // /// `window_active` - 1 if window active #[cfg(feature = "tmux_1_6")] pub fn window_active(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::WindowActive(v)); self } /// `window_active_clients` - Number of clients viewing this window #[cfg(feature = "tmux_3_1")] pub fn window_active_clients(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::WindowActiveClients(v)); self } /// `window_active_clients_list` - List of clients viewing this window #[cfg(feature = "tmux_3_1")] pub fn window_active_clients_list(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::WindowActiveClientsList(v)); self } /// `window_active_sessions` - Number of sessions on which this window is active #[cfg(feature = "tmux_3_1")] pub fn window_active_sessions(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::WindowActiveSessions(v)); self } /// `window_active_sessions_list` - List of sessions on which this window is active #[cfg(feature = "tmux_3_1")] pub fn window_active_sessions_list(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::WindowActiveSessionsList(v)); self } /// `window_activity` - Time of window last activity #[cfg(feature = "tmux_2_1")] pub fn window_activity(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::WindowActivity(v)); self } /// `window_activity_string` - String time of window last activity #[cfg(all(feature = "tmux_2_1", not(feature = "tmux_2_2")))] pub fn window_activity_string(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::WindowActivityString(v)); self } /// `window_activity_flag` - 1 if window has activity #[cfg(any( all(feature = "tmux_1_9", not(feature = "tmux_2_2")), feature = "tmux_2_3" ))] pub fn window_activity_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::WindowActivityFlag(v)); self } /// `window_bell_flag` - 1 if window has bell #[cfg(feature = "tmux_1_9")] pub fn window_bell_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::WindowBellFlag(v)); self } /// `window_content_flag` - 1 if window has content alert #[cfg(all(feature = "tmux_1_9", not(feature = "tmux_2_0")))] pub fn window_content_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::WindowContentFlag(v)); self } /// `window_bigger` - 1 if window is larger than client #[cfg(feature = "tmux_2_9")] pub fn window_bigger(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::WindowBigger(v)); self } /// `window_cell_height` - Height of each cell in pixels #[cfg(feature = "tmux_3_1")] pub fn window_cell_height(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::WindowCellHeight(v)); self } /// `window_cell_width` - Width of each cell in pixels #[cfg(feature = "tmux_3_1")] pub fn window_cell_width(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::WindowCellWidth(v)); self } /// `window_end_flag` - 1 if window has the highest index #[cfg(feature = "tmux_2_9")] pub fn window_end_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::WindowEndFlag(v)); self } /// `window_find_matches` - Matched data from the find-window command if available #[cfg(all(feature = "tmux_1_7", not(feature = "tmux_2_6")))] pub fn window_find_matches(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::WindowFindMatches(v)); self } /// `window_flags` - #F Window flags #[cfg(feature = "tmux_1_6")] pub fn window_flags(&mut self, v: &'a mut Option<WindowFlags>) -> &mut Self { self.push(VariableOutput::WindowFlags(v)); self } // TODO: WindowRawFlags /// `window_raw_flags` - Window flags with nothing escaped #[cfg(feature = "tmux_3_2")] pub fn window_raw_flags(&mut self, v: &'a mut Option<WindowFlags>) -> &mut Self { self.push(VariableOutput::WindowRawFlags(v)); self } /// `window_format` - 1 if format is for a window #[cfg(feature = "tmux_2_6")] pub fn window_format(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::WindowFormat(v)); self } /// `window_height` - Height of window #[cfg(feature = "tmux_1_6")] pub fn window_height(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::WindowHeight(v)); self } /// `window_id` - Unique window ID #[cfg(feature = "tmux_1_7")] pub fn window_id(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::WindowId(v)); self } /// `window_index` - #I Index of window #[cfg(feature = "tmux_1_6")] pub fn window_index(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::WindowIndex(v)); self } /// `window_last_flag` - 1 if window is the last used #[cfg(feature = "tmux_2_0")] pub fn window_last_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::WindowLastFlag(v)); self } /// `window_layout` - Window layout description, ignoring zoomed window panes #[cfg(feature = "tmux_1_6")] pub fn window_layout(&mut self, v: &'a mut Option<Layout>) -> &mut Self { self.push(VariableOutput::WindowLayout(v)); self } /// `window_linked` - 1 if window is linked across sessions #[cfg(feature = "tmux_2_1")] pub fn window_linked(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::WindowLinked(v)); self } /// `window_linked_sessions` - Number of sessions this window is linked to #[cfg(feature = "tmux_3_1")] pub fn window_linked_sessions(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::WindowLinkedSessions(v)); self } /// `window_linked_sessions_list` - List of sessions this window is linked to #[cfg(feature = "tmux_3_1")] pub fn window_linked_sessions_list(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::WindowLinkedSessionsList(v)); self } /// `window_marked_flag` - 1 if window contains the marked pane #[cfg(feature = "tmux_3_1")] pub fn window_marked_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::WindowMarkedFlag(v)); self } /// `window_name` - #W Name of window #[cfg(feature = "tmux_1_6")] pub fn window_name(&mut self, v: &'a mut Option<String>) -> &mut Self { self.push(VariableOutput::WindowName(v)); self } /// `window_offset_x` - X offset into window if larger than client #[cfg(feature = "tmux_2_9")] pub fn window_offset_x(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::WindowOffsetX(v)); self } /// `window_offset_y` - Y offset into window if larger than client #[cfg(feature = "tmux_2_9")] pub fn window_offset_y(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::WindowOffsetY(v)); self } /// `window_panes` - Number of panes in window #[cfg(feature = "tmux_1_7")] pub fn window_panes(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::WindowPanes(v)); self } /// `window_silence_flag` - 1 if window has silence alert #[cfg(feature = "tmux_1_9")] pub fn window_silence_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::WindowSilenceFlag(v)); self } /// `window_stack_index` - Index in session most recent stack #[cfg(feature = "tmux_2_5")] pub fn window_stack_index(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::WindowStackIndex(v)); self } /// `window_start_flag` - 1 if window has the lowest index #[cfg(feature = "tmux_2_9")] pub fn window_start_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::WindowStartFlag(v)); self } /// `window_visible_layout` - Window layout description, respecting zoomed window panes #[cfg(feature = "tmux_2_2")] pub fn window_visible_layout(&mut self, v: &'a mut Option<Layout>) -> &mut Self { self.push(VariableOutput::WindowVisibleLayout(v)); self } /// `window_width` - Width of window #[cfg(feature = "tmux_1_6")] pub fn window_width(&mut self, v: &'a mut Option<usize>) -> &mut Self { self.push(VariableOutput::WindowWidth(v)); self } /// `window_zoomed_flag` - 1 if window is zoomed #[cfg(feature = "tmux_2_0")] pub fn window_zoomed_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::WindowZoomedFlag(v)); self } /// `wrap_flag` - Pane wrap flag #[cfg(feature = "tmux_1_8")] pub fn wrap_flag(&mut self, v: &'a mut Option<bool>) -> &mut Self { self.push(VariableOutput::WrapFlag(v)); self } }
true
a67a875f18fff072f6a98e8e3f032f1ae6188089
Rust
azriel91/autexousious
/crate/game_input_model/src/loaded/control_axis.rs
UTF-8
441
2.796875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
use strum_macros::{Display, EnumIter, EnumString}; /// Control axis input for characters. /// /// This is not used in `PlayerInputConfigs`, but as a logical representation #[derive(Clone, Copy, Debug, Display, EnumIter, EnumString, Hash, PartialEq, Eq)] #[strum(serialize_all = "snake_case")] pub enum ControlAxis { /// Up button. Up, /// Down button. Down, /// Left button. Left, /// Right button. Right, }
true
a936a09f5d895b5afde9355857431cb9846f79b7
Rust
michaelfletchercgy/rainguage
/rainguage-messages/src/lib.rs
UTF-8
10,872
2.65625
3
[]
no_license
#![no_std] use serde::{Serialize, Deserialize}; use crc::{crc32, Hasher32}; use core::iter::Iterator; use byteorder::ByteOrder; use byteorder::NetworkEndian; const MAGIC:[u8;3] = [125, 8, 141]; #[derive(Debug)] pub enum SerializeError { Internal(postcard::Error) } impl From<postcard::Error> for SerializeError { fn from(err: postcard::Error) -> Self { SerializeError::Internal(err) } } #[derive(Debug, PartialEq)] pub enum DeserializeError { SerializeError(postcard::Error), InvalidLength, InvalidChecksum{ crc32_buf: [u8;4], msg_buf: [u8; 64], msg_len: u8 } } impl From<postcard::Error> for DeserializeError { fn from(err: postcard::Error) -> Self { DeserializeError::SerializeError(err) } } // // ReadingMagic -> ReadingLength -> ReadingBytes -> ReadingChecksum // #[derive(Debug)] enum IteratorState { ReadingMagic{ bytes_read:u8 }, ReadingLength, ReadingBytes{ msg_len: u8, num_read: usize, msg_buf: [u8; 64] }, ReadingChecksum { num_read: usize, crc32_buf: [u8;4], msg_buf: [u8; 64], msg_len: u8 } } // Wraps an iterator of bytes pub struct PacketIterator <I:Iterator<Item=u8>> { byte_iter:I, state:IteratorState } impl <I:Iterator<Item=u8>> PacketIterator<I> { pub fn new(byte_iter:I) -> PacketIterator<I> { PacketIterator { byte_iter, state:IteratorState::ReadingMagic { bytes_read: 0 } } } } impl <'a, I:Iterator<Item=u8>> Iterator for PacketIterator<I> { type Item = Result<TelemetryPacket, DeserializeError>; fn next(&mut self) -> Option<Result<TelemetryPacket, DeserializeError>> { loop { match self.byte_iter.next() { Some(byte) => { //println!("byte={}", byte); match self.state { IteratorState::ReadingMagic {ref mut bytes_read } => { if *bytes_read > 3 { *bytes_read = 0; } else if byte == MAGIC[*bytes_read as usize] { *bytes_read = *bytes_read + 1; } if *bytes_read == 3 { self.state = IteratorState::ReadingLength; } }, IteratorState::ReadingLength => { if byte > 64 { self.state = IteratorState::ReadingMagic{ bytes_read:0 }; return Some(Result::Err(DeserializeError::InvalidLength)); } self.state = IteratorState::ReadingBytes { msg_len:byte, num_read:0, msg_buf: [0u8; 64] }; }, IteratorState::ReadingBytes{msg_len, ref mut num_read, ref mut msg_buf} => { msg_buf[*num_read] = byte; *num_read += 1; if *num_read >= msg_len.into() { self.state = IteratorState::ReadingChecksum { num_read:0, msg_buf:*msg_buf, msg_len, crc32_buf: [0u8; 4] }; } }, IteratorState::ReadingChecksum{ref mut num_read, msg_buf, msg_len, ref mut crc32_buf} => { crc32_buf[*num_read] = byte; *num_read += 1; if *num_read >= 4 { let mut digest = crc32::Digest::new(crc32::IEEE); digest.write(&msg_buf[0..msg_len as usize]); let calculated_sum = digest.sum32(); let provided_sum = NetworkEndian::read_u32(crc32_buf); let clone_buf = crc32_buf.clone(); self.state = IteratorState::ReadingMagic { bytes_read:0 }; if calculated_sum == provided_sum { match postcard::from_bytes(&msg_buf[0..msg_len as usize]) { Ok(packet) => { return Some(Result::Ok(packet)); }, Err(err) => { return Some(Result::Err(DeserializeError::SerializeError(err))); } } } else { return Some(Result::Err(DeserializeError::InvalidChecksum{ msg_buf, msg_len, crc32_buf:clone_buf })); } } } } }, None => { return Option::None; } }; } } } #[derive(Serialize, Deserialize, Debug, PartialEq)] /// TelemetryPacket is sent from the rainguage. pub struct TelemetryPacket { /// The hardware identifier pub device_id: [u8; 16], /// The number of loops that have been run. The device has no clock so this is an approximation of time. It /// will wrap back to 0. pub loop_cnt: u32, /// The number of times the rainguage has tipped over. pub tip_cnt: u32, /// The last voltage recorded by the battery. pub vbat: u32, pub temperature: f32, pub relative_humidity: f32, pub usb_bytes_read: u32, pub usb_bytes_written: u32, pub usb_error_cnt: u32, pub lora_rx_bytes: u32, pub lora_tx_bytes: u32, pub lora_error_cnt: u32, /// The number of other hardware errors that occured. This is an error outside of a more specific hardware error. Things like flashing /// leds. pub hardware_err_other_cnt: u32 } impl TelemetryPacket { pub fn new() -> TelemetryPacket { TelemetryPacket { device_id: [0; 16], loop_cnt: 0, tip_cnt: 0, vbat: 0, temperature: 0.0, relative_humidity: 0.0, usb_bytes_read: 0, usb_bytes_written: 0, usb_error_cnt: 0, lora_rx_bytes: 0, lora_tx_bytes: 0, lora_error_cnt: 0, hardware_err_other_cnt: 0 } } } // Serialize a telemetry packet into a byte buffer returning the length of the written bytes. // // The packet is written including a magic value, bytes and a checksum. The format is // // magic 3 bytes - always 125, 8, 141 // len 1 byte - length of bytes packet) // bytes `len` bytes - payload // checksum 4 bytes, a crc32 checksum of `bytes` (u32 in network byte order) pub fn serialize(telem:&TelemetryPacket, buf:&mut [u8]) -> Result<usize, SerializeError> { // Write magic into the first three bytes buf[0] = MAGIC[0]; buf[1] = MAGIC[1]; buf[2] = MAGIC[2]; // Serialize the telemetry packet let result = postcard::to_slice(telem, &mut buf[4..])?; let len = result.len(); // Calculate the crc32 checksum let mut digest = crc32::Digest::new(crc32::IEEE); digest.write(result); let checksum = digest.sum32(); // Write the length into the buffer buf[3] = result.len() as u8; // Write the checksum into the buffer. NetworkEndian::write_u32(&mut buf[len + 4..len+4+4+1], checksum); // write the sum in Ok(3 + 1 + len + 4) } #[cfg(test)] #[macro_use] extern crate std; #[cfg(test)] mod tests { #[test] fn largest_packet() { let mut packet = super::TelemetryPacket::new(); packet.device_id = [255; 16]; packet.loop_cnt = u32::MAX; packet.tip_cnt = u32::MAX; packet.vbat = u32::MAX; packet.temperature = 0.0; packet.relative_humidity = 0.0; packet.usb_bytes_read = u32::MAX; packet.usb_bytes_written = u32::MAX; packet.usb_error_cnt = u32::MAX; packet.lora_rx_bytes = u32::MAX; packet.lora_tx_bytes = u32::MAX; packet.lora_error_cnt = u32::MAX; packet.hardware_err_other_cnt = u32::MAX; let mut buf:[u8; 127] = [0; 127]; let cnt = super::serialize(&packet, &mut buf).unwrap(); println!("{:?}", buf); assert_eq!(72, cnt); } #[test] fn test_serialize_deserialize_zero() { let mut buf:[u8; 255] = [0; 255]; let packet = super::TelemetryPacket::new(); super::serialize(&packet, &mut buf).unwrap(); println!("{:?}", buf); let bytes = buf.iter() .map(|byte| *byte); let mut iter = super::PacketIterator::new(bytes); assert_eq!(Some(Ok(packet)), iter.next()); assert_eq!(None, iter.next()); } #[test] fn test_serialize_deserialize_full() { let mut buf:[u8; 255] = [0; 255]; let mut packet = super::TelemetryPacket::new(); packet.device_id = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 130, 140, 150, 160, 170]; packet.loop_cnt = 180; packet.vbat = 190 as u32; packet.usb_bytes_read = 200; packet.usb_error_cnt = 210; packet.lora_error_cnt = 220; packet.lora_tx_bytes = 230; super::serialize(&packet, &mut buf).unwrap(); let bytes = buf.iter() .map(|byte| *byte); let mut iter = super::PacketIterator::new(bytes); let first_packet = iter.next().unwrap().unwrap(); assert_eq!(packet, first_packet); assert_eq!(None, iter.next()); } #[test] fn test_bad_checksum() { let mut buf:[u8; 128] = [0; 128]; let packet = super::TelemetryPacket::new(); super::serialize(&packet, &mut buf).unwrap(); // Random Change buf[28] = 23; let bytes = buf.iter() .map(|byte| *byte); let mut iter = super::PacketIterator::new(bytes); if let Some(Err(_)) = iter.next() { } else { panic!("expected to get an error"); } assert_eq!(None, iter.next()); } }
true
c96ffdf4ce028903abd2c5f8f8af36bd4802a0fe
Rust
lwandsyj/rust
/lear2/src/fn_learn.rs
UTF-8
457
3.640625
4
[]
no_license
pub fn test(mut a: i32) -> i32 { a = a + 1; a } pub fn test_brow(a: &mut i32) -> i32 { *a = *a + 1; *a } /** * 调用 * let mut a = 1; let b = test_brow(&mut a); println!("{}", a); println!("{}", b); */ // 引用类型数组可以是不固定长度 fn test1(a:&[i32]){ println!("{:?}",a); } fn main1() { let a:[i32;5]=[1,2,3,4,5]; test1(&a); println!("{:?}",a); let b:[i32;3]=[3,4,5]; test1(&b); }
true
fa48ace6d44158d05469e73fe64e130b9a9d89bf
Rust
vinhhungle/webassembly-react
/rust-wasm/src/condition.rs
UTF-8
345
3.21875
3
[]
no_license
pub fn run() { let age: u8 = 18; let is_of_age = age >= 21; // if age >= 21 { true } else { false } let check_id: bool = false; if is_of_age && check_id { println!("What would you like to drink?") } else if !is_of_age && check_id { println!("Sorry, you have to leave") } else { println!("I'll need to see your ID") } }
true
f882a7f4a73e5e42c780f1c2ad2861aebf7630de
Rust
a-bakos/rust-playground
/archived-learning/hands-on-data-structures-and-algorithms-in-rust/p03-copy-clone-mut/src/main.rs
UTF-8
484
3.796875
4
[]
no_license
// i32 implements Copy marker trait // it means it'll automatically copy all of the memory across #[derive(Debug, Clone)] pub struct Person { name: String, age: i32, } fn main() { let p = Person { name: "Frank".to_string(), age: 6, }; // if the struct doesn't have a clone marker trait implemented, // now we'd have two variables pointing to the same memory, aka p2 = p let p2 = p.clone(); println!("p = {:?}, p2 = {:?}", p, p2); }
true
32b2d5090f408320f38da66b0cafd85473979f43
Rust
RussellChamp/advent-of-code-2016
/2016/day18/src/main.rs
UTF-8
3,519
3.328125
3
[ "MIT" ]
permissive
// Trap rules // * if 110 or 011, 100, 001 // where nonexistent sides are considered 0 #[derive(Debug, PartialEq, Clone)] enum Tile { Trapped = 1, Safe = 0 } type Row = Vec<Tile>; type Grid = Vec<Row>; //Part 1 fn add_row(grid: &mut Grid) { static TRAPS: [[Tile; 3]; 4] = [ [Tile::Trapped, Tile::Trapped, Tile::Safe], [Tile::Safe, Tile::Trapped, Tile::Trapped], [Tile::Trapped, Tile::Safe, Tile::Safe], [Tile::Safe, Tile::Safe, Tile::Trapped], ]; let last_row = grid.clone().into_iter().last().unwrap(); //println!("Last row {:?}", last_row); let mut new_row: Row = vec![]; for idx in 0..last_row.len() { let mut pre: [Tile; 3] = [Tile::Safe, Tile::Safe, Tile::Safe]; if idx > 0 { pre[0] = last_row[idx - 1].clone(); } pre[1] = last_row[idx].clone(); if idx + 1 < last_row.len() { pre[2] = last_row[idx + 1].clone(); } if TRAPS.contains(&pre) { new_row.push(Tile::Trapped); } else { new_row.push(Tile::Safe); } } //println!("New row: {:?}", new_row); grid.push(new_row); } fn create_grid(rows: usize) -> Grid { let first_row: Row = String::from(".^..^....^....^^.^^.^.^^.^.....^.^..^...^^^^^^.^^^^.^.^^^^^^^.^^^^^..^.^^^.^^..^.^^.^....^.^...^^.^.") .chars().map(|c| { match c { '^' => Tile::Trapped, _ => Tile::Safe, } }).collect::<Row>(); let mut grid: Grid = vec![first_row]; while grid.len() < rows { add_row(&mut grid); } grid } // Part 2 fn step_row(last_row: &mut Row) -> i64 { static TRAPS: [[Tile; 3]; 4] = [ [Tile::Trapped, Tile::Trapped, Tile::Safe], [Tile::Safe, Tile::Trapped, Tile::Trapped], [Tile::Trapped, Tile::Safe, Tile::Safe], [Tile::Safe, Tile::Safe, Tile::Trapped], ]; let mut new_row: Row = vec![]; let mut safe_tiles = 0; for idx in 0..last_row.len() { let mut pre: [Tile; 3] = [Tile::Safe, Tile::Safe, Tile::Safe]; if idx > 0 { pre[0] = last_row[idx - 1].clone(); } pre[1] = last_row[idx].clone(); if idx + 1 < last_row.len() { pre[2] = last_row[idx + 1].clone(); } if TRAPS.contains(&pre) { new_row.push(Tile::Trapped); } else { new_row.push(Tile::Safe); safe_tiles = safe_tiles + 1; } } *last_row = new_row; safe_tiles } fn main() { let grid = create_grid(40); let total_safe = grid.iter().fold(0, |sum, r| sum + r.iter().filter(|t| **t == Tile::Safe).count()); let total_trap = grid.iter().fold(0, |sum, r| sum + r.iter().filter(|t| **t == Tile::Trapped).count()); println!("Part 1: There are {} safe tiles and {} traps", total_safe, total_trap); //Need to improve the algorithm so it finishes in a sane amount of time let mut row: Row = String::from(".^..^....^....^^.^^.^.^^.^.....^.^..^...^^^^^^.^^^^.^.^^^^^^^.^^^^^..^.^^^.^^..^.^^.^....^.^...^^.^.") .chars().map(|c| { match c { '^' => Tile::Trapped, _ => Tile::Safe, } }).collect::<Row>(); let mut safe_tiles = 48; //from row 1 for _ in 0..400000 - 1 { safe_tiles = safe_tiles + step_row(&mut row); } println!("Part 2: There are {} safe tiles", safe_tiles); }
true
545012f4c355fa241565f3f8a3c323a1d4a9ff88
Rust
bokutotu/curs
/src/error.rs
UTF-8
4,563
2.765625
3
[]
no_license
use cublas_sys::cublasStatus_t; use cuda_runtime_sys::cudaError_t; use std::ffi::CStr; use std::fmt::{self, Debug, Display, Formatter, Result}; use std::result; use thiserror::Error; pub struct CublasError { pub raw: cublasStatus_t, } fn cublas_error_to_string(error: cublasStatus_t) -> String { let string = match error { cublasStatus_t::CUBLAS_STATUS_NOT_INITIALIZED => { "The cuBLAS library was not initialized. This is usually caused by the lack of a prior cublasCreate() call, an error in the CUDA Runtime API called by the cuBLAS routine, or an error in the hardware setup. To correct: call cublasCreate() prior to the function call; and check that the hardware, an appropriate version of the driver, and the cuBLAS library are correctly installed." } cublasStatus_t::CUBLAS_STATUS_ALLOC_FAILED => { "Resource allocation failed inside the cuBLAS library. This is usually caused by a cudaMalloc() failure. To correct: prior to the function call, deallocate previously allocated memory as much as possible." } cublasStatus_t::CUBLAS_STATUS_INVALID_VALUE => { "An unsupported value or parameter was passed to the function (a negative vector size, for example). To correct: ensure that all the parameters being passed have valid values." } cublasStatus_t::CUBLAS_STATUS_ARCH_MISMATCH => { "The function requires a feature absent from the device architecture; usually caused by compute capability lower than 5.0. To correct: compile and run the application on a device with appropriate compute capability." } cublasStatus_t::CUBLAS_STATUS_MAPPING_ERROR => { "An access to GPU memory space failed, which is usually caused by a failure to bind a texture. To correct: prior to the function call, unbind any previously bound textures." } cublasStatus_t::CUBLAS_STATUS_EXECUTION_FAILED => { "The GPU program failed to execute. This is often caused by a launch failure of the kernel on the GPU, which can be caused by multiple reasons. To correct: check that the hardware, an appropriate version of the driver, and the cuBLAS library are correctly installed." } cublasStatus_t::CUBLAS_STATUS_INTERNAL_ERROR => { "An internal cuBLAS operation failed. This error is usually caused by a cudaMemcpyAsync() failure. To correct: check that the hardware, an appropriate version of the driver, and the cuBLAS library are correctly installed. Also, check that the memory passed as a parameter to the routine is not being deallocated prior to the routine’s completion." } cublasStatus_t::CUBLAS_STATUS_NOT_SUPPORTED => { "The functionality requested is not supported" } cublasStatus_t::CUBLAS_STATUS_LICENSE_ERROR => { "The functionality requested requires some license and an error was detected when trying to check the current licensing. This error can happen if the license is not present or is expired or if the environment variable NVIDIA_LICENSE_FILE is not set properly." } _ => unreachable!(), }; string.to_string() } impl Debug for CublasError { fn fmt(&self, f: &mut Formatter) -> Result { let string = cublas_error_to_string(self.raw); f.debug_struct("cublasError") .field("error status", &self.raw) .field("content", &string) .finish() } } impl Display for CublasError { fn fmt(&self, f: &mut Formatter) -> Result { let string = cublas_error_to_string(self.raw); write!(f, "({})", string) } } pub struct CudaError { pub raw: cudaError_t, } impl Debug for CudaError { fn fmt(&self, f: &mut Formatter) -> result::Result<(), fmt::Error> { write!( f, "{}", unsafe { CStr::from_ptr(cuda_runtime_sys::cudaGetErrorString(self.raw)) } .to_string_lossy() ) } } impl Display for CudaError { fn fmt(&self, f: &mut Formatter) -> result::Result<(), fmt::Error> { write!( f, "{}", unsafe { CStr::from_ptr(cuda_runtime_sys::cudaGetErrorString(self.raw)) } .to_string_lossy() ) } } #[derive(Error, Debug)] pub enum Error { #[error("Cuda Error {0}")] Cuda(CudaError), #[error("cublas Error {0}")] Cublas(CublasError), }
true
ba5f9e5f0e0e9f5dfc7aae99bdb8e3f4bff64182
Rust
gkbrk/rust-gophermap
/src/lib.rs
UTF-8
7,404
3.484375
3
[ "MIT" ]
permissive
//! gophermap is a Rust crate that can parse and generate Gopher responses. //! It can be used to implement Gopher clients and servers. It doesn't handle //! any I/O on purpose. This library is meant to be used by other servers and //! clients in order to avoid re-implementing the gophermap logic. //! #![forbid(unsafe_code)] use std::io::Write; /// A single entry in a Gopher map. This struct can be filled in order to /// generate Gopher responses. It can also be the result of parsing one. pub struct GopherEntry<'a> { /// The type of the link pub item_type: ItemType, /// The human-readable description of the link. Displayed on the UI. pub display_string: &'a str, /// The target page (selector) of the link pub selector: &'a str, /// The host for the target of the link pub host: &'a str, /// The port for the target of the link pub port: u16, } impl<'a> GopherEntry<'a> { /// Parse a line into a Gopher directory entry. /// ```rust /// use gophermap::GopherEntry; /// let entry = GopherEntry::from("1Floodgap Home /home gopher.floodgap.com 70\r\n") /// .unwrap(); /// assert_eq!(entry.selector, "/home"); /// ``` pub fn from(line: &'a str) -> Option<Self> { let line = { let mut chars = line.chars(); if !(chars.next_back()? == '\n' && chars.next_back()? == '\r') { return None; } chars.as_str() }; let mut parts = line.split('\t'); Some(GopherEntry { item_type: ItemType::from(line.chars().next()?), display_string: { let part = parts.next()?; let (index, _) = part.char_indices().skip(1).next()?; &part[index..] }, selector: parts.next()?, host: parts.next()?, port: parts.next()?.parse().ok()?, }) } /// Serializes a Gopher entry into bytes. This function can be used to /// generate Gopher responses. pub fn write<W>(&self, mut buf: W) -> std::io::Result<()> where W: Write, { write!( buf, "{}{}\t{}\t{}\t{}\r\n", self.item_type.to_char(), self.display_string, self.selector, self.host, self.port )?; Ok(()) } } pub struct GopherMenu<W> where W: Write, { target: W, } impl<'a, W> GopherMenu<&'a W> where &'a W: Write, { pub fn with_write(target: &'a W) -> Self { GopherMenu { target: &target } } pub fn info(&self, text: &str) -> std::io::Result<()> { self.write_entry(ItemType::Info, text, "FAKE", "fake.host", 1) } pub fn error(&self, text: &str) -> std::io::Result<()> { self.write_entry(ItemType::Error, text, "FAKE", "fake.host", 1) } pub fn write_entry( &self, item_type: ItemType, text: &str, selector: &str, host: &str, port: u16, ) -> std::io::Result<()> { GopherEntry { item_type, display_string: text, selector, host, port, } .write(self.target) } pub fn end(&mut self) -> std::io::Result<()> { write!(self.target, ".\r\n") } } /// Item type for a Gopher directory entry #[derive(Debug, PartialEq)] pub enum ItemType { /// Item is a file File, /// Item is a directory Directory, /// Item is a CSO phone-book server CsoServer, /// Error Error, /// Item is a BinHexed Macintosh file. BinHex, /// Item is a DOS binary archive of some sort. /// Client must read until the TCP connection closes. Beware. DosBinary, /// Item is a UNIX uuencoded file. Uuencoded, /// Item is an Index-Search server. Search, /// Item points to a text-based telnet session. Telnet, /// Item is a binary file! /// Client must read until the TCP connection closes. Beware. Binary, /// Item is a redundant server RedundantServer, /// Item points to a text-based tn3270 session. Tn3270, /// Item is a GIF format graphics file. Gif, /// Item is some sort of image file. Client decides how to display. Image, /// Informational message Info, /// Other types Other(char), } impl ItemType { /// Parses a char into an Item Type pub fn from(c: char) -> Self { match c { '0' => ItemType::File, '1' => ItemType::Directory, '2' => ItemType::CsoServer, '3' => ItemType::Error, '4' => ItemType::BinHex, '5' => ItemType::DosBinary, '6' => ItemType::Uuencoded, '7' => ItemType::Search, '8' => ItemType::Telnet, '9' => ItemType::Binary, '+' => ItemType::RedundantServer, 'T' => ItemType::Tn3270, 'g' => ItemType::Gif, 'I' => ItemType::Image, 'i' => ItemType::Info, c => ItemType::Other(c), } } /// Turns an Item Type into a char pub fn to_char(&self) -> char { match self { ItemType::File => '0', ItemType::Directory => '1', ItemType::CsoServer => '2', ItemType::Error => '3', ItemType::BinHex => '4', ItemType::DosBinary => '5', ItemType::Uuencoded => '6', ItemType::Search => '7', ItemType::Telnet => '8', ItemType::Binary => '9', ItemType::RedundantServer => '+', ItemType::Tn3270 => 'T', ItemType::Gif => 'g', ItemType::Image => 'I', ItemType::Info => 'i', ItemType::Other(c) => *c, } } } #[cfg(test)] mod tests { use super::*; fn get_test_pairs() -> Vec<(String, GopherEntry<'static>)> { let mut pairs = Vec::new(); pairs.push(( "1Floodgap Home /home gopher.floodgap.com 70\r\n".to_owned(), GopherEntry { item_type: ItemType::Directory, display_string: "Floodgap Home", selector: "/home", host: "gopher.floodgap.com", port: 70, }, )); pairs.push(( "iWelcome to my page FAKE (NULL) 0\r\n".to_owned(), GopherEntry { item_type: ItemType::Info, display_string: "Welcome to my page", selector: "FAKE", host: "(NULL)", port: 0, }, )); return pairs; } #[test] fn test_parse() { for (raw, parsed) in get_test_pairs() { let entry = GopherEntry::from(&raw).unwrap(); assert_eq!(entry.item_type, parsed.item_type); assert_eq!(entry.display_string, parsed.display_string); assert_eq!(entry.selector, parsed.selector); assert_eq!(entry.host, parsed.host); assert_eq!(entry.port, parsed.port); } } #[test] fn test_write() { for (raw, parsed) in get_test_pairs() { let mut output = Vec::new(); parsed.write(&mut output).unwrap(); let line = String::from_utf8(output).unwrap(); assert_eq!(raw, line); } } }
true
2b767f69ea875614b833ec9e1a0a3fd6e55c467f
Rust
lRiaXl/public
/rust/tests/handling_test/src/main.rs
UTF-8
1,518
3.03125
3
[]
no_license
use std::fs::{File, OpenOptions}; use std::io::prelude::*; use std::io::{ErrorKind, Write}; use handling::*; fn main() { let path = "a.txt"; File::create(path).unwrap(); open_or_create(path, "content to be written"); let mut file = File::open(path).unwrap(); let mut s = String::new(); file.read_to_string(&mut s).unwrap(); println!("{}", s); // output: content to be written } #[cfg(test)] mod tests { use super::*; use std::fs; use std::panic; fn get_file_content(filename: &str) -> String { let mut file = File::open(filename).unwrap(); let mut s = String::new(); file.read_to_string(&mut s).unwrap(); fs::remove_file(filename).unwrap(); return s; } #[test] fn test_if_file_exists() { let filename = "test_existing_file.txt"; let content = "hello world!"; File::create(filename).unwrap(); open_or_create(filename, content); assert_eq!(content, get_file_content(filename)); } #[test] fn test_create_file() { let file = "no_existing_file.txt"; let content = "hello world!"; open_or_create(file, content); assert_eq!(content, get_file_content(file)); } #[test] fn test_error_case() { let filename = "hello.txt"; File::create(filename).unwrap(); let mut perms = fs::metadata(filename).unwrap().permissions(); perms.set_readonly(true); fs::set_permissions(filename, perms).unwrap(); let result = panic::catch_unwind(|| open_or_create(filename, "test")); fs::remove_file(filename).unwrap(); assert!(result.is_err()); } }
true
853818ae4a5022d99e5f1716821e20633639d1d7
Rust
loganyu/leetcode
/problems/039_combination_sum.rs
UTF-8
1,751
3.375
3
[]
no_license
/* Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input. Example 1: Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] Explanation: 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. Example 2: Input: candidates = [2,3,5], target = 8 Output: [[2,2,2,2],[2,3,3],[3,5]] Example 3: Input: candidates = [2], target = 1 Output: [] Constraints: 1 <= candidates.length <= 30 1 <= candidates[i] <= 200 All elements of candidates are distinct. 1 <= target <= 500 */ impl Solution { pub fn combination_sum(candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> { let mut combos = vec![]; Self::find_combos(&candidates, &mut vec![], &mut combos, target, 0); combos } fn find_combos(candidates: &Vec<i32>, cans: &mut Vec<i32>, combos: &mut Vec<Vec<i32>>, target: i32, idx: usize) { if target < 0 { return; } else if target == 0 { combos.push(cans.clone()); return; } for i in idx..candidates.len() { cans.push(candidates[i]); Self::find_combos(candidates, cans, combos, target - candidates[i], i); cans.pop(); } } }
true
9764428f58e3b7115da7f14af1e85b665bf17c63
Rust
rennis250/processing-rs
/src/transform.rs
UTF-8
5,690
3.109375
3
[]
no_license
use Screen; use {Matrix4, Vector3, Unit}; impl<'a> Screen<'a> { /// Pre-multiply the current MVP transformation matrix with a matrix formed /// from the given values. pub fn apply_matrix( &mut self, n00: f32, n01: f32, n02: f32, n03: f32, n10: f32, n11: f32, n12: f32, n13: f32, n20: f32, n21: f32, n22: f32, n23: f32, n30: f32, n31: f32, n32: f32, n33: f32, ) { let m = Matrix4::new( n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33, ); self.matrices.curr_matrix = m * self.matrices.curr_matrix; } /// Remove the current MVP transformation matrix from the stack and use the most /// recently used one instead. pub fn pop_matrix(&mut self) { match self.matrices.matrix_stack.pop() { Some(m) => self.matrices.curr_matrix = m, None => { self.matrices.curr_matrix = Matrix4::identity(); } }; } /// Push the current MVP transformation matrix onto the stack, so that it can be /// saved for later. Useful for when you want to temporarily apply some rotation /// or translation to a single object and don't want to disturb the rest of the /// scene. pub fn push_matrix(&mut self) { self.matrices.matrix_stack.push(self.matrices.curr_matrix); } /// Remove the current MVP transfomation matrix and set it to the standard 4x4 /// identity matrix. pub fn reset_matrix(&mut self) { self.matrices.curr_matrix = Matrix4::identity(); } /// Pre-multiply the current MVP transformation matrix by a rotation matrix which /// is derived from a rotation angle about a vector in the direction (x, y, z). pub fn rotate(&mut self, angle: f32, x: f32, y: f32, z: f32) { // let m = Matrix4::new( // angle.cos(), // -angle.sin(), // 0., // 0., // angle.sin(), // angle.cos(), // 0., // 0., // 0., // 0., // 1., // 0., // 0., // 0., // 0., // 1., // ); let m = Matrix4::from_axis_angle(&Unit::new_unchecked(Vector3::new(x, y, z)), angle); self.matrices.curr_matrix = m * self.matrices.curr_matrix; } /// Apply a rotation matrix for a given angle around the x-axis to the current MVP /// transformation matrix. pub fn rotate_x(&mut self, angle: f32) { let m = Matrix4::from_axis_angle(&Unit::new_unchecked(Vector3::new(1., 0., 0.)), angle); self.matrices.curr_matrix = m * self.matrices.curr_matrix; } /// Apply a rotation matrix for a given angle around the y-axis to the current MVP /// transformation matrix. pub fn rotate_y(&mut self, angle: f32) { let m = Matrix4::from_axis_angle(&Unit::new_unchecked(Vector3::new(0., 1., 0.)), angle); self.matrices.curr_matrix = m * self.matrices.curr_matrix; } /// Apply a rotation matrix for a given angle around the z-axis to the current MVP /// transformation matrix. pub fn rotate_z(&mut self, angle: f32) { let m = Matrix4::from_axis_angle(&Unit::new_unchecked(Vector3::new(0., 0., 1.)), angle); self.matrices.curr_matrix = m * self.matrices.curr_matrix; } /// Scale the scene along the x-, y-, and z-axes by applying a matrix derived from /// these values to the current MVP transformation matrix. pub fn scale(&mut self, x: f32, y: f32, z: f32) { // let m = Matrix4::new(x, 0., 0., 0., 0., y, 0., 0., 0., 0., z, 0., 0., 0., 0., 1.); self.matrices.curr_matrix.append_nonuniform_scaling( &Vector3::new(x, y, z), ); //* self.matrices.curr_matrix; } /// Derive a matrix that applies shear for a given angle the scene about the x-axis /// and apply it to the current MVP transformation matrix. pub fn shear_x(&mut self, angle: f32) { let m = Matrix4::new( 1., angle.tan(), 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., ); self.matrices.curr_matrix = m * self.matrices.curr_matrix; } /// Derive a matrix that applies shear for a given angle the scene about the y-axis /// and apply it to the current MVP transformation matrix. pub fn shear_y(&mut self, angle: f32) { let m = Matrix4::new( 1., 0., 0., 0., angle.tan(), 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., ); self.matrices.curr_matrix = m * self.matrices.curr_matrix; } /// Derive a translation matrix from the given (x, y, z) vector and apply it to the /// current MVP transformation matrix. pub fn translate(&mut self, x: f32, y: f32, z: f32) { let m = Matrix4::new(1., 0., 0., x, 0., 1., 0., y, 0., 0., 1., z, 0., 0., 0., 1.); self.matrices.curr_matrix = m * self.matrices.curr_matrix; } /// Print out the current MVP transformation matrix. pub fn print_matrix(&self) { println!("{:?}", self.matrices.curr_matrix); } }
true
12d236367ef244f322b7b6bd11d856b60a1b6374
Rust
fplust/rlox
/src/main.rs
UTF-8
1,939
2.578125
3
[]
no_license
mod error; mod expr; mod parser; mod scanner; mod token; mod tokentype; // mod ast_printer; mod environment; mod interpreter; mod lox_class; mod lox_function; mod lox_instance; mod object; mod resolver; mod stmt; // use crate::ast_printer::AstPrinter; use crate::interpreter::Interpreter; use crate::parser::Parser; use crate::resolver::Resolver; use crate::scanner::Scanner; use std::env; use std::fs::File; use std::io::prelude::*; use std::io::{self, BufReader}; fn main() { let args: Vec<String> = env::args().collect(); println!("{:?}", args); let args_len: usize = args.len(); if args_len > 2 { println!("Usage: lox [script]"); } else if args_len == 2 { run_file(&args[1]); } else { run_prompt(); } } fn run_file(path: &str) { match File::open(path) { Err(e) => println!("{:?}", e), Ok(file) => { let mut buf_reader = BufReader::new(file); let mut s: String = String::from(""); buf_reader.read_to_string(&mut s).unwrap(); run(&s); } } } fn run_prompt() { let stdin = io::stdin(); let mut stdout = io::stdout(); let mut buf_reader = BufReader::new(stdin); loop { print!("> "); stdout.flush().unwrap(); let mut line: String = String::from(""); buf_reader.read_line(&mut line).unwrap(); run(&line); } } fn run(source: &String) { let mut scanner = Scanner::new(source); let tokens = scanner.scan_tokens(); // for token in tokens { // println!("{}", token); // } let mut parser = Parser::new(tokens); let statements = parser.parse().expect("Error"); // let printer = AstPrinter {}; // println!("{}", printer.print(&expr)); let mut interpreter = Interpreter::new(); let mut resolver = Resolver::new(&mut interpreter); resolver.resolves(&statements); interpreter.interpret(statements); }
true
b5af8f9041f17ae6b77bc3f6bf4ef7176e48d52d
Rust
tramulns/benchmark-memory
/benchmark_cpu_cache_levels/src/lib.rs
UTF-8
1,057
2.65625
3
[]
no_license
#![feature(test)] #[allow(dead_code)] const KB: usize = 1024; #[allow(dead_code)] const MB: usize = KB * KB; #[allow(dead_code)] const N: usize = 16 * MB; #[cfg(test)] mod tests { use super::*; extern crate test; use test::Bencher; #[bench] fn bench_calc_2048kb_array(b: &mut Bencher) { let mut data = vec![0_u8; KB * 2048]; let mask = data.len() - 1; b.iter(|| { for i in 0..N { data[(i * 64) & mask] += 1; } }); } #[bench] fn bench_calc_4096kb_array(b: &mut Bencher) { let mut data = vec![0_u8; KB * 4096]; let mask = data.len() - 1; b.iter(|| { for i in 0..N { data[(i * 64) & mask] += 1; } }); } #[bench] fn bench_calc_6144kb_array(b: &mut Bencher) { let mut data = vec![0_u8; KB * 6144]; let mask = data.len() - 1; b.iter(|| { for i in 0..N { data[(i * 64) & mask] += 1; } }); } }
true
be21e70db1ad07f2956d7930c5810a9072dc93d3
Rust
sb89/fixerio
/src/exchange.rs
UTF-8
5,318
3.125
3
[ "MIT" ]
permissive
/// The response from fixerio. #[derive(Debug, Deserialize)] pub struct Exchange { /// The base currency requested. pub base: String, /// The date for which the exchange rates are for. pub date: String, /// The exhcange rates for the base currency. pub rates: Rates, } /// The exchange rates for the base currency within the response. #[derive(Debug, Deserialize)] pub struct Rates { /// Australian dollar #[serde(rename = "AUD", default)] pub aud: f32, /// Bulgarian lev #[serde(rename = "BGN", default)] pub bgn: f32, /// Brazilian real #[serde(rename = "BRL", default)] pub brl: f32, #[serde(rename = "CAD", default)] /// Canadian dollar pub cad: f32, #[serde(rename = "CHF", default)] /// Swiss franc pub chf: f32, /// Chinese yuan #[serde(rename = "CNY", default)] pub cny: f32, /// Czech koruna #[serde(rename = "CZK", default)] pub czk: f32, /// Danish krone #[serde(rename = "DKK", default)] pub dkk: f32, /// Euro #[serde(rename = "EUR", default)] pub eur: f32, /// Pound sterling #[serde(rename = "GBP", default)] pub gbp: f32, /// Hong Kong dollar #[serde(rename = "HKD", default)] pub hkd: f32, /// Croatian kuna #[serde(rename = "HRK", default)] pub hrk: f32, /// Hungarian forint #[serde(rename = "HUF", default)] pub huf: f32, /// Indonesian rupiah #[serde(rename = "IDR", default)] pub idr: f32, /// Israeli new shekel #[serde(rename = "ILS", default)] pub ils: f32, /// Indian rupee #[serde(rename = "INR", default)] pub inr: f32, /// Japanese yen #[serde(rename = "JPY", default)] pub jpy: f32, /// South Korean won #[serde(rename = "KRW", default)] pub krw: f32, /// Mexican peso #[serde(rename = "MXN", default)] pub mxn: f32, /// Malasyian ringgit #[serde(rename = "MYR", default)] pub myr: f32, /// Norwegian krone #[serde(rename = "NOK", default)] pub nok: f32, /// New Zealand dollar #[serde(rename = "NZD", default)] pub nzd: f32, /// Philippine peso #[serde(rename = "PHP", default)] pub php: f32, /// Polish złoty #[serde(rename = "PLN", default)] pub pln: f32, /// Romanian leu #[serde(rename = "RON", default)] pub ron: f32, /// Russian ruble #[serde(rename = "RUB", default)] pub rub: f32, /// Swedish krona #[serde(rename = "SEK", default)] pub sek: f32, /// Singapore dollar #[serde(rename = "SGD", default)] pub sgd: f32, /// Thai baht #[serde(rename = "THB", default)] pub thb: f32, /// Turkish lira #[serde(rename = "TRY", default)] pub try: f32, /// United States dollar #[serde(rename = "USD", default)] pub usd: f32, /// South African rand #[serde(rename = "ZAR", default)] pub zar: f32 } /// Fixerio currency. #[derive(Debug, PartialEq)] pub enum Currency { /// Australian dollar AUD, /// Bulgarian lev BGN, /// Brazilian real BRL, /// Canadian dollar CAD, /// Swiss franc CHF, /// Chinese yuan CNY, /// Czech koruna CZK, /// Danish krone DKK, /// Euro EUR, /// Pound sterling GBP, /// Hong Kong dollar HKD, /// Croatian kuna HRK, /// Hungarian forint HUF, /// Indonesian rupiah IDR, /// Israeli new shekel ILS, /// Indian rupee INR, /// Japanese yen JPY, /// South Korean won KRW, /// Mexican peso MXN, /// Malasyian ringgit MYR, /// Norwegian krone NOK, /// New Zealand dollar NZD, /// Philippine peso PHP, /// Polish złoty PLN, /// Romanian leu RON, /// Russian ruble RUB, /// Swedish krona SEK, /// Singapore dollar SGD, /// Thai baht THB, /// Turkish lira TRY, /// United States dollar USD, /// South African rand ZAR, } impl Currency { /// Return the string representation. pub fn string(&self) -> &str { match *self { Currency::AUD => "AUD", Currency::BGN => "BGN", Currency::BRL => "BRL", Currency::CAD => "CAD", Currency::CHF => "CHF", Currency::CNY => "CNY", Currency::CZK => "CZK", Currency::DKK => "DKK", Currency::EUR => "EUR", Currency::GBP => "GBP", Currency::HKD => "HKD", Currency::HRK => "HRK", Currency::HUF => "HUF", Currency::IDR => "IDR", Currency::ILS => "ILS", Currency::INR => "INR", Currency::JPY => "JPY", Currency::KRW => "KRW", Currency::MXN => "MXN", Currency::MYR => "MYR", Currency::NOK => "NOK", Currency::NZD => "NZD", Currency::PHP => "PHP", Currency::PLN => "PLN", Currency::RON => "RON", Currency::RUB => "RUB", Currency::SEK => "SEK", Currency::SGD => "SGD", Currency::THB => "THB", Currency::TRY => "TRY", Currency::USD => "USD", Currency::ZAR => "ZAR" } } }
true
d6bce0e50164ea12f0582d985617da83d365deac
Rust
hhawkens/advent_2018
/src/day_3/types.rs
UTF-8
307
3.125
3
[]
no_license
#[derive(Debug)] pub struct Rect { pub location: Point, pub size: Size, } #[derive(Debug, PartialEq, Eq, Hash)] pub struct Point { /// To the right pub x: i32, /// Down pub y: i32, } #[derive(Debug)] pub struct Size { /// Width pub w: i32, /// Height pub h: i32, }
true
19fe4a2a4dc0b8b479741fd7b037a5f5a86ff35f
Rust
popovegor/codeforces
/828B/rust/src/main.rs
UTF-8
1,572
2.9375
3
[]
no_license
fn main() { use std::io; use std::io::prelude::*; use std::cmp; let stdin = io::stdin(); let mut counter = 0; let mut w = 0; let mut h = 0; let (mut left, mut right, mut bottom, mut top) = (100,1,1,100); let mut black_counter = 0; let mut white_counter = 0; for line in stdin.lock().lines() { if counter == 0 { let l = line.unwrap(); let mut l1 = l.split(" "); h = l1.next().unwrap().parse::<i32>().unwrap(); w = l1.next().unwrap().parse::<i32>().unwrap(); // println!("w{:?} - h{:?}", w, h); } else { let l = line.unwrap_or(String::default()); let mut chars = l.chars(); let mut i = 0; while let Some(ch) = chars.next() { i += 1; if ch == 'B' { black_counter += 1; left = cmp::min(left, i); top = cmp::min(counter, top); right = cmp::max(right, i); bottom = cmp::max(bottom, counter); } else { white_counter += 1; } // println!("c{:?} i{:?} {:?}", counter, i, ch); } // println!("{:?}", l); } counter += 1; } if black_counter == 0 && white_counter > 0 { println!("{:?}", 1); } else { let square_side_len = cmp::max((right - left + 1), (bottom - top + 1)); let black_needed = square_side_len * square_side_len - black_counter; if black_needed < 0 || (black_needed + black_counter) > w*h || square_side_len > w || square_side_len > h { println!("{:?}", -1); } else { println!("{:?}", black_needed); } } // println!("{:?} {:?} {:?} {:?}", right, left, bottom, top); }
true
deaa1dd2e72f9a3791c19761bbbeab576028b47b
Rust
TheButlah/mujoco-rs
/mujoco/src/lib.rs
UTF-8
3,918
2.5625
3
[ "MIT" ]
permissive
//! Provides safe bindings to [MuJoCo](http://www.mujoco.org/index.html), a physics //! simulator commonly used for robotics and machine learning. pub mod model; mod re_exports; pub mod state; mod vfs; pub use model::Model; pub use state::State; use lazy_static::lazy_static; use std::cell::RefCell; use std::ffi::{CStr, CString}; pub(crate) mod helpers; lazy_static! { /// The location of the MuJoCo key /// /// By default this is ~/.mujoco/mjkey.txt, but can be overriden via the /// `MUJOCO_RS_KEY_LOC` environment variable pub static ref KEY_LOC: String = match std::env::var("MUJOCO_RS_KEY_LOC") { Ok(loc) => loc, Err(std::env::VarError::NotPresent) => dirs::home_dir() .expect( "Could not find home directory when attempting to use default mujoco key \ location. Consider setting `MUJOCO_RS_KEY_LOC`." ) .join(".mujoco").join("mjkey.txt").to_str().unwrap().to_owned(), Err(std::env::VarError::NotUnicode(_)) => panic!("`MUJOCO_RS_KEY_LOC` must be unicode!") }; } // Using a thread-local VFS is how we enable the use of temporary VFS objects in // a global storage without accidentally getting filename collisions or thread // safety issues. The RefCell is there to allow us to mutate safely (it could // probably be mutated via unsafe code everywhere but that is a minor speed // improvement for many unsafe LOC) thread_local! { static VFS: RefCell<vfs::Vfs> = RefCell::new(vfs::Vfs::new()); } /// Activates MuJoCo using the default key [`KEY_LOC`] /// /// [`KEY_LOC`]: struct.KEY_LOC.html pub fn activate() { let s: &str = &KEY_LOC; activate_from_str(s) } /// Deactivates MuJoCo /// /// Note that this globally deactivates MuJoCo, so make sure sure that other /// code doesn't expect it to be activated when this is called pub fn deactivate() { unsafe { mujoco_sys::mj_deactivate() } } /// Activates MuJoCo from a the key's filepath /// /// # Panics /// Panics if there is an error getting the mujoco key pub fn activate_from_str(key_loc: impl AsRef<str>) { let key_loc = CString::new(key_loc.as_ref()).unwrap(); activate_from_cstr(key_loc) } /// Activates MuJoCo from a the key's filepath as a c-style string /// /// # Panics /// Panics if there is an error getting the mujoco key pub fn activate_from_cstr(key_loc: impl AsRef<CStr>) { let key_loc = key_loc.as_ref(); let activate_result; unsafe { activate_result = mujoco_sys::mj_activate(key_loc.as_ptr()); } if activate_result != 1 { unreachable!("If activation fails, mujoco calls error handler and terminates.") } } #[cfg(test)] mod tests { use lazy_static::lazy_static; use std::ffi::CString; lazy_static! { pub(crate) static ref PKG_ROOT: std::path::PathBuf = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .canonicalize() .expect("Could not resolve absolute path for package root!"); pub(crate) static ref SIMPLE_XML_PATH: std::path::PathBuf = PKG_ROOT.join("tests").join("res").join("simple.xml"); pub(crate) static ref SIMPLE_XML: &'static str = r#" <mujoco> <worldbody> <light name="light0" diffuse=".5 .5 .5" pos="0 0 3" dir="0 0 -1"/> <geom name="geom0" type="plane" size="1 1 0.1" rgba=".9 0 0 1"/> <body name="body1" pos="0 0 1"> <joint name="joint0" type="free"/> <geom name="geom1" type="box" size=".1 .2 .3" rgba="0 .9 0 1"/> </body> </worldbody> </mujoco>"#; } #[test] fn activate() { let s: &str = &super::KEY_LOC; super::activate(); super::activate_from_str(s); super::activate_from_cstr(CString::new(s).unwrap()); } }
true
5eb7cb64fc6ada724c5cb5ad419eb06d0161abad
Rust
chinatsu/oo-workshop
/src/chance/chance_test.rs
UTF-8
2,401
3.09375
3
[]
no_license
use super::{Chance, ChanceError}; lazy_static! { static ref CERTAIN: Chance = Chance::new(super::CERTAIN).unwrap(); static ref LIKELY: Chance = Chance::new(0.75).unwrap(); static ref FIFTY_NINE: Chance = Chance::new(0.59).unwrap(); static ref EQUALLY_LIKELY: Chance = Chance::new(0.5).unwrap(); static ref FORTY_ONE: Chance = Chance::new(0.41).unwrap(); static ref UNLIKELY: Chance = Chance::new(0.25).unwrap(); static ref IMPOSSIBLE: Chance = Chance::new(0.0).unwrap(); } #[test] fn the_chance_of_25_should_be_ok() { assert!(Chance::new(0.25).is_ok()); } #[test] fn the_chance_of_130_should_be_out_of_bounds() { assert_eq!(Err(ChanceError::OutOfBounds), Chance::new(1.30)); } #[test] fn the_chance_of_minus_10_should_be_out_of_bounds() { assert_eq!(Err(ChanceError::OutOfBounds), Chance::new(-0.1)); } #[test] fn the_chance_of_75_should_equal_likely() -> Result<(), ChanceError> { assert_eq!(*LIKELY, Chance::new(0.75)?); Ok(()) } #[test] fn the_chance_of_75_should_not_equal_the_chance_of_25() { assert_ne!(*UNLIKELY, *LIKELY); } #[test] fn the_opposite_of_100_should_be_0() { assert_eq!(*IMPOSSIBLE, !*CERTAIN); } #[test] fn the_opposite_of_75_should_be_25() { assert_eq!(*UNLIKELY, !*LIKELY); } #[test] fn the_opposite_of_the_opposite_of_41_should_be_41() { assert_eq!(*FORTY_ONE, !!*FORTY_ONE); } #[test] fn the_opposite_of_the_opposite_of_the_opposite_of_41_should_be_59() { assert_eq!(*FIFTY_NINE, !!!*FORTY_ONE); } #[test] fn chances_with_values_41_and_50_together_should_be_20_5() { assert_eq!(Chance::new(0.205).unwrap(), *FORTY_ONE & *EQUALLY_LIKELY); } #[test] fn chances_with_values_13_and_0_together_should_be_0() { assert_eq!(*IMPOSSIBLE, *FIFTY_NINE & *IMPOSSIBLE); } #[test] fn chances_with_values_100_and_75_and_50_together_should_be_3_75() -> Result<(), ChanceError> { assert_eq!(Chance::new(0.375)?, *CERTAIN & *LIKELY & *EQUALLY_LIKELY); Ok(()) } #[test] fn chances_of_75_or_75_should_be_93_75() -> Result<(), ChanceError> { assert_eq!(Chance::new(0.9375)?, *LIKELY | *LIKELY); Ok(()) } #[test] fn sequence_of_4_chances_of_75_should_be_99_609375() -> Result<(), ChanceError> { assert_eq!(Chance::new(0.99609375)?, *LIKELY | *LIKELY | *LIKELY | *LIKELY); Ok(()) } #[test] fn chances_of_100_or_75_should_be_100() { assert_eq!(*CERTAIN, *CERTAIN | *UNLIKELY); }
true
c39148bf9a189c3f29f336de12cf1d4b50c29ccc
Rust
rk9109/sandbox-api
/src/main.rs
UTF-8
494
2.546875
3
[]
no_license
// TODO convert to REST API mod command; mod sandbox; use command::Language; use sandbox::Sandbox; const TEST_C_CODE: &'static str = r#" #include <stdio.h> int main() { for (int i = 0; i < 10; i++) { printf("%d\n", i); } return 0; } "#; fn main() { let output = Sandbox::new(TEST_C_CODE, Language::C) .expect("Failed to construct sandbox") .output() .expect("Failed to execute"); println!("STDOUT:\n{}", output.execute_output.stdout); }
true
ac35012aa407d9854482267fa63f9b93b3688bba
Rust
akovaski/AdventOfCode
/2018/src/year2018/d10p1.rs
UTF-8
3,215
3.03125
3
[]
no_license
use regex::Regex; use std::cmp; use std::collections::{HashSet, VecDeque}; use std::fs::File; use std::io; use std::io::prelude::*; use std::io::BufReader; pub struct Light { pub pos: Vector, pub vel: Vector, } #[derive(Clone, Copy, Eq, PartialEq, Hash)] pub struct Vector { pub x: i32, pub y: i32, } pub fn main() -> io::Result<()> { let f = File::open("./input/day10.txt")?; let mut reader = BufReader::new(f); let re = Regex::new(r"^position=< ?(-?\d+), ?(-?\d+)> velocity=< ?(-?\d+), ?(-?\d+)>$").unwrap(); let lights: Vec<_> = reader .by_ref() .lines() .map(|l| { let line = l.unwrap(); let line_ref = line.trim().as_ref(); let cap = re.captures(line_ref).unwrap(); let x_pos: i32 = cap[1].parse().unwrap(); let y_pos: i32 = cap[2].parse().unwrap(); let x_vel: i32 = cap[3].parse().unwrap(); let y_vel: i32 = cap[4].parse().unwrap(); Light { pos: Vector { x: x_pos, y: y_pos }, vel: Vector { x: x_vel, y: y_vel }, } }) .collect(); let mut prev_dev = VecDeque::new(); for t in 0.. { let sim = simulate_movement(&lights, t); let y_avg: i32 = sim.iter().map(|l| l.pos.y).sum::<i32>() / sim.len() as i32; let y_dev = sim .iter() .map(|l| { let dev = y_avg - l.pos.y; dev.abs() }) .sum::<i32>(); if prev_dev.len() > 6 { prev_dev.pop_front(); let rolling_dev = prev_dev.iter().map(|av: &(i32, i32)| av.1).sum::<i32>() / prev_dev.len() as i32; if y_dev > rolling_dev { break; } } prev_dev.push_back((t, y_dev)); } let min_dev = prev_dev.iter().min_by_key(|(_, dev)| dev).unwrap(); let sim = simulate_movement(&lights, min_dev.0); print_lights(&sim); Ok(()) } fn print_lights(lights: &Vec<Light>) { let (min, max) = lights .iter() .fold((lights[0].pos, lights[0].pos), |(mut min, mut max), l| { //let (min, max) = (min, max); min.x = cmp::min(min.x, l.pos.x); min.y = cmp::min(min.y, l.pos.y); max.x = cmp::max(max.x, l.pos.x); max.y = cmp::max(max.y, l.pos.y); (min, max) }); let mut light_set = HashSet::new(); for l in lights { light_set.insert(l.pos); } for y in min.y..=max.y { for x in min.x..=max.x { let disp_char = match light_set.get(&Vector { x, y }) { Some(_) => '#', None => '.', }; print!("{}", disp_char); } println!(); } } pub fn simulate_movement(lights: &Vec<Light>, time: i32) -> Vec<Light> { lights .iter() .map(|l| Light { pos: Vector { x: l.pos.x + l.vel.x * time, y: l.pos.y + l.vel.y * time, }, vel: Vector { x: l.vel.x, y: l.vel.y, }, }) .collect() }
true
97da531d9ce4814033a7e71857f6c08bc0d22b83
Rust
Indy2222/introns
/preprocess/src/samples/io.rs
UTF-8
6,475
2.75
3
[]
no_license
use crate::features::FeatureId; use anyhow::{Context, Error, Result}; use ncrs::data::Symbol; use ndarray::{arr0, Array, Array2}; use ndarray_npy::NpzWriter; use std::convert::TryFrom; use std::fs::{self, File, OpenOptions}; use std::path::{Path, PathBuf}; pub struct OrganismWriter { target_dir: PathBuf, counter: u64, path_writer: csv::Writer<File>, } impl OrganismWriter { pub fn with_target_dir<P: AsRef<Path>>(target_dir: P, organism_id: &str) -> Result<Self> { let mut target_dir = target_dir.as_ref().to_path_buf(); target_dir.push(organism_id); if !target_dir.exists() { fs::create_dir(&target_dir).context(format!( "Failed to create directory for samples of organism {}", organism_id ))?; } let path_writer = { let mut csv_path = target_dir.clone(); csv_path.push("samples.csv"); let create_file = !csv_path.exists(); let file = OpenOptions::new() .create(create_file) .append(true) .open(&csv_path) .with_context(|| { format!("Failed to create samples CSV file {}", csv_path.display()) })?; let mut path_writer = csv::WriterBuilder::new().from_writer(file); if create_file { path_writer.serialize(( "path", "is_positive", "sample_type_name", "feature_id", "absolute_position", "scaffold_name", ))?; } path_writer }; Ok(Self { target_dir, path_writer, counter: 0, }) } /// Store a new sample to disk. /// /// # Arguments /// /// * `sequence` - input sequence to be stored in the sample. /// /// * `relative_position` - 0-based position of splice-site within the sequence. pub fn write( &mut self, sequence: &[Symbol], is_positive: bool, sample_type_name: &str, relative_position: usize, absolute_position: usize, feature_id: Option<FeatureId>, scaffold_name: &str, ) -> Result<()> { let relative_sample_path = self.relative_sample_path(is_positive, sample_type_name); let mut target_file_path = self.target_dir.clone(); target_file_path.push(&relative_sample_path); { let target_sub_dir = target_file_path.parent().unwrap(); fs::create_dir_all(&target_sub_dir).with_context(|| { format!( "Failed to create samples directory {}", target_sub_dir.display() ) })?; } let input = sequence_to_one_hot(&sequence); let output = arr0(if is_positive { 1.0 } else { 0.0 }); { let file = File::create(&target_file_path).context("Failed to store a sample")?; let mut npz_writer = NpzWriter::new_compressed(file); let error_context = || { format!( "Error while writing to target file {}", target_file_path.display() ) }; if relative_position > sequence.len() { panic!("Relative splice-site position out of sequence bounds."); } let relative_position = arr0( u64::try_from(relative_position) .context("Splice-site position cannot be serialized")?, ); npz_writer .add_array("position", &relative_position) .with_context(error_context)?; npz_writer .add_array("input", &input) .with_context(error_context)?; npz_writer .add_array("output", &output) .with_context(error_context)?; } self.write_path( &relative_sample_path, is_positive, sample_type_name, feature_id, absolute_position, scaffold_name, )?; self.counter += 1; Ok(()) } fn write_path( &mut self, relative_path: &Path, is_positive: bool, sample_type_name: &str, feature_id: Option<FeatureId>, absolute_position: usize, scaffold_name: &str, ) -> Result<()> { if relative_path.is_absolute() { panic!( "Relative sample path expected, got absolute path: {}", relative_path.display() ); } let feature_id = match feature_id { Some(feature_id) => feature_id.to_hex(), None => String::new(), }; let absolute_position = format!("{}", absolute_position); self.path_writer .serialize(( relative_path .to_str() .expect("Failed to serialize sample path as a UTF-8 string."), format!("{}", is_positive), sample_type_name, feature_id, absolute_position, scaffold_name, )) .map_err(Error::new) } fn relative_sample_path(&self, is_positive: bool, sample_type_name: &str) -> PathBuf { let mut relative_path = PathBuf::new(); relative_path.push(format!("{:04}", self.counter >> 16)); relative_path.push(format!("{:03}", (self.counter >> 8) & 0xff)); let mut file_name = String::new(); if is_positive { file_name.push_str("positive_"); } else { file_name.push_str("negative_"); } file_name.push_str(sample_type_name); file_name.push_str(&format!("_{:03}.npz", self.counter & 0xff)); relative_path.push(file_name); relative_path } } /// Create a one-hot-encoded 2D array of a sequence. First dimension /// represents individual sequence positions and second dimension represents /// one-hot-encoding. fn sequence_to_one_hot(sequence: &[Symbol]) -> Array2<f32> { let mut input = Array::zeros((sequence.len(), 5)); for (i, symbol) in sequence.iter().enumerate() { let pos: usize = (*symbol).into(); input[(i, pos)] = 1.; } input }
true
bd343b0c2338bee0b60f4e0baa7c43e2e41e35db
Rust
NyxTo/Advent-of-Code
/2019/Code/day_10_asteroid.rs
UTF-8
1,473
2.921875
3
[]
no_license
use std::fs::File; use std::io::{BufRead, BufReader}; use std::cmp::{min, max}; fn gcd(mut a: usize, mut b: usize) -> usize { while b > 0 { let rem = a % b; a = b; b = rem; } a } fn main() { let grid = BufReader::new(File::open("in_10.txt").unwrap()).lines().map(|row| row.unwrap().chars().collect::<Vec<_>>()).collect::<Vec<_>>(); let (hgt, wid, mut max_det, mut vapour) = (grid.len(), grid[0].len(), 0, (0, 0)); for sy in 0..hgt { for sx in 0..wid { if grid[sy][sx] == '#' { let (mut detect, mut btwn, mut aster, mut ang) = (0, vec![vec![0; wid]; hgt], vec![], vec![vec![0.; wid]; hgt]); for ey in 0..hgt { for ex in 0..wid { if grid[ey][ex] == '#' { if ex == sx && ey == sy { continue; } let num = gcd(max(sx, ex) - min(sx, ex), max(sy, ey) - min(sy, ey)); btwn[ey][ex] = (1..num).filter(|i| { let (bx, by) = ((sx * (num - i) + ex * i) / num, (sy * (num - i) + ey * i) / num); grid[by][bx] == '#' }).count(); if btwn[ey][ex] == 0 { detect += 1; } aster.push((ex, ey)); ang[ey][ex] = (ex as f64 - sx as f64).atan2(ey as f64 - sy as f64); } } } if detect >= max_det { max_det = detect; aster.sort_by(|(x1, y1), (x2, y2)| ang[*y2][*x2].partial_cmp(&ang[*y1][*x1]).unwrap()); aster.sort_by_key(|(x, y)| btwn[*y][*x]); vapour = aster[199]; } } } } println!("Part A: {}", max_det); // 221 println!("Part B: {}", vapour.0 * 100 + vapour.1); // 806 }
true
fb77b7aa24d2d3bd97c7f147c149665782414c1d
Rust
algon-320/mandarin
/kernel/src/global.rs
UTF-8
1,247
2.546875
3
[]
no_license
use crate::console::{Attribute, Console}; use crate::graphics::{font, FrameBuffer, Scaled}; use crate::sync::spin::SpinMutex; use core::mem::MaybeUninit; pub static FRAME_BUF: SpinMutex<MaybeUninit<Scaled<FrameBuffer, 1>>> = SpinMutex::new("frame_buffer", MaybeUninit::uninit()); pub fn init_frame_buffer(frame_buffer: FrameBuffer) { let mut fb = FRAME_BUF.lock(); unsafe { fb.as_mut_ptr().write(Scaled(frame_buffer)) }; } pub fn lock_frame_buffer<F: FnMut(&mut Scaled<FrameBuffer, 1>)>(mut f: F) { let mut fb = FRAME_BUF.lock(); let fb = unsafe { &mut *fb.as_mut_ptr() }; f(fb) } pub static CONSOLE: SpinMutex<Console> = SpinMutex::new("console", Console::new(80, 27)); pub fn init_console(columns: usize, lines: usize) { let mut console = CONSOLE.lock(); console.resize(columns, lines); } pub fn console_write(attr: Attribute, args: core::fmt::Arguments) { let mut console = CONSOLE.lock(); use core::fmt::Write; let old_attr = console.attr; console.attr = attr; console.write_fmt(args).unwrap(); console.attr = old_attr; } pub fn console_flush() { let mut console = CONSOLE.lock(); lock_frame_buffer(|fb| { console.render(fb, &mut font::ShinonomeFont); }); }
true
ca3b5872214906c728258dca015c36f1abc89c86
Rust
rob-clarke/arusti
/arusti/tests/olan_tests.rs
UTF-8
4,264
3.0625
3
[]
no_license
use arusti; use arusti::{ElementType,Element}; fn compare_elements(result: &Vec<Element>, expectation: &Vec<Element>) { assert_eq!(result.len(), expectation.len(), "Figure has wrong number of elements"); for (index,(result,expected)) in result.iter().zip( expectation.iter() ).enumerate() { assert_eq!(result, expected, "Element {} does not match expectation", index); } } #[test] fn loop_plain() { let sequence_str = "o".to_string(); let sequence = arusti::olan::parse_sequence(sequence_str); let expected_elements = vec![ Element::line(0.0), Element::radius(180.0), Element::radius(180.0), Element::line(0.0), ]; compare_elements(&sequence.figures[0].elements, &expected_elements); } #[test] fn loop_with_leading_roll() { let sequence_str = "1o".to_string(); let sequence = arusti::olan::parse_sequence(sequence_str); let expected_elements = vec![ Element::line(0.0), Element { angle: 360.0, argument: 1.0, .. Element::new(ElementType::Roll) }, Element::radius(180.0), Element::radius(180.0), Element::line(0.0), ]; compare_elements(&sequence.figures[0].elements, &expected_elements); } #[test] fn loop_with_combining_roll() { let sequence_str = "o1".to_string(); let sequence = arusti::olan::parse_sequence(sequence_str); let expected_elements = vec![ Element::line(0.0), Element::radius(180.0), Element { angle: 360.0, argument: 1.0, .. Element::new(ElementType::Roll) }, Element::radius(180.0), Element::line(0.0), ]; compare_elements(&sequence.figures[0].elements, &expected_elements); } #[test] fn loop_with_all_rolls() { let sequence_str = "1o1".to_string(); let sequence = arusti::olan::parse_sequence(sequence_str); let expected_elements = vec![ Element::line(0.0), Element { angle: 360.0, argument: 1.0, .. Element::new(ElementType::Roll) }, Element::radius(180.0), Element { angle: 360.0, argument: 1.0, .. Element::new(ElementType::Roll) }, Element::radius(180.0), Element::line(0.0), ]; compare_elements(&sequence.figures[0].elements, &expected_elements); } #[test] fn loop_with_inverted_flight() { let sequence_str = "-o-".to_string(); let sequence = arusti::olan::parse_sequence(sequence_str); let expected_elements = vec![ Element::invline(0.0), Element::radius(-180.0), Element::radius(-180.0), Element::invline(0.0), ]; compare_elements(&sequence.figures[0].elements, &expected_elements); } #[test] fn loop_with_inverted_entry_and_inverting_leading_roll() { let sequence_str = "-2o".to_string(); let sequence = arusti::olan::parse_sequence(sequence_str); let expected_elements = vec![ Element::invline(0.0), Element { angle: 180.0, argument: 1.0, .. Element::new(ElementType::Roll) }, Element::radius(180.0), Element::radius(180.0), Element::line(0.0), ]; compare_elements(&sequence.figures[0].elements, &expected_elements); } #[test] fn loop_with_inverted_entry_and_inverting_combining_roll() { let sequence_str = "-o2".to_string(); let sequence = arusti::olan::parse_sequence(sequence_str); let expected_elements = vec![ Element::invline(0.0), Element::radius(-180.0), Element { angle: 180.0, argument: 1.0, .. Element::new(ElementType::Roll) }, Element::radius(180.0), Element::line(0.0), ]; compare_elements(&sequence.figures[0].elements, &expected_elements); } #[test] fn hammerhead_turn() { let sequence_str = "h".to_string(); let sequence = arusti::olan::parse_sequence(sequence_str); let expected_elements = vec![ Element::line(0.0), Element::radius(90.0), Element::line(90.0), Element { angle: 180.0, argument: 0.0, .. Element::new(ElementType::Stall) }, Element::line(-90.0), Element::radius(90.0), Element::line(0.0), ]; compare_elements(&sequence.figures[0].elements, &expected_elements); }
true
04b6bedbfb90e194343d2fd56500d851e2843422
Rust
m-lima/advent-of-code-2020
/src/bin/112/build.rs
UTF-8
814
2.625
3
[]
no_license
pub fn prepare() { use std::io::Write; const OUTPUT: &str = "src/bin/112/input.rs"; const INPUT: &str = include_str!("input.txt"); println!("cargo:rerun-if-changed=src/bin/112/{}", INPUT); let input: Vec<_> = INPUT .split('\n') .filter(|line| !line.is_empty()) .map(|line| line.chars().collect::<Vec<_>>()) .collect(); let mut output = std::fs::File::create(OUTPUT).unwrap(); output .write_all( format!( "pub const INPUT: [[char; {}]; {}] = [", input[0].len(), input.len() ) .as_bytes(), ) .unwrap(); for line in input { output.write_all(format!("{:?},", line).as_bytes()).unwrap(); } output.write_all(b"];").unwrap(); }
true
1f1bd79e8d27d676bd719d96aaa3a92ee51c7b2e
Rust
longlb/exercism
/rust/triangle/src/lib.rs
UTF-8
987
3.578125
4
[]
no_license
pub struct Triangle { side1: u64, side2: u64, side3: u64, } impl Triangle { pub fn build(sides: [u64; 3]) -> Option<Triangle> { let new_tri = Triangle { side1: sides[0], side2: sides[1], side3: sides[2], }; if new_tri.is_valid() { Some(new_tri) } else { None } } pub fn is_equilateral(&self) -> bool { self.side1 == self.side2 && self.side2 == self.side3 && self.side3 == self.side1 } pub fn is_scalene(&self) -> bool { self.side1 != self.side2 && self.side2 != self.side3 && self.side3 != self.side1 } pub fn is_isosceles(&self) -> bool { self.side1 == self.side2 || self.side2 == self.side3 || self.side3 == self.side1 } fn is_valid(&self) -> bool { self.side1 < self.side2 + self.side3 && self.side2 < self.side1 + self.side3 && self.side3 < self.side1 + self.side2 } }
true
e393954bde0ff61b876070ee5572e15717893ce3
Rust
acohen4/steelmate
/src/lib/engine.rs
UTF-8
13,224
3.15625
3
[]
no_license
use super::board::{Board, Color, Piece, PieceKind, Position}; use std::collections::HashMap; struct MovePattern { is_repeatable: bool, move_enumerations: Vec<Position>, } impl MovePattern { fn new(is_repeatable: bool, move_enumerations: Vec<Position>) -> MovePattern { MovePattern { is_repeatable, move_enumerations, } } } pub enum BoardSetup { Basic, } pub struct ChessEngine { pub board: Board, } impl ChessEngine { pub fn create_board(setup: BoardSetup) -> Result<Board, String> { match setup { BoardSetup::Basic => ChessEngine::setup_basic_board() } } pub fn possible_moves(board: &Board, p: &Position) -> Result<Vec<Position>, String> { match board.get_space(p)? { Option::None => Ok(vec![]), Option::Some(Piece { kind: PieceKind::Pawn, color: c, has_moved: hm }) => { Ok(ChessEngine::generate_pawn_moves(board, p, *c, *hm)) }, Option::Some(Piece { kind: PieceKind::King, color: c, has_moved: hm }) => { Ok(ChessEngine::generate_king_moves(board, p, *c, *hm)) }, Option::Some(piece) => { let mut solutions = vec![]; let pattern = ChessEngine::get_move_pattern(piece.kind)?; for diff in pattern.move_enumerations.iter() { ChessEngine::apply_move(board, &mut solutions, p, diff, &piece.color, pattern.is_repeatable) } Ok(solutions) } } } fn generate_king_moves(board: &Board, p: &Position, color: Color, has_moved: bool) -> Vec<Position> { let mut solutions = vec![]; if !has_moved { if ChessEngine::can_side_castle(board, p, true) { solutions.push(Position::new(p.row, p.col - 3)); } if ChessEngine::can_side_castle(board, p, false) { solutions.push(Position::new(p.row, p.col + 2)); } } // do the basic case let surroundings: Vec<Position> = ChessEngine::expand_with_inverses(vec![ Position::new(0, 1), Position::new(1, 0), Position::new(1, 1), ]) .iter() .map(|pos| Position::add(p, pos)) .collect(); for pos in surroundings { if let Ok(_) = board.get_space(&pos) { if ChessEngine::is_enemy_space(board, &pos, color) || board.is_empty_space(&pos) { if !ChessEngine::is_threatened(board, &pos, color) { solutions.push(pos.clone()); } } } } solutions } fn can_side_castle(board: &Board, king_pos: &Position, is_left: bool) -> bool { let direction = if is_left { -1 } else { 1 }; let rook_col = if is_left { 0 } else { (board.get_size() as i32) - 1 }; let mut can_castle = match board.get_space(&Position::new(king_pos.row, rook_col)){ Ok(Option::Some(Piece {kind: _, color: _, has_moved: false})) => true, _ => false, }; let mut i = king_pos.col; while i > 0 && can_castle { i = i + direction; match board.get_space(&Position::new(king_pos.row, i)) { Ok(Option::Some(_)) => can_castle = false, _ => () } } can_castle } fn generate_pawn_moves(board: &Board, p: &Position, c: Color, has_moved: bool) -> Vec<Position>{ // convert color to direction let mut solutions = vec![]; let direction = if c == Color::White { 1 } else { -1 }; let forward_space = Position::new(direction + p.row, p.col); if let Ok(Option::None) = board.get_space(&forward_space) { solutions.push(forward_space); if has_moved == false { let double_forward_space = Position::new(2 * direction + p.row , p.col); if let Ok(Option::None) = board.get_space(&double_forward_space) { solutions.push(double_forward_space); } } } let positive_diagonal_space = Position::new(p.row + direction , p.col + 1); if ChessEngine::is_enemy_space(board, &positive_diagonal_space, c) { solutions.push(positive_diagonal_space); } let negative_diagonal_space = Position::new(p.row + direction , p.col - 1); if ChessEngine::is_enemy_space(board, &negative_diagonal_space, c) { solutions.push(negative_diagonal_space); } solutions } fn is_enemy_space(board: &Board, p: &Position, c: Color) -> bool { if let Ok( Option::Some(Piece { kind: _, color: move_color, has_moved: _ }) ) = board.get_space(p) { *move_color != c } else { false } } pub fn execute_move(board: &mut Board, from: &Position, to: &Position) -> Result<Option<Piece>, String> { let possibilities = ChessEngine::possible_moves(board, from)?; if possibilities.contains(to) { // if castle, also move Rook if ChessEngine::is_castle(board, from, to) { ChessEngine::castle_rook(board, from, to)?; } Ok(board.move_piece(from, to)?) } else { Err(String::from("You cannot move to this space")) } } fn apply_move( board: &Board, sink: &mut Vec<Position>, pos: &Position, diff: &Position, color: &Color, repeat: bool, ) { let check_pos = Position::add(pos, diff); println!("Checking Position"); println!("{:?}", check_pos); if let Err(_) = board.validate_position(&check_pos) { return; } if let Ok(space) = board.get_space(&check_pos) { match space { Option::None => { sink.push(check_pos); if repeat { ChessEngine::apply_move(board, sink, &check_pos, diff, color, repeat); } } Option::Some(piece) => { if piece.color != *color { sink.push(check_pos); } } } } } fn get_move_pattern(kind: PieceKind) -> Result<MovePattern, String> { match kind { PieceKind::King | PieceKind::Pawn => Err(String::from("not supported")), PieceKind::Queen => { let moves = ChessEngine::expand_with_inverses(vec![ Position::new(0, 1), Position::new(1, 0), Position::new(1, 1), ]); Ok(MovePattern::new(true, moves)) } PieceKind::Rook => { let moves = ChessEngine::expand_with_inverses(vec![ Position::new(0, 1), Position::new(1, 0), ]); Ok(MovePattern::new(true, moves)) } PieceKind::Bishop => { Ok(MovePattern::new(true, Position::new(1, 1) .yield_all_inverse_positions())) } PieceKind::Knight => { let moves = ChessEngine::expand_with_inverses(vec![ Position::new(1, 2), Position::new(2, 1), ]); Ok(MovePattern::new(false, moves)) } } } fn expand_with_inverses(positions: Vec<Position>) -> Vec<Position> { //positions.iter().map(|pos| pos.yield_all_inverse_positions()).collect() let mut expanded = Vec::new(); for pos in positions.iter() { expanded.append(&mut pos.yield_all_inverse_positions()); } expanded } fn is_castle(board: &Board, from: &Position, to: &Position) -> bool { board.get_space(from).unwrap().unwrap().kind == PieceKind::King && (from.col - to.col).abs() == 2 } fn castle_rook(board: &mut Board, king_start: &Position, king_dest: &Position) -> Result<(), String> { let is_right = king_start.col > king_dest.col; let rook_from_col = if is_right {0} else {board.get_size() as i32}; let rook_to_col = if is_right {king_dest.col - 1} else {king_dest.col + 1}; ChessEngine::execute_move(board, &Position::new(king_start.row, rook_from_col), &Position::new(king_start.row, rook_to_col))?; Ok(()) } fn is_threatened(board: &Board, pos: &Position, color: Color) -> bool { let threatened = board.get_piece_positions().iter() .filter(|(_, piece)| piece.color != color) .flat_map(|(position, _)| ChessEngine::possible_moves(board, position).unwrap()) .any(|possible_move| possible_move == *pos); threatened } fn setup_basic_board() -> Result<Board, String>{ let mut b = Board::new(8)?; //setup pawns b.fill(Some(6), None, Piece::new(PieceKind::Pawn, Color::Black))?; b.fill(Some(1), None, Piece::new(PieceKind::Pawn, Color::White))?; // populate accepts map of Spot => Piece let mut map = HashMap::new(); // handle rooks map.insert( Position::new(0, 0), Piece::new(PieceKind::Rook, Color::White), ); map.insert( Position::new(0, 7), Piece::new(PieceKind::Rook, Color::White), ); map.insert( Position::new(7, 0), Piece::new(PieceKind::Rook, Color::Black), ); map.insert( Position::new(7, 7), Piece::new(PieceKind::Rook, Color::Black), ); // handle knights map.insert( Position::new(0, 1), Piece::new(PieceKind::Knight, Color::White), ); map.insert( Position::new(0, 6), Piece::new(PieceKind::Knight, Color::White), ); map.insert( Position::new(7, 1), Piece::new(PieceKind::Knight, Color::Black), ); map.insert( Position::new(7, 6), Piece::new(PieceKind::Knight, Color::Black), ); // handle bishops map.insert( Position::new(0, 2), Piece::new(PieceKind::Bishop, Color::White), ); map.insert( Position::new(0, 5), Piece::new(PieceKind::Bishop, Color::White), ); map.insert( Position::new(7, 2), Piece::new(PieceKind::Bishop, Color::Black), ); map.insert( Position::new(7, 5), Piece::new(PieceKind::Bishop, Color::Black), ); // handle queens map.insert( Position::new(0, 3), Piece::new(PieceKind::Queen, Color::White), ); map.insert( Position::new(7, 3), Piece::new(PieceKind::Queen, Color::Black), ); // handle kings map.insert( Position::new(0, 4), Piece::new(PieceKind::King, Color::White), ); map.insert( Position::new(7, 4), Piece::new(PieceKind::King, Color::Black), ); b.populate(map)?; Ok(b) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_basic_board() -> Result<(), String> { let board = ChessEngine::setup_basic_board()?; let pos = Position::new(0, 1); let res = board.get_space(&pos); let op = res?; assert_eq!( Some(&Piece { kind: PieceKind::Knight, color: Color::White, has_moved: false }), op ); Ok(()) } #[test] fn test_move_piece() -> Result<(), String> { let mut board = ChessEngine::setup_basic_board()?; let from = Position::new(1, 1); let to = Position::new(2, 1); ChessEngine::execute_move(&mut board, &from, &to)?; let op_to = board.get_space(&to)?; let op_from = board.get_space(&from)?; assert_eq!( Some(&Piece { kind: PieceKind::Pawn, color: Color::White, has_moved: true }), op_to ); assert_eq!(None, op_from); Ok(()) } #[test] fn test_possible_moves() -> Result<(), String> { let board = ChessEngine::setup_basic_board()?; let pos = Position::new(0, 1); let possibilities = ChessEngine::possible_moves(&board, &pos)?; board.pretty_print(); println!("{:?}", possibilities); assert_eq!(possibilities.len(), 2); Ok(()) } }
true
b36f1451cae914f0eea9f2760d6377ec041aed44
Rust
yaozijian/RustProgramming
/chap15/src/section1.rs
UTF-8
667
3.71875
4
[ "MIT" ]
permissive
pub fn demo(){ let x = 5; let y = &x; let z = Box::new(x); assert_eq!(x,5); assert_eq!(*y,5); assert_eq!(*z,5); } pub fn demo2(){ struct MyBox<T>(T); impl<T> MyBox<T>{ fn new(x: T) -> MyBox<T>{ MyBox(x) } } use std::ops::Deref; impl<T> Deref for MyBox<T>{ type Target = T; fn deref(&self) -> &T{ &self.0 } } let x = 5; let y = &x; let z = MyBox::new(x); let a = MyBox::new(String::from("ABC")); fn hello(x : &str){ println!("{}",x); }; assert_eq!(x,5); assert_eq!(*y,5); assert_eq!(*z,5); assert_eq!(*a,String::from("ABC")); hello(a.deref().deref()); hello(&a); hello(&*a); }
true
0aed52d6d235a63d94a9e35e41fca828a0307f8a
Rust
zhengrenzhe/nand2tetris
/compiler/vm-compiler/src/lexical.rs
UTF-8
1,670
3.4375
3
[]
no_license
#[derive(Debug)] pub struct Token { pub command: String, pub target: String, pub arg: String, } pub fn lexical(code: &str) -> Option<Token> { let parts: Vec<&str> = code.split(' ').filter(|code| !code.is_empty()).collect(); if parts.is_empty() { return None; } Some(Token { command: String::from(parts[0]), target: String::from(*parts.get(1).unwrap_or(&"")), arg: String::from(*parts.get(2).unwrap_or(&"")), }) } #[cfg(test)] mod tests { use super::*; #[test] fn test_lexical_analysis() { if let Some(val) = lexical("") { panic!(format!("val: {:?} should be None", val)); } match lexical("add") { Some(token) => { assert_eq!(token.command, String::from("add")); assert_eq!(token.target, String::from("")); assert_eq!(token.arg, String::from("")); } None => panic!("should not be None"), } match lexical("push 12") { Some(token) => { assert_eq!(token.command, String::from("push")); assert_eq!(token.target, String::from("12")); assert_eq!(token.arg, String::from("")); } None => panic!("should not be None"), } match lexical("push constant 12") { Some(token) => { assert_eq!(token.command, String::from("push")); assert_eq!(token.target, String::from("constant")); assert_eq!(token.arg, String::from("12")); } None => panic!("should not be None"), } } }
true
68d2c48e7b995f9cf69a985eb6292ef8c6ee5112
Rust
chyvonomys/serpanok
/src/format.rs
UTF-8
5,990
2.765625
3
[]
no_license
use chrono::{Datelike, Timelike}; pub fn format_lat_lon(lat: f32, lon: f32) -> String { format!("{:.03}°{} {:.03}°{}", lat.abs(), if lat > 0.0 {"N"} else {"S"}, lon.abs(), if lat > 0.0 {"E"} else {"W"}, ) } const MONTH_ABBREVS: [&str; 12] = [ "Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру" ]; fn format_time(t: chrono::DateTime<chrono_tz::Tz>) -> String { format!("{} {} {:02}:{:02}", t.day(), MONTH_ABBREVS.get(t.month0() as usize).unwrap_or(&"?"), t.hour(), t.minute() ) } fn format_rain_rate(mmhr: f32) -> String { if mmhr < 0.01 { None } else if mmhr < 2.5 { Some("\u{1F4A7}") } else if mmhr < 7.6 { Some("\u{1F4A7}\u{1F4A7}") } else { Some("\u{1F4A7}\u{1F4A7}\u{1F4A7}") }.map(|g| format!("{}{:.2}мм/год", g, mmhr)).unwrap_or_else(|| "--".to_owned()) } fn format_snow_rate(mmhr: f32) -> String { if mmhr < 0.01 { None } else if mmhr < 1.3 { Some("\u{2744}") } else if mmhr < 3.0 { Some("\u{2744}\u{2744}") } else if mmhr < 7.6 { Some("\u{2744}\u{2744}\u{2744}") } else { Some("\u{2744}\u{26A0}") }.map(|g| format!("{}{:.2}мм/год", g, mmhr)).unwrap_or_else(|| "--".to_owned()) } fn format_wind_dir(u: f32, v: f32) -> &'static str { let ws_az = (-v).atan2(-u) / std::f32::consts::PI * 180.0; if ws_az > 135.0 + 22.5 { "\u{2192}" } else if ws_az > 90.0 + 22.5 { "\u{2198}" } else if ws_az > 45.0 + 22.5 { "\u{2193}" } else if ws_az > 22.5 { "\u{2199}" } else if ws_az > -22.5 { "\u{2190}" } else if ws_az > -45.0 - 22.5 { "\u{2196}" } else if ws_az > -90.0 - 22.5 { "\u{2191}" } else if ws_az > -135.0 - 22.5 { "\u{2197}" } else { "\u{2192}" } } use crate::data; pub struct ForecastText(pub String); pub fn format_place_link(name: &Option<String>, lat: f32, lon: f32) -> String { let text = name.clone().unwrap_or_else(|| format_lat_lon(lat, lon)); format!("[{}](http://www.openstreetmap.org/?mlat={}&mlon={})", text, lat, lon) } pub fn format_forecast(name: &Option<String>, lat: f32, lon: f32, f: &data::Forecast, tz: chrono_tz::Tz) -> ForecastText { let interval = (f.time.1 - f.time.0).num_minutes() as f32; let mut result = String::new(); result.push_str(&format_place_link(name, lat, lon)); result.push('\n'); result.push_str(&format!("_{}_\n", format_time(f.time.0.with_timezone(&tz)))); if let Some(tmpk) = f.temperature { let tmpc = (10.0 * (tmpk - 273.15)).round() / 10.0; result.push_str(&format!("t повітря: *{:.1}°C*\n", tmpc)); } if let Some(rain) = f.rain_accum { let rain_rate = ((rain.1 - rain.0) * 60.0 / interval).max(0.0); result.push_str(&format!("дощ: *{}*\n", format_rain_rate(rain_rate))); } if let Some(snow) = f.snow_accum { let snow_rate = ((snow.1 - snow.0) * 60.0 / interval).max(0.0); result.push_str(&format!("сніг: *{}*\n", format_snow_rate(snow_rate))); } if let Some(snow_depth) = f.snow_depth { result.push_str(&format!("шар снігу: *{:.01}см*\n", snow_depth * 100.0)); } if let Some(clouds) = f.total_cloud_cover { result.push_str(&format!("хмарність: *{:.0}%*\n", clouds.round())); } if let Some(wind) = f.wind_speed { let wind_speed = (wind.0 * wind.0 + wind.1 * wind.1).sqrt(); result.push_str(&format!("вітер: *{} {:.1}м/с*\n", format_wind_dir(wind.0, wind.1), (10.0 * wind_speed).round() / 10.0)); } if let Some(relhum) = f.rel_humidity { result.push_str(&format!("відн. вологість: *{:.0}%*\n", relhum)); } if let Some(pmsl) = f.pressure_msl { result.push_str(&format!("атм. тиск: *{:.0}ммHg*\n", pmsl / 133.322)) } ForecastText(result) } use plotters::prelude::*; pub fn format_exchange_graph( rs: &[(chrono::DateTime::<chrono::Utc>, u32, u32)], from: &chrono::DateTime::<chrono::Utc>, to: &chrono::DateTime::<chrono::Utc>, ) -> Result<String, String> { let min_buy = rs.iter().map(|x| x.1).min().unwrap_or(0); let min_sell = rs.iter().map(|x| x.2).min().unwrap_or(0); let max_buy = rs.iter().map(|x| x.1).max().unwrap_or(3000); let max_sell = rs.iter().map(|x| x.2).max().unwrap_or(3000); let min = std::cmp::min(min_buy, min_sell) as f32 / 100.0; let max = std::cmp::max(max_buy, max_sell) as f32 / 100.0; let max_pad = max + 0.1 * (max - min); let min_pad = min - 0.1 * (max - min); let filename = format!("plot-{}.png", chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, false)); { let root = BitMapBackend::new(&filename, (200, 100)).into_drawing_area(); root.fill(&RGBColor(255, 255, 240)); let mut chart = ChartBuilder::on(&root) .x_label_area_size(20) .y_label_area_size(30) .build_cartesian_2d(*from..*to, min_pad..max_pad) .map_err(|e| e.to_string())?; chart .configure_mesh() .light_line_style(BLACK.mix(0.0).filled()) .x_labels(5) .y_labels(5) .x_label_formatter(&|dt: &chrono::DateTime::<chrono::Utc>| format!("{}:{}", dt.hour(), dt.minute())) .draw() .map_err(|e| e.to_string())?; chart .draw_series(LineSeries::new( rs.iter().map(|x| (x.0, x.1 as f32 * 0.01)), &RGBColor(20, 20, 200), )) .map_err(|e| e.to_string())?; chart .draw_series(LineSeries::new( rs.iter().map(|x| (x.0, x.2 as f32 * 0.01)), &RGBColor(20, 200, 20), )) .map_err(|e| e.to_string())?; } Ok(filename) }
true
b16142cf5144097229d0a02f2e7942b78db3a226
Rust
mcmcgrath13/delf-rs
/src/graph/mod.rs
UTF-8
10,170
3
3
[ "MIT" ]
permissive
use std::collections::{HashMap, HashSet}; use std::process::exit; use ansi_term::Colour::{Red, Green, Cyan}; use petgraph::{ graph::{EdgeIndex, NodeIndex}, Directed, Graph, Incoming, Outgoing, }; /// The edge of a DelfGraph is a DelfEdge pub mod edge; /// The node of a DelfGraph is a DelfObject pub mod object; use crate::storage::{get_connection, DelfStorageConnection}; use crate::DelfYamls; /// The DelfGraph is the core structure for delf's functionality. It contains the algorithm to traverse the graph, as well as metadata to perform the deletions. #[derive(Debug)] pub struct DelfGraph { pub(crate) nodes: HashMap<String, NodeIndex>, pub(crate) edges: HashMap<String, EdgeIndex>, graph: Graph<object::DelfObject, edge::DelfEdge, Directed>, storages: HashMap<String, Box<dyn DelfStorageConnection>>, } impl DelfGraph { /// Create a new DelfGraph from a schema and a config. See [yaml_rust](../../yaml_rust/index.html) for information on creating the Yaml structs, or alternately use the helper functions: [read_files](../fn.read_files.html), [read_yamls](../fn.read_yamls.html) for constructing a DelfGraph from either paths or `&str` of yaml. pub fn new(yamls: &DelfYamls) -> DelfGraph { let schema = &yamls.schema; let config = &yamls.config; let mut edges_to_insert = Vec::new(); let mut nodes = HashMap::<String, NodeIndex>::new(); let mut edges = HashMap::<String, EdgeIndex>::new(); let mut graph = Graph::<object::DelfObject, edge::DelfEdge>::new(); // each yaml is an object for yaml in schema.iter() { let obj_name = String::from(yaml["object_type"]["name"].as_str().unwrap()); let obj_node = object::DelfObject::from(&yaml["object_type"]); let node_id = graph.add_node(obj_node); nodes.insert(obj_name.clone(), node_id); // need to make sure all the nodes exist before edges can be added to the graph for e in yaml["object_type"]["edge_types"].as_vec().unwrap().iter() { let delf_edge = edge::DelfEdge::from(e); edges_to_insert.push((obj_name.clone(), delf_edge)); } } // add all the edges to the graph for (from, e) in edges_to_insert.iter_mut() { if !nodes.contains_key(&e.to.object_type) { eprintln!("Error creating edge {:#?}: No object with name {:#?}", e.name, e.to.object_type); exit(1); } let edge_id = graph.add_edge(nodes[from], nodes[&e.to.object_type], e.clone()); edges.insert(String::from(&e.name), edge_id); } // create the storage map let mut storages = HashMap::<String, Box<dyn DelfStorageConnection>>::new(); for yaml in config.iter() { for storage in yaml["storages"].as_vec().unwrap().iter() { let storage_name = String::from(storage["name"].as_str().unwrap()); storages.insert( storage_name, get_connection( storage["plugin"].as_str().unwrap(), storage["url"].as_str().unwrap(), ), ); } } return DelfGraph { nodes, edges, graph, storages, }; } /// Pretty print the graph's contents. pub fn print(&self) { println!("{:#?}", self.graph); } /// Given an edge name, get the corresponding DelfEdge pub fn get_edge(&self, edge_name: &String) -> &edge::DelfEdge { let edge_id = self.edges.get(edge_name).unwrap(); return self.graph.edge_weight(*edge_id).unwrap(); } /// Given an edge name and the ids of the to/from object instances, delete the edge pub fn delete_edge(&self, edge_name: &String, from_id: &String, to_id: &String) { let e = self.get_edge(edge_name); e.delete_one(from_id, to_id, self); } /// Given an object name, get the corresponding DelfObject pub fn get_object(&self, object_name: &String) -> &object::DelfObject { let object_id = self.nodes.get(object_name).unwrap(); return self.graph.node_weight(*object_id).unwrap(); } /// Given the object name and the id of the instance, delete the object pub fn delete_object(&self, object_name: &String, id: &String) { self._delete_object(object_name, id, None); } fn _delete_object( &self, object_name: &String, id: &String, from_edge: Option<&edge::DelfEdge>, ) { let obj = self.get_object(object_name); let deleted = obj.delete(id, from_edge, &self.storages); if deleted { let edges = self.graph.edges_directed(self.nodes[&obj.name], Outgoing); for e in edges { e.weight().delete_all(id, &obj.id_type, self); } } } /// Validate that the objects and edges described in the schema exist in the corresponding storage as expected. Additionally, ensure that all objects in the graph are reachable by traversal via `deep` or `refcount` edges starting at an object with deletion type of `directly`, `directly_only`, `short_ttl`, or `not_deleted`. This ensures that all objects are deletable and accounted for. pub fn validate(&self) { println!("\u{1f50d} {}", Cyan.bold().paint("Validating DelF graph...")); let mut errs = Vec::new(); let mut passed = true; for (_, node_id) in self.nodes.iter() { match self.graph .node_weight(*node_id) .unwrap() .validate(&self.storages) { Err(e) => errs.push(e), _ => () } } if errs.len() > 0 { passed = false; println!("\u{274c} {}", Red.paint("Not all objects found in storage")); for err in errs.drain(..) { println!(" {}", err); } } else { println!("\u{2705} {}", Green.paint("Objects exist in storage")); } for (_, edge_id) in self.edges.iter() { match self.graph.edge_weight(*edge_id).unwrap().validate(self) { Err(e) => errs.push(e), _ => () } } if errs.len() > 0 { passed = false; println!("\u{274c} {}", Red.paint("Not all edges found in storage")); for err in errs.drain(..) { println!(" {}", err); } } else { println!("\u{2705} {}", Green.paint("Edges exist in storage")); } match self.reachability_analysis() { Err(e) => errs.push(e), _ => () } if errs.len() > 0 { passed = false; println!("\u{274c} {}", Red.paint("Not all objects deletable")); for err in errs.drain(..) { println!(" {}", err); } } else { println!("\u{2705} {}", Green.paint("All objects deletable")); } if passed { println!("\u{1F680} {} \u{1F680}", Green.bold().paint("Validation successful!")); } else { println!("\u{26a0} {} \u{26a0}", Red.bold().paint("Validation errors found")); } } // Starting from a directly deletable (or excepted) node, ensure all ndoes are reached. fn reachability_analysis(&self) -> Result<(), String> { let mut visited_nodes = HashSet::new(); for (_, node_id) in self.nodes.iter() { let obj = self.graph.node_weight(*node_id).unwrap(); match obj.deletion { object::DeleteType::ShortTTL | object::DeleteType::Directly | object::DeleteType::DirectlyOnly | object::DeleteType::NotDeleted => { // this object is a starting point in traversal, start traversal self.visit_node(&obj.name, &mut visited_nodes); } _ => (), } } if visited_nodes.len() != self.nodes.len() { let node_set: HashSet<String> = self.nodes.keys().cloned().collect(); return Err(format!( "Not all objects are deletable: {:?}", node_set.difference(&visited_nodes) )); } else { return Ok(()); } } // Recursively visit all un-visited nodes that are connected via depp or refcounte edges from the starting node with the passed in name fn visit_node(&self, name: &String, visited_nodes: &mut HashSet<String>) { visited_nodes.insert(name.clone()); let edges = self.graph.edges_directed(self.nodes[name], Outgoing); for e in edges { let ew = e.weight(); match ew.deletion { edge::DeleteType::Deep | edge::DeleteType::RefCount => { if !visited_nodes.contains(&ew.to.object_type) { self.visit_node(&ew.to.object_type, visited_nodes); } } _ => (), } } } // find all the inbound edges for a given object fn get_inbound_edges(&self, obj: &object::DelfObject) -> Vec<&edge::DelfEdge> { let object_id = self.nodes.get(&obj.name).unwrap(); let edges = self.graph.edges_directed(*object_id, Incoming); let mut res = Vec::new(); for edge in edges { res.push(edge.weight()); } return res; } /// Check all objects in the DelfGraph with the deletion type of `short_ttl` if there are instances of the object which are past their expiration time. If so, delete the objects. pub fn check_short_ttl(&self) { for (_, node_id) in self.nodes.iter() { let obj = self.graph.node_weight(*node_id).unwrap(); for obj_id in obj.check_short_ttl(&self.storages).iter() { self.delete_object(&obj.name, obj_id); } } } }
true
6c0e8e36b308ca708bae70153efefedd172f86a1
Rust
DesmondWillowbrook/cargo-optional-features-for-testing-and-examples
/src/main.rs
UTF-8
316
2.96875
3
[]
no_license
use test_features::one::add_one; #[cfg(feature = "add_two")] use test_features::two::add_two; fn main () -> std::io::Result<()> { let num: usize = 5; println!("Add 1 to num: {}", add_one(num)); #[cfg(feature = "add_two")] { println!("Add 2 to num: {}", add_two(num)); } Ok(()) }
true
c844b05ad06a8c4daa911b893ebd4d3d01a64450
Rust
schungx/rhai
/tests/debugging.rs
UTF-8
2,320
2.96875
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#![cfg(feature = "debugging")] use rhai::{Engine, INT}; #[cfg(not(feature = "no_index"))] use rhai::Array; #[cfg(not(feature = "no_object"))] use rhai::Map; #[test] fn test_debugging() { let mut engine = Engine::new(); engine.register_debugger( |_, dbg| dbg, |_, _, _, _, _| Ok(rhai::debugger::DebuggerCommand::Continue), ); #[cfg(not(feature = "no_function"))] #[cfg(not(feature = "no_index"))] { let r = engine .eval::<Array>( " fn foo(x) { if x >= 5 { back_trace() } else { foo(x+1) } } foo(0) ", ) .unwrap(); assert_eq!(r.len(), 6); assert_eq!(engine.eval::<INT>("len(back_trace())").unwrap(), 0); } } #[test] #[cfg(not(feature = "no_object"))] fn test_debugger_state() { let mut engine = Engine::new(); engine.register_debugger( |_, mut debugger| { // Say, use an object map for the debugger state let mut state = Map::new(); // Initialize properties state.insert("hello".into(), (42 as INT).into()); state.insert("foo".into(), false.into()); debugger.set_state(state); debugger }, |mut context, _, _, _, _| { // Print debugger state - which is an object map println!( "Current state = {}", context.global_runtime_state().debugger().state() ); // Modify state let mut state = context .global_runtime_state_mut() .debugger_mut() .state_mut() .write_lock::<Map>() .unwrap(); let hello = state.get("hello").unwrap().as_int().unwrap(); state.insert("hello".into(), (hello + 1).into()); state.insert("foo".into(), true.into()); state.insert("something_new".into(), "hello, world!".into()); // Continue with debugging Ok(rhai::debugger::DebuggerCommand::StepInto) }, ); engine.run("let x = 42;").unwrap(); }
true
1921912b6e8472305a883f1d2b93b569d281c1c7
Rust
ssolaric/cses.fi
/2. Sorting and Searching/7-sum-of-two-values.rs
UTF-8
1,696
3.3125
3
[ "MIT" ]
permissive
// This is the 2sum problem. use std::collections::HashMap; use std::io; use std::str; pub struct Scanner<R> { reader: R, buffer: Vec<String>, } impl<R: io::BufRead> Scanner<R> { pub fn new(reader: R) -> Self { Self { reader, buffer: vec![], } } pub fn token<T: str::FromStr>(&mut self) -> T { loop { if let Some(token) = self.buffer.pop() { return token.parse().ok().expect("Failed parse"); } let mut input = String::new(); self.reader.read_line(&mut input).expect("Failed read"); self.buffer = input.split_whitespace().rev().map(String::from).collect(); } } } fn two_sum(values: &[i32], target: i32) -> Option<(usize, usize)> { let mut to_index = HashMap::new(); let n = values.len(); for i in 0..n { let to_find = target - values[i]; if let Some(ind) = to_index.get(&to_find) { return Some((*ind, i)); } to_index.insert(values[i], i); } None } fn solve<R: io::BufRead, W: io::Write>(scan: &mut Scanner<R>, out: &mut W) { let n: usize = scan.token(); let target: i32 = scan.token(); let mut values = Vec::new(); for _ in 0..n { values.push(scan.token::<i32>()); } match two_sum(&values, target) { Some((pos1, pos2)) => writeln!(out, "{} {}", pos1 + 1, pos2 + 1).ok(), None => writeln!(out, "IMPOSSIBLE").ok(), }; } fn main() { let (stdin, stdout) = (io::stdin(), io::stdout()); let mut scan = Scanner::new(stdin.lock()); let mut out = io::BufWriter::new(stdout.lock()); solve(&mut scan, &mut out); }
true
0231e78af7a2c964807b586b2b572d0e445cdd36
Rust
UnicodeSnowman/matasano-crypto-challenges
/rust/src/main.rs
UTF-8
1,502
2.90625
3
[]
no_license
extern crate matasano; use matasano::one; use matasano::two; fn main() { println!("{}", "Section One"); println!("{}", "================"); //one::convert_hex_to_base64("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"); //one::fixed_xor(); //let hex_string: &str = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"; //let bytes: Vec<u8> = hex_string.from_hex().unwrap(); //one::single_bit_xor_cypher(&bytes); //one::single_bit_xor_cypher(&hex_string); // let winner = one::detect_single_character_xor(); // match winner { // Ok(w) => println!("WINNAR {:?} {:?}", w.key, w.secret), // Err(err) => println!("oh noes, you lose {:?}", err) // } //let key: Vec<u8> = vec!(b'I', b'C', b'E'); //let string_bytes: Vec<u8> = "Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal".bytes().collect(); //let xored_string = one::repeating_key_xor(&string_bytes, &key); //let res = one::break_repeating_key_xor(); println!("{}", "Section Two"); println!("{}", "================"); // let mut bytes = "YELLOW SUBMARINE".bytes().collect(); // two::pad_pkcs_7(&mut bytes, 20); // println!("{:?}", String::from_utf8(bytes).unwrap()); //two::an_ecb_cbc_detection_oracle::run(); //two::byte_at_a_time_ecb_decryption_simple::run(); //two::ecb_cut_and_paste::run(); two::byte_at_a_time_ecb_decryption_harder::run(); }
true
e4c3abce32634160b79e30513b200d65573cb2d5
Rust
Palmr/lameboy
/src/lameboy/cpu/instructions/stack.rs
UTF-8
1,350
3.25
3
[ "MIT" ]
permissive
use crate::lameboy::cpu::Cpu; /// Push an 8-bit value to the stack. /// Decrements the stack pointer and then writes the 8-bit value using the new stack pointer value. pub fn push_stack_d8(cpu: &mut Cpu, d8: u8) { // Decrement stack pointer cpu.registers.sp = cpu.registers.sp.wrapping_sub(1); // Write byte to stack cpu.mmu.write8(cpu.registers.sp, d8); } /// Push a 16-bit value to the stack. /// Pushing the high byte of the value first, then the low byte. pub fn push_stack_d16(cpu: &mut Cpu, d16: u16) { // Write high byte push_stack_d8(cpu, ((d16 >> 8) & 0xFF) as u8); // Write low byte push_stack_d8(cpu, (d16 & 0xFF) as u8); } /// Pop an 8-bit value off the stack. /// Decrements the stack pointer and then writes the 8-bit value using the new stack pointer value. pub fn pop_stack_d8(cpu: &mut Cpu) -> u8 { // Read byte from stack let value = cpu.mmu.read8(cpu.registers.sp); // Increment stack pointer cpu.registers.sp = cpu.registers.sp.wrapping_add(1); value } /// Pop a 16-bit value off the stack. /// Pushing the high byte of the value first, then the low byte. pub fn pop_stack_d16(cpu: &mut Cpu) -> u16 { let mut value: u16; // Pop low byte value = u16::from(pop_stack_d8(cpu)); // Pop high byte value |= (u16::from(pop_stack_d8(cpu))) << 8; value }
true
d8c93dcd1e1c57d800375b0cc53edfdc80aafdc8
Rust
feds01/lang
/compiler/hash-reporting/src/errors.rs
UTF-8
1,408
2.953125
3
[ "MIT" ]
permissive
//! Hash Compiler error and warning reporting module //! //! All rights reserved 2021 (c) The Hash Language authors use std::{io, process::exit}; use thiserror::Error; use hash_ast::error::ParseError; /// Enum representing the variants of error that can occur when running an interactive session #[derive(Error, Debug)] pub enum InteractiveCommandError { #[error("Unkown command `{0}`.")] UnrecognisedCommand(String), #[error("Command `{0}` does not take any arguments.")] ZeroArguments(String), // @Future: Maybe provide a second paramater to support multiple argument command #[error("Command `{0}` requires one argument.")] ArgumentMismatchError(String), #[error("Unexpected error: `{0}`")] InternalError(String), } /// Error message prefix const ERR: &str = "\x1b[31m\x1b[1merror\x1b[0m"; /// Errors that might occur when attempting to compile and or interpret a /// program. #[derive(Debug, Error)] pub enum CompilerError { #[error("{0}")] IoError(#[from] io::Error), #[error("{message}")] ArgumentError { message: String }, #[error("{0}")] ParseError(#[from] ParseError), #[error("{0}")] InterpreterError(#[from] InteractiveCommandError), } impl CompilerError { pub fn report_and_exit(&self) -> ! { self.report(); exit(-1); } pub fn report(&self) { println!("{}: {}", ERR, self); } }
true
a7b9e243d738716f575b35969fd85aa122dd714c
Rust
immunant/c2rust
/c2rust-bitfields-derive/src/lib.rs
UTF-8
8,743
2.65625
3
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
#![recursion_limit = "512"] use proc_macro::{Span, TokenStream}; use quote::quote; use syn::parse::Error; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{ parse_macro_input, Attribute, Field, Fields, Ident, ItemStruct, Lit, Meta, NestedMeta, Path, PathArguments, PathSegment, Token, }; #[cfg(target_endian = "big")] compile_error!("Big endian architectures are not currently supported"); /// This struct keeps track of a single bitfield attr's params /// as well as the bitfield's field name. #[derive(Debug)] struct BFFieldAttr { field_name: Ident, name: String, ty: String, bits: (String, proc_macro2::Span), } fn parse_bitfield_attr( attr: &Attribute, field_ident: &Ident, ) -> Result<Option<BFFieldAttr>, Error> { let mut name = None; let mut ty = None; let mut bits = None; let mut bits_span = None; if let Meta::List(meta_list) = attr.parse_meta()? { for nested_meta in meta_list.nested { if let NestedMeta::Meta(Meta::NameValue(meta_name_value)) = nested_meta { let rhs_string = match meta_name_value.lit { Lit::Str(lit_str) => lit_str.value(), _ => { let err_str = "Found bitfield attribute with non str literal assignment"; let span = meta_name_value.path.span(); return Err(Error::new(span, err_str)); } }; if let Some(lhs_ident) = meta_name_value.path.get_ident() { match lhs_ident.to_string().as_str() { "name" => name = Some(rhs_string), "ty" => ty = Some(rhs_string), "bits" => { bits = Some(rhs_string); bits_span = Some(meta_name_value.path.span()); } // This one shouldn't ever occur here, // but we're handling it just to be safe "padding" => { return Ok(None); } _ => {} } } } else if let NestedMeta::Meta(Meta::Path(ref path)) = nested_meta { if let Some(ident) = path.get_ident() { if ident == "padding" { return Ok(None); } } } } } if name.is_none() || ty.is_none() || bits.is_none() { let mut missing_fields = Vec::new(); if name.is_none() { missing_fields.push("name"); } if ty.is_none() { missing_fields.push("ty"); } if bits.is_none() { missing_fields.push("bits"); } let err_str = format!("Missing bitfield params: {:?}", missing_fields); let span = attr.path.segments.span(); return Err(Error::new(span, err_str)); } Ok(Some(BFFieldAttr { field_name: field_ident.clone(), name: name.unwrap(), ty: ty.unwrap(), bits: (bits.unwrap(), bits_span.unwrap()), })) } fn filter_and_parse_fields(field: &Field) -> Vec<Result<BFFieldAttr, Error>> { let attrs: Vec<_> = field .attrs .iter() .filter(|attr| attr.path.segments.last().unwrap().ident == "bitfield") .collect(); if attrs.is_empty() { return Vec::new(); } attrs .into_iter() .map(|attr| parse_bitfield_attr(attr, field.ident.as_ref().unwrap())) .flat_map(Result::transpose) // Remove the Ok(None) values .collect() } fn parse_bitfield_ty_path(field: &BFFieldAttr) -> Path { let leading_colon = if field.ty.starts_with("::") { Some(Token![::]([ Span::call_site().into(), Span::call_site().into(), ])) } else { None }; let mut segments = Punctuated::new(); let mut segment_strings = field.ty.split("::").peekable(); while let Some(segment_string) = segment_strings.next() { segments.push_value(PathSegment { ident: Ident::new(segment_string, Span::call_site().into()), arguments: PathArguments::None, }); if segment_strings.peek().is_some() { segments.push_punct(Token![::]([ Span::call_site().into(), Span::call_site().into(), ])); } } Path { leading_colon, segments, } } #[proc_macro_derive(BitfieldStruct, attributes(bitfield))] pub fn bitfield_struct(input: TokenStream) -> TokenStream { let struct_item = parse_macro_input!(input as ItemStruct); match bitfield_struct_impl(struct_item) { Ok(ts) => ts, Err(error) => error.to_compile_error().into(), } } fn bitfield_struct_impl(struct_item: ItemStruct) -> Result<TokenStream, Error> { // REVIEW: Should we throw a compile error if bit ranges on a single field overlap? let struct_ident = struct_item.ident; let fields = match struct_item.fields { Fields::Named(named_fields) => named_fields.named, Fields::Unnamed(_) => { let err_str = "Unnamed struct fields are not currently supported but may be in the future."; let span = struct_ident.span(); return Err(Error::new(span, err_str)); } Fields::Unit => { let err_str = "Cannot create bitfield struct out of struct with no fields"; let span = struct_ident.span(); return Err(Error::new(span, err_str)); } }; let bitfields: Result<Vec<BFFieldAttr>, Error> = fields.iter().flat_map(filter_and_parse_fields).collect(); let bitfields = bitfields?; let field_types: Vec<_> = bitfields.iter().map(parse_bitfield_ty_path).collect(); let field_types_return = &field_types; let field_types_typedef = &field_types; let field_types_setter_arg = &field_types; let method_names: Vec<_> = bitfields .iter() .map(|field| Ident::new(&field.name, Span::call_site().into())) .collect(); let field_names: Vec<_> = bitfields.iter().map(|field| &field.field_name).collect(); let field_names_setters = &field_names; let field_names_getters = &field_names; let method_name_setters: Vec<_> = method_names .iter() .map(|field_ident| { let span = Span::call_site().into(); let setter_name = &format!("set_{}", field_ident); Ident::new(setter_name, span) }) .collect(); let field_bit_info: Result<Vec<_>, Error> = bitfields .iter() .map(|field| { let bit_string = &field.bits.0; let nums: Vec<_> = bit_string.split("..=").collect(); let err_str = "bits param must be in the format \"1..=4\""; if nums.len() != 2 { return Err(Error::new(field.bits.1, err_str)); } let lhs = nums[0].parse::<usize>(); let rhs = nums[1].parse::<usize>(); let (lhs, rhs) = match (lhs, rhs) { (Err(_), _) | (_, Err(_)) => return Err(Error::new(field.bits.1, err_str)), (Ok(lhs), Ok(rhs)) => (lhs, rhs), }; Ok(quote! { (#lhs, #rhs) }) }) .collect(); let field_bit_info = field_bit_info?; let field_bit_info_setters = &field_bit_info; let field_bit_info_getters = &field_bit_info; // TODO: Method visibility determined by struct field visibility? let q = quote! { #[automatically_derived] impl #struct_ident { #( /// This method allows you to write to a bitfield with a value pub fn #method_name_setters(&mut self, int: #field_types_setter_arg) { use c2rust_bitfields::FieldType; let field = &mut self.#field_names_setters; let (lhs_bit, rhs_bit) = #field_bit_info_setters; int.set_field(field, (lhs_bit, rhs_bit)); } /// This method allows you to read from a bitfield to a value pub fn #method_names(&self) -> #field_types_return { use c2rust_bitfields::FieldType; type IntType = #field_types_typedef; let field = &self.#field_names_getters; let (lhs_bit, rhs_bit) = #field_bit_info_getters; <IntType as FieldType>::get_field(field, (lhs_bit, rhs_bit)) } )* } }; Ok(q.into()) }
true
b8df6ae8e4de33703de889d4f76f010bd7c789e5
Rust
stkfd/rd-histogram
/src/simple_vec_histogram.rs
UTF-8
6,022
3.125
3
[]
no_license
use num::traits::NumAssign; use ord_subset::{OrdSubset, OrdSubsetIterExt, OrdSubsetSliceExt}; use std::cmp::Ordering; use traits::{DynamicHistogram, EmptyClone, Merge, MergeRef}; #[derive(Clone, Debug, PartialEq)] pub struct SimpleVecHistogram<V, C> { bins: Vec<Bin<V, C>>, bins_cap: usize, } #[derive(Clone, Debug, PartialEq)] pub struct Bin<V, C> { left: V, right: V, count: C, sum: V, } impl<V: PartialOrd + OrdSubset + NumAssign + Copy, C: Clone + NumAssign + Copy> SimpleVecHistogram<V, C> { fn search_bins(&self, value: V) -> Result<usize, usize> { self.bins.binary_search_by(|probe| { if probe.left <= value && probe.right > value { Ordering::Equal } else if probe.left > value { Ordering::Greater } else { Ordering::Less } }) } fn shrink_to_fit(&mut self) { while self.bins.len() > self.bins_cap { let merge_result = self .bins .iter() .zip(self.bins.iter().skip(1)) .enumerate() .map(|(i, (bin, next_bin))| { // calculate distances between bins (i, bin, next_bin, next_bin.left - bin.right) }) .ord_subset_min_by_key(|(_i, _bin, _next_bin, distance)| *distance) .map(|(i, bin, next_bin, _)| { let merged_bin = Bin { left: bin.left, right: next_bin.right, sum: bin.sum + next_bin.sum, count: bin.count + next_bin.count, }; (i, merged_bin) }); if let Some((i, merged_bin)) = merge_result { self.bins[i] = merged_bin; self.bins.remove(i + 1); } } } fn bins(&self) -> &[Bin<V, C>] { self.bins.as_slice() } } impl<V: PartialOrd + OrdSubset + Copy + NumAssign, C: Copy + NumAssign + Into<V>> DynamicHistogram<V, C> for SimpleVecHistogram<V, C> { /// Type of a bin in this histogram type Bin = Bin<V, C>; /// Instantiate a histogram with the given number of maximum bins fn new(n_bins: usize) -> Self { SimpleVecHistogram { bins: Vec::with_capacity(n_bins), bins_cap: n_bins, } } /// Insert a new data point into this histogram fn insert(&mut self, value: V, count: C) { let search_result = self.search_bins(value); match search_result { Ok(found) => { self.bins[found].count += count; self.bins[found].sum += value * count.into(); } Err(insert_at) => self.bins.insert( insert_at, Bin { left: value, right: value, count, sum: value * count.into(), }, ), } self.shrink_to_fit(); } /// Count the total number of data points in this histogram (over all bins) fn count(&self) -> C { unimplemented!() } } impl<V: PartialOrd + OrdSubset + Copy + NumAssign, C: Copy + NumAssign + Into<V>> EmptyClone for SimpleVecHistogram<V, C> { fn empty_clone(&self) -> Self { SimpleVecHistogram::new(self.bins_cap) } } impl<V: PartialOrd + OrdSubset + Copy + NumAssign, C: Copy + NumAssign + Into<V>> MergeRef for SimpleVecHistogram<V, C> { fn merge_ref(&mut self, other: &Self) { self.bins.extend_from_slice(other.bins()); self.bins.ord_subset_sort_by_key(|b| b.left); self.shrink_to_fit(); } } impl<V: PartialOrd + OrdSubset + Copy + NumAssign, C: Copy + NumAssign + Into<V>> Merge for SimpleVecHistogram<V, C> { fn merge(&mut self, other: Self) { self.bins.extend(other.bins.into_iter()); self.bins.ord_subset_sort_by_key(|b| b.left); self.shrink_to_fit(); } } #[cfg(test)] mod tests { use super::*; #[test] fn insert() { // fill with the maximum bin number let mut h = SimpleVecHistogram::new(5); let samples: &[(f64, u32)] = &[(1., 1), (2., 1), (3., 1), (4., 1), (5., 1)]; h.insert_iter(samples); for (bin, s) in h.bins().iter().zip(samples.iter()) { assert_eq!(s.0, bin.left); assert_eq!(s.0, bin.right); } // checks merging the closest two bins h.insert(5.5, 2); assert_eq!( h.bins()[4], Bin { left: 5., right: 5.5, count: 3, sum: 16. } ); // checks inserting into an existing bin h.insert(5.2, 1); assert_eq!( h.bins()[4], Bin { left: 5., right: 5.5, count: 4, sum: 21.2 } ); } #[test] fn merge() { // fill with the maximum bin number let samples1: &[(f64, u32)] = &[(1., 1), (2., 1), (3., 1), (4., 1), (5., 1)]; let samples2: &[(f64, u32)] = &[(1.1, 1), (2.1, 1), (3.1, 1), (4.1, 1), (5.1, 1)]; let mut h = SimpleVecHistogram::new(5); h.insert_iter(samples1); println!("{:?}", h); let mut h2 = SimpleVecHistogram::new(5); h2.insert_iter(samples2); println!("{:?}", h2); h.merge(h2); println!("{:?}", h); assert_eq!(h.bins().len(), 5); assert_eq!( h.bins()[2], Bin { left: 3., right: 3.1, count: 2, sum: 6.1 } ); assert_eq!( h.bins()[4], Bin { left: 5., right: 5.1, count: 2, sum: 10.1 } ); } }
true
c0563791dd9ae4d6ca09b42b63a69f0273affb6d
Rust
emakryo/cmpro
/src/abc221/src/bin/c.rs
UTF-8
885
2.59375
3
[]
no_license
#![allow(unused_macros, unused_imports)] use proconio::marker::Bytes; macro_rules! dbg { ($($xs:expr),+) => { if cfg!(debug_assertions) { std::dbg!($($xs),+) } else { ($($xs),+) } } } fn main() { proconio::input!{ n: Bytes, } let m = n.len(); let mut cs = n.into_iter().map(|c| (c - b'0') as u64).collect::<Vec<_>>(); cs.sort(); cs.reverse(); let mut a = 0; let mut b = 0; for i in 0..m/2 { let c = cs[2*i]; let d = cs[2*i+1]; // d <= c if a <= b { a = 10*a + c; b = 10*b + d; } else { a = 10*a + d; b = 10*b + c; } } if m%2==1 { if a <= b { a = 10*a + cs[m-1]; } else { b = 10*b + cs[m-1]; } } println!("{}", a*b); }
true
134d79f3059cc8fda9706ba4154a79fba04014db
Rust
b-ramsey/cargo-generate
/src/git.rs
UTF-8
886
2.5625
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use git2::{ build::CheckoutBuilder, build::RepoBuilder, Repository as GitRepository, RepositoryInitOptions, }; use quicli::prelude::*; use remove_dir_all::remove_dir_all; use std::path::PathBuf; use Args; pub fn create(project_dir: &PathBuf, args: Args) -> Result<GitRepository> { let mut rb = RepoBuilder::new(); rb.bare(false).with_checkout(CheckoutBuilder::new()); if let Some(ref branch) = args.branch { rb.branch(branch); } Ok(rb.clone(&args.git, &project_dir)?) } pub fn remove_history(project_dir: &PathBuf) -> Result<()> { Ok(remove_dir_all(project_dir.join(".git")).context("Error cleaning up cloned template")?) } pub fn init(project_dir: &PathBuf) -> Result<GitRepository> { Ok( GitRepository::init_opts(project_dir, RepositoryInitOptions::new().bare(false)) .context("Couldn't init new repository")?, ) }
true
d63faa075580a490542c4c763c335b56e8df9877
Rust
racer-rust/racer
/src/racer/codecleaner.rs
UTF-8
14,591
3.5
4
[ "MIT" ]
permissive
use crate::core::{BytePos, ByteRange}; /// Type of the string #[derive(Clone, Copy, Debug)] enum StrStyle { /// normal string starts with " Cooked, /// Raw(n) => raw string started with n #s Raw(usize), } #[derive(Clone, Copy)] enum State { Code, Comment, CommentBlock, String(StrStyle), Char, Finished, } #[derive(Clone, Copy)] pub struct CodeIndicesIter<'a> { src: &'a str, pos: BytePos, state: State, } impl<'a> Iterator for CodeIndicesIter<'a> { type Item = ByteRange; fn next(&mut self) -> Option<ByteRange> { match self.state { State::Code => Some(self.code()), State::Comment => Some(self.comment()), State::CommentBlock => Some(self.comment_block()), State::String(style) => Some(self.string(style)), State::Char => Some(self.char()), State::Finished => None, } } } impl<'a> CodeIndicesIter<'a> { fn code(&mut self) -> ByteRange { let mut pos = self.pos; let start = match self.state { State::String(_) | State::Char => pos.decrement(), // include quote _ => pos, }; let src_bytes = self.src.as_bytes(); for &b in &src_bytes[pos.0..] { pos = pos.increment(); match b { b'/' if src_bytes.len() > pos.0 => match src_bytes[pos.0] { b'/' => { self.state = State::Comment; self.pos = pos.increment(); return ByteRange::new(start, pos.decrement()); } b'*' => { self.state = State::CommentBlock; self.pos = pos.increment(); return ByteRange::new(start, pos.decrement()); } _ => {} }, b'"' => { // " let str_type = self.detect_str_type(pos); self.state = State::String(str_type); self.pos = pos; return ByteRange::new(start, pos); // include dblquotes } b'\'' => { // single quotes are also used for lifetimes, so we need to // be confident that this is not a lifetime. // Look for backslash starting the escape, or a closing quote: if src_bytes.len() > pos.increment().0 && (src_bytes[pos.0] == b'\\' || src_bytes[pos.increment().0] == b'\'') { self.state = State::Char; self.pos = pos; return ByteRange::new(start, pos); // include single quote } } _ => {} } } self.state = State::Finished; ByteRange::new(start, self.src.len().into()) } fn comment(&mut self) -> ByteRange { let mut pos = self.pos; let src_bytes = self.src.as_bytes(); for &b in &src_bytes[pos.0..] { pos = pos.increment(); if b == b'\n' { if pos.0 + 2 <= src_bytes.len() && src_bytes[pos.0..pos.0 + 2] == [b'/', b'/'] { continue; } break; } } self.pos = pos; self.code() } fn comment_block(&mut self) -> ByteRange { let mut nesting_level = 0usize; let mut prev = b' '; let mut pos = self.pos; for &b in &self.src.as_bytes()[pos.0..] { pos = pos.increment(); match b { b'/' if prev == b'*' => { prev = b' '; if nesting_level == 0 { break; } else { nesting_level -= 1; } } b'*' if prev == b'/' => { prev = b' '; nesting_level += 1; } _ => { prev = b; } } } self.pos = pos; self.code() } fn string(&mut self, str_type: StrStyle) -> ByteRange { let src_bytes = self.src.as_bytes(); let mut pos = self.pos; match str_type { StrStyle::Raw(level) => { // raw string (e.g. br#"\"#) #[derive(Debug)] enum SharpState { Sharp { // number of preceding #s num_sharps: usize, // Position of last " quote_pos: BytePos, }, None, // No preceding "##... } let mut cur_state = SharpState::None; let mut end_was_found = false; // detect corresponding end(if start is r##", "##) greedily for (i, &b) in src_bytes[self.pos.0..].iter().enumerate() { match cur_state { SharpState::Sharp { num_sharps, quote_pos, } => { cur_state = match b { b'#' => SharpState::Sharp { num_sharps: num_sharps + 1, quote_pos, }, b'"' => SharpState::Sharp { num_sharps: 0, quote_pos: BytePos(i), }, _ => SharpState::None, } } SharpState::None => { if b == b'"' { cur_state = SharpState::Sharp { num_sharps: 0, quote_pos: BytePos(i), }; } } } if let SharpState::Sharp { num_sharps, quote_pos, } = cur_state { if num_sharps == level { end_was_found = true; pos += quote_pos.increment(); break; } } } if !end_was_found { pos = src_bytes.len().into(); } } StrStyle::Cooked => { let mut is_not_escaped = true; for &b in &src_bytes[pos.0..] { pos = pos.increment(); match b { b'"' if is_not_escaped => { break; } // " b'\\' => { is_not_escaped = !is_not_escaped; } _ => { is_not_escaped = true; } } } } }; self.pos = pos; self.code() } fn char(&mut self) -> ByteRange { let mut is_not_escaped = true; let mut pos = self.pos; for &b in &self.src.as_bytes()[pos.0..] { pos = pos.increment(); match b { b'\'' if is_not_escaped => { break; } b'\\' => { is_not_escaped = !is_not_escaped; } _ => { is_not_escaped = true; } } } self.pos = pos; self.code() } fn detect_str_type(&self, pos: BytePos) -> StrStyle { let src_bytes = self.src.as_bytes(); let mut sharp = 0; if pos == BytePos::ZERO { return StrStyle::Cooked; } // now pos is at one byte after ", so we have to start at pos - 2 for &b in src_bytes[..pos.decrement().0].iter().rev() { match b { b'#' => sharp += 1, b'r' => return StrStyle::Raw(sharp), _ => return StrStyle::Cooked, } } StrStyle::Cooked } } /// Returns indices of chunks of code (minus comments and string contents) pub fn code_chunks(src: &str) -> CodeIndicesIter<'_> { CodeIndicesIter { src, state: State::Code, pos: BytePos::ZERO, } } #[cfg(test)] mod code_indices_iter_test { use super::*; use crate::testutils::{rejustify, slice}; #[test] fn removes_a_comment() { let src = &rejustify( " this is some code // this is a comment some more code ", ); let mut it = code_chunks(src); assert_eq!("this is some code ", slice(src, it.next().unwrap())); assert_eq!("some more code", slice(src, it.next().unwrap())); } #[test] fn removes_consecutive_comments() { let src = &rejustify( " this is some code // this is a comment // this is more comment // another comment some more code ", ); let mut it = code_chunks(src); assert_eq!("this is some code ", slice(src, it.next().unwrap())); assert_eq!("some more code", slice(src, it.next().unwrap())); } #[test] fn removes_string_contents() { let src = &rejustify( " this is some code \"this is a string\" more code ", ); let mut it = code_chunks(src); assert_eq!("this is some code \"", slice(src, it.next().unwrap())); assert_eq!("\" more code", slice(src, it.next().unwrap())); } #[test] fn removes_char_contents() { let src = &rejustify( " this is some code \'\"\' more code \'\\x00\' and \'\\\'\' that\'s it ", ); let mut it = code_chunks(src); assert_eq!("this is some code \'", slice(src, it.next().unwrap())); assert_eq!("\' more code \'", slice(src, it.next().unwrap())); assert_eq!("\' and \'", slice(src, it.next().unwrap())); assert_eq!("\' that\'s it", slice(src, it.next().unwrap())); } #[test] fn removes_string_contents_with_a_comment_in_it() { let src = &rejustify( " this is some code \"string with a // fake comment \" more code ", ); let mut it = code_chunks(src); assert_eq!("this is some code \"", slice(src, it.next().unwrap())); assert_eq!("\" more code", slice(src, it.next().unwrap())); } #[test] fn removes_a_comment_with_a_dbl_quote_in_it() { let src = &rejustify( " this is some code // comment with \" double quote some more code ", ); let mut it = code_chunks(src); assert_eq!("this is some code ", slice(src, it.next().unwrap())); assert_eq!("some more code", slice(src, it.next().unwrap())); } #[test] fn removes_multiline_comment() { let src = &rejustify( " this is some code /* this is a \"multiline\" comment */some more code ", ); let mut it = code_chunks(src); assert_eq!("this is some code ", slice(src, it.next().unwrap())); assert_eq!("some more code", slice(src, it.next().unwrap())); } #[test] fn handles_nesting_of_block_comments() { let src = &rejustify( " this is some code /* nested /* block */ comment */ some more code ", ); let mut it = code_chunks(src); assert_eq!("this is some code ", slice(src, it.next().unwrap())); assert_eq!(" some more code", slice(src, it.next().unwrap())); } #[test] fn handles_documentation_block_comments_nested_into_block_comments() { let src = &rejustify( " this is some code /* nested /** documentation block */ comment */ some more code ", ); let mut it = code_chunks(src); assert_eq!("this is some code ", slice(src, it.next().unwrap())); assert_eq!(" some more code", slice(src, it.next().unwrap())); } #[test] fn removes_string_with_escaped_dblquote_in_it() { let src = &rejustify( " this is some code \"string with a \\\" escaped dblquote fake comment \" more code ", ); let mut it = code_chunks(src); assert_eq!("this is some code \"", slice(src, it.next().unwrap())); assert_eq!("\" more code", slice(src, it.next().unwrap())); } #[test] fn removes_raw_string_with_dangling_escape_in_it() { let src = &rejustify( " this is some code br\" escaped dblquote raw string \\\" more code ", ); let mut it = code_chunks(src); assert_eq!("this is some code br\"", slice(src, it.next().unwrap())); assert_eq!("\" more code", slice(src, it.next().unwrap())); } #[test] fn removes_string_with_escaped_slash_before_dblquote_in_it() { let src = &rejustify(" this is some code \"string with an escaped slash, so dbl quote does end the string after all \\\\\" more code "); let mut it = code_chunks(src); assert_eq!("this is some code \"", slice(src, it.next().unwrap())); assert_eq!("\" more code", slice(src, it.next().unwrap())); } #[test] fn handles_tricky_bit_from_str_rs() { let src = &rejustify( " before(\"\\\\\'\\\\\\\"\\\\\\\\\"); more_code(\" skip me \") ", ); for range in code_chunks(src) { let range = || range.to_range(); println!("BLOB |{}|", &src[range()]); if src[range()].contains("skip me") { panic!("{}", &src[range()]); } } } #[test] fn removes_nested_rawstr() { let src = &rejustify( r####" this is some code br###""" r##""##"### more code "####, ); let mut it = code_chunks(src); assert_eq!("this is some code br###\"", slice(src, it.next().unwrap())); assert_eq!("\"### more code", slice(src, it.next().unwrap())); } }
true
3f25a94579101de7158a4a0e2f469e40937aa5cd
Rust
Aloso/parkour
/src/error.rs
UTF-8
9,015
3.71875
4
[ "MIT", "Apache-2.0" ]
permissive
use std::fmt; use std::num::{ParseFloatError, ParseIntError}; use crate::help::PossibleValues; use crate::util::Flag; /// The error type when parsing command-line arguments. You can create an /// `Error` by creating an `ErrorInner` and converting it with `.into()`. /// /// This error type supports an error source for attaching context to the error. #[derive(Debug)] pub struct Error { inner: ErrorInner, source: Option<Box<dyn std::error::Error + Sync + Send + 'static>>, } impl Error { /// Attach context to the error. Note that this overwrites the current /// source, if there is one. /// /// ### Usage /// /// ``` /// use parkour::{Error, util::Flag}; /// /// Error::missing_value() /// .with_source(Error::in_subcommand("test")) /// # ; /// ``` /// /// This could produce the following output: /// ```text /// missing value /// source: in subcommand `test` /// ``` pub fn with_source( self, source: impl std::error::Error + Sync + Send + 'static, ) -> Self { Error { source: Some(Box::new(source)), ..self } } /// Attach context to the error. This function ensures that an already /// attached source isn't discarded, but appended to the the new source. The /// sources therefore form a singly linked list. /// /// ### Usage /// /// ``` /// use parkour::{Error, ErrorInner, util::Flag}; /// /// Error::missing_value() /// .chain(ErrorInner::IncompleteValue(1)) /// # ; /// ``` pub fn chain(mut self, source: ErrorInner) -> Self { let mut new = Self::from(source); new.source = self.source.take(); Error { source: Some(Box::new(new)), ..self } } /// Create a `NoValue` error pub fn no_value() -> Self { ErrorInner::NoValue.into() } /// Returns `true` if this is a `NoValue` error pub fn is_no_value(&self) -> bool { matches!(self.inner, ErrorInner::NoValue) } /// Create a `MissingValue` error pub fn missing_value() -> Self { ErrorInner::MissingValue.into() } /// Returns the [`ErrorInner`] of this error pub fn inner(&self) -> &ErrorInner { &self.inner } /// Create a `EarlyExit` error pub fn early_exit() -> Self { ErrorInner::EarlyExit.into() } /// Returns `true` if this is a `EarlyExit` error pub fn is_early_exit(&self) -> bool { matches!(self.inner, ErrorInner::EarlyExit) } /// Create a `UnexpectedValue` error pub fn unexpected_value( got: impl ToString, expected: Option<PossibleValues>, ) -> Self { ErrorInner::InvalidValue { got: got.to_string(), expected }.into() } /// Create a `MissingArgument` error pub fn missing_argument(arg: impl ToString) -> Self { ErrorInner::MissingArgument { arg: arg.to_string() }.into() } /// Create a `InArgument` error pub fn in_argument(flag: &Flag) -> Self { ErrorInner::InArgument(flag.first_to_string()).into() } /// Create a `InSubcommand` error pub fn in_subcommand(cmd: impl ToString) -> Self { ErrorInner::InSubcommand(cmd.to_string()).into() } /// Create a `TooManyArgOccurrences` error pub fn too_many_arg_occurrences(arg: impl ToString, max: Option<u32>) -> Self { ErrorInner::TooManyArgOccurrences { arg: arg.to_string(), max }.into() } } impl From<ErrorInner> for Error { fn from(inner: ErrorInner) -> Self { Error { inner, source: None } } } /// The error type when parsing command-line arguments #[derive(Debug, PartialEq)] pub enum ErrorInner { /// The argument you tried to parse wasn't present at the current position. /// Has a similar purpose as `Option::None` NoValue, /// The argument you tried to parse wasn't present at the current position, /// but was required MissingValue, /// The argument you tried to parse was only partly present IncompleteValue(usize), /// Used when an argument should abort argument parsing, like --help EarlyExit, /// Indicates that the error originated in the specified argument. This /// should be used as the source for another error InArgument(String), /// Indicates that the error originated in the specified subcommand. This /// should be used as the source for another error InSubcommand(String), /// The parsed value doesn't meet our expectations InvalidValue { /// The value we tried to parse got: String, /// The expectation that was violated. For example, this string can /// contain a list of accepted values. expected: Option<PossibleValues>, }, /// The parsed list contains more items than allowed TooManyValues { /// The maximum number of items max: usize, /// The number of items that was parsed count: usize, }, /// The parsed array has the wrong length WrongNumberOfValues { /// The length of the array expected: usize, /// The number of items that was parsed got: usize, }, /// A required argument was not provided MissingArgument { /// The name of the argument that is missing arg: String, }, /// An unknown argument was provided UnexpectedArgument { /// The (full) argument that wasn't expected arg: String, }, /// The argument has a value, but no value was expected UnexpectedValue { /// The value of the argument value: String, }, /// An argument was provided more often than allowed TooManyArgOccurrences { /// The name of the argument that was provided too many times arg: String, /// The maximum number of times the argument may be provided max: Option<u32>, }, /// Parsing an integer failed ParseIntError(ParseIntError), /// Parsing a floating-point number failed ParseFloatError(ParseFloatError), } impl From<ParseIntError> for Error { fn from(e: ParseIntError) -> Self { ErrorInner::ParseIntError(e).into() } } impl From<ParseFloatError> for Error { fn from(e: ParseFloatError) -> Self { ErrorInner::ParseFloatError(e).into() } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.source { Some(source) => Some(&**source as &(dyn std::error::Error + 'static)), None => None, } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.inner { ErrorInner::NoValue => write!(f, "no value"), ErrorInner::MissingValue => write!(f, "missing value"), ErrorInner::IncompleteValue(part) => { write!(f, "missing part {} of value", part) } ErrorInner::EarlyExit => write!(f, "early exit"), ErrorInner::InArgument(opt) => write!(f, "in `{}`", opt.escape_debug()), ErrorInner::InSubcommand(cmd) => { write!(f, "in subcommand {}", cmd.escape_debug()) } ErrorInner::InvalidValue { expected, got } => { if let Some(expected) = expected { write!( f, "unexpected value `{}`, expected {}", got.escape_debug(), expected, ) } else { write!(f, "unexpected value `{}`", got.escape_debug()) } } ErrorInner::UnexpectedArgument { arg } => { write!(f, "unexpected argument `{}`", arg.escape_debug()) } ErrorInner::UnexpectedValue { value } => { write!(f, "unexpected value `{}`", value.escape_debug()) } ErrorInner::TooManyValues { max, count } => { write!(f, "too many values, expected at most {}, got {}", max, count) } ErrorInner::WrongNumberOfValues { expected, got } => { write!(f, "wrong number of values, expected {}, got {}", expected, got) } ErrorInner::MissingArgument { arg } => { write!(f, "required {} was not provided", arg) } ErrorInner::TooManyArgOccurrences { arg, max } => { if let Some(max) = max { write!( f, "{} was used too often, it can be used at most {} times", arg, max ) } else { write!(f, "{} was used too often", arg) } } ErrorInner::ParseIntError(e) => write!(f, "{}", e), ErrorInner::ParseFloatError(e) => write!(f, "{}", e), } } }
true
3abb46cea2b60c54f13e04b08078c306026a654a
Rust
philipcraig/mylang
/src/frame.rs
UTF-8
8,295
3.5625
4
[ "MIT" ]
permissive
use crate::ast::{BinaryOp, Expression, Function, OpName, Statement, UnaryOp}; use std::{collections::HashMap, fmt, rc::Rc}; use thiserror::Error; #[derive(Debug, PartialEq)] pub enum Value { Boolean(bool), Float(f64), Function(Rc<Function>), Integer(i32), String(Rc<String>), } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Value::Boolean(b) => write!(f, "Boolean({})", b), Value::Float(float) => write!(f, "Float({})", float), Value::Function(_) => write!(f, "Function()"), Value::Integer(i) => write!(f, "Integer({})", i), Value::String(s) => write!(f, "String({})", s), } } } #[derive(Error, Debug, PartialEq)] pub enum EvaluationError { #[error("Evaluation requested on unknown identifier `{0}`")] UnknownIdentifier(String), #[error("Called on {0}, which is not a callable type")] NonCallableType(String), #[error("Mismatch in argument count for Function {name:?}. Expected {expected:?} arguments but got {got:?}")] ArgumentCountMismatch { name: String, expected: usize, got: usize, }, #[error("Function {0} didn't return a value")] NoReturnValue(String), #[error("Can't apply a unary operation {opname:?} to {value:?}")] IllegalUnaryOperation { opname: String, value: String }, #[error("Can't apply binary operation {opname:?} to {left:?} {right:?}")] IllegalBinaryOperation { opname: String, left: String, right: String, }, } pub struct Frame { values: HashMap<String, Rc<Value>>, } impl Frame { pub(crate) fn new() -> Self { Self { values: HashMap::new(), } } pub(crate) fn evaluate_body( &mut self, body: &[Statement], ) -> Result<Option<Rc<Value>>, EvaluationError> { for statement in body { if let Some(v) = self.evaluate_statement(statement)? { return Ok(Some(v)); } } Ok(None) } fn evaluate_expression(&self, expression: &Expression) -> Result<Rc<Value>, EvaluationError> { match expression { Expression::Boolean(b) => Ok(Rc::new(Value::Boolean(*b))), Expression::Float(f) => Ok(Rc::new(Value::Float(*f))), Expression::Function(function) => Ok(Rc::new(Value::Function(function.clone()))), Expression::Integer(i) => Ok(Rc::new(Value::Integer(*i))), Expression::StringLiteral(s) => Ok(Rc::new(Value::String(s.clone()))), Expression::Identifier(identifier) => self.values.get(identifier).map_or_else( || Err(EvaluationError::UnknownIdentifier(identifier.to_string())), |value| Ok(Rc::clone(value)), ), Expression::Call(call) => { if let Some(value) = self.values.get(&call.name) { match &**value { Value::Boolean(_) | Value::Float(_) | Value::Integer(_) | Value::String(_) => { Err(EvaluationError::NonCallableType((**value).to_string())) } Value::Function(function) => { if function.arguments.len() == call.arguments.len() { let mut function_frame = Self::new(); for (arg_name, arg_expression) in function.arguments.iter().zip(call.arguments.iter()) { let argument_value = self.evaluate_expression(arg_expression)?; function_frame .values .insert(arg_name.clone(), argument_value); } (function_frame.evaluate_body(&function.body)?).map_or_else( || Err(EvaluationError::NoReturnValue(call.name.clone())), |return_value| Ok(Rc::clone(&return_value)), ) } else { Err(EvaluationError::ArgumentCountMismatch { name: call.name.clone(), expected: function.arguments.len(), got: call.arguments.len(), }) } } } } else { Err(EvaluationError::UnknownIdentifier(call.name.clone())) } } Expression::UnaryOp(op) => self.evaluate_unary_op(op), Expression::BinaryOp(op) => self.evaluate_binary_op(op), } } fn evaluate_statement( &mut self, statement: &Statement, ) -> Result<Option<Rc<Value>>, EvaluationError> { match &statement { Statement::Let(let_statement) => { let value = self.evaluate_expression(&let_statement.expression)?; self.values.insert(let_statement.identifier.clone(), value); Ok(None) } Statement::Return(return_statement) => { Ok(Some(self.evaluate_expression(return_statement)?)) } Statement::Expression(expression) => { let _value = self.evaluate_expression(expression); // TODO: Print _value to the console if we're in a REPL. Ok(None) } } } fn evaluate_unary_op(&self, op: &UnaryOp) -> Result<Rc<Value>, EvaluationError> { let target = self.evaluate_expression(&op.target)?; match (&*target, &op.operation) { (Value::Float(_) | Value::Integer(_), OpName::Plus) => Ok(target.clone()), (Value::Float(f), OpName::Minus) => Ok(Rc::new(Value::Float(-f))), (Value::Integer(i), OpName::Minus) => Ok(Rc::new(Value::Integer(-i))), ( Value::Boolean(_) | Value::Function(_) | Value::String(_) | Value::Float(_) | Value::Integer(_), _, ) => Err(EvaluationError::IllegalUnaryOperation { opname: op.operation.to_string(), value: (*target).to_string(), }), } } fn evaluate_binary_op(&self, op: &BinaryOp) -> Result<Rc<Value>, EvaluationError> { let left = self.evaluate_expression(&op.left)?; let right = self.evaluate_expression(&op.right)?; match (&op.operation, &*left, &*right) { (OpName::Plus, &Value::Integer(lhs), &Value::Integer(rhs)) => { Ok(Rc::new(Value::Integer(lhs + rhs))) } (OpName::Minus, &Value::Integer(lhs), &Value::Integer(rhs)) => { Ok(Rc::new(Value::Integer(lhs - rhs))) } (OpName::Divide, &Value::Integer(lhs), &Value::Integer(rhs)) => { Ok(Rc::new(Value::Integer(lhs / rhs))) } (OpName::Multiply, &Value::Integer(lhs), &Value::Integer(rhs)) => { Ok(Rc::new(Value::Integer(lhs * rhs))) } (OpName::Plus, &Value::Float(lhs), &Value::Float(rhs)) => { Ok(Rc::new(Value::Float(lhs + rhs))) } (OpName::Minus, &Value::Float(lhs), &Value::Float(rhs)) => { Ok(Rc::new(Value::Float(lhs - rhs))) } (OpName::Divide, &Value::Float(lhs), &Value::Float(rhs)) => { Ok(Rc::new(Value::Float(lhs / rhs))) } (OpName::Multiply, &Value::Float(lhs), &Value::Float(rhs)) => { Ok(Rc::new(Value::Float(lhs * rhs))) } _ => Err(EvaluationError::IllegalBinaryOperation { opname: op.operation.to_string(), left: left.to_string(), right: right.to_string(), }), } } }
true
9f6d6cab3295d329c4a4e91d8b2012c420e076ed
Rust
tatetian/ngo2
/src/libos/src/entry/context_switch/gp_regs.rs
UTF-8
1,147
2.5625
3
[ "BSD-3-Clause" ]
permissive
use crate::prelude::*; /// The general-purpose registers of CPU. /// /// Note. The Rust definition of this struct must be kept in sync with assembly code. #[derive(Clone, Copy, Debug, Default)] #[repr(C)] pub struct GpRegs { pub r8: u64, pub r9: u64, pub r10: u64, pub r11: u64, pub r12: u64, pub r13: u64, pub r14: u64, pub r15: u64, pub rdi: u64, pub rsi: u64, pub rbp: u64, pub rbx: u64, pub rdx: u64, pub rax: u64, pub rcx: u64, pub rsp: u64, pub rip: u64, pub rflags: u64, } impl From<&sgx_cpu_context_t> for GpRegs { fn from(src: &sgx_cpu_context_t) -> Self { Self { r8: src.r8, r9: src.r9, r10: src.r10, r11: src.r11, r12: src.r12, r13: src.r13, r14: src.r14, r15: src.r15, rdi: src.rdi, rsi: src.rsi, rbp: src.rbp, rbx: src.rbx, rdx: src.rdx, rax: src.rax, rcx: src.rcx, rsp: src.rsp, rip: src.rip, rflags: src.rflags, } } }
true
d9272fe0ee2e4eb06d3f65f8aa5b66cd7332d701
Rust
Cazadorro/sfal
/src/erfc.rs
UTF-8
4,869
3.234375
3
[ "MIT" ]
permissive
/// Functions that approximate the erfc(x), the "Complementary Error Function". use super::erf; use super::consts; use std::f64; ///https://en.wikipedia.org/wiki/Error_function#Asymptotic_expansion pub fn divergent_series(x: f64, max_n: u64) -> f64 { let mut prod = 1.0; let mut sum = 1.0; for n in 1..max_n { if n & 1 == 1 { prod *= n as f64; } prod /= (2.0 * x * x); } (f64::exp(-(x * x)) / (x * f64::consts::PI.sqrt())) * sum } ///https://en.wikipedia.org/wiki/Error_function#Continued_fraction_expansion pub fn continued_fraction(x: f64, max_n: u64) -> f64 { let mut fraction = 1.0; for i in (1..=max_n).rev() { let ai = i as f64 / 2.0; if i & 1 == 1 { fraction = (x * x) + (ai as f64 / fraction); } else { fraction = 1.0 + (ai as f64 / fraction); } } (x / f64::consts::PI.sqrt()) * f64::exp(-(x * x)) / fraction } ///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations pub fn abramowitz_0(x: f64) -> f64 { let x_negative = x < 0.0; let x = if x_negative { -x } else { x }; let ai_array = [0.278393, 0.230389, 0.000972, 0.078108]; let mut denominator_sum = 1.0_f64; let mut x_prod = 1.0; for i in 0..ai_array.len() { x_prod *= x; denominator_sum += ai_array[i] * x_prod; } let result = (1.0 / denominator_sum.powi(4)); if x_negative { -result } else { result } } ///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations pub fn abramowitz_1(x: f64) -> f64 { let x_negative = x < 0.0; let x = if x_negative { -x } else { x }; let p = 0.47047; let t = 1.0/(1.0 + p*x); let ai_array = [0.3480242,-0.0958798,0.7478556]; let mut sum = 1.0; let mut t_prod = 1.0; for i in 0..ai_array.len() { t_prod *= t; sum += ai_array[i] * t_prod; } let result = (sum*f64::exp(-(x*x))); if x_negative { -result } else { result } } ///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations pub fn abramowitz_2(x: f64) -> f64 { let x_negative = x < 0.0; let x = if x_negative { -x } else { x }; let ai_array = [0.0705230784, 0.0422820123, 0.0092705272, 0.0001520143, 0.0002765672, 0.0000430638]; let mut denominator_sum = 1.0_f64; let mut x_prod = 1.0; for i in 0..ai_array.len() { x_prod *= x; denominator_sum += ai_array[i] * x_prod; } let result = (1.0 / denominator_sum.powi(16)); if x_negative { -result } else { result } } ///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations pub fn abramowitz_3(x: f64) -> f64 { let x_negative = x < 0.0; let x = if x_negative { -x } else { x }; let p = 0.3275911; let t = 1.0/(1.0 + p*x); let ai_array = [0.254829592,-0.284496736,1.421413741,-1.453152027,1.061405429]; let mut sum = 1.0; let mut t_prod = 1.0; for i in 0..ai_array.len() { t_prod *= t; sum += ai_array[i] * t_prod; } let result = (sum*f64::exp(-(x*x))); if x_negative { -result } else { result } } ///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations pub fn karagiannidis(x: f64) -> f64{ let x_negative = x < 0.0; let x = if x_negative { -x } else { x }; let a = 1.98; let b = 1.135; let result = ((1.0 - f64::exp(-a*x))*f64::exp(-(x*x)))/(b * f64::consts::PI.sqrt() * x); if x_negative { -result } else { result } } ///https://en.wikipedia.org/wiki/Error_function#Numerical_approximations pub fn sergei_pade(x:f64)-> f64{ 1.0 - erf::sergei_pade(x) } pub fn polynomial_9th(x:f64) -> f64{ 1.0 - erf::polynomial_9th(x) } ///Numerical Recipes third edition page 265. pub fn recipes_cheb(x : f64) -> f64{ let cheb_coef_array = [-1.3026537197817094, 6.4196979235649026e-1, 1.9476473204185836e-2,-9.561514786808631e-3,-9.46595344482036e-4, 3.66839497852761e-4,4.2523324806907e-5,-2.0278578112534e-5, -1.624290004647e-6,1.303655835580e-6,1.5626441722e-8,-8.5238095915e-8, 6.529054439e-9,5.059343495e-9,-9.91364156e-10,-2.27365122e-10, 9.6467911e-11, 2.394038e-12,-6.886027e-12,8.94487e-13, 3.13092e-13, -1.12708e-13,3.81e-16,7.106e-15,-1.523e-15,-9.4e-17,1.21e-16,-2.8e-17]; let mut d=0.0; let mut dd=0.0; let x_negative = x < 0.0; let x = if x_negative{ -x }else{ x }; let t = 2.0/(2.0+x); let ty = 4.0*t - 2.0; for j in (0..cheb_coef_array.len()).rev() { let tmp = d; d = ty*d - dd + cheb_coef_array[j as usize]; dd = tmp; } let result = t*f64::exp(-x*x + 0.5*(cheb_coef_array[0] + ty*d) - dd); if x_negative{ -result }else{ result } }
true
e95967df9ce5dd18e8ee73c489ce9ef120d27977
Rust
fuerstenau/gorrosion-gtp
/src/data/color.rs
UTF-8
778
2.859375
3
[]
no_license
use super::super::messages::WriteGTP; use super::*; use std::io; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Value { Black, White, } impl WriteGTP for Value { fn write_gtp(&self, f: &mut impl io::Write) -> io::Result<()> { match self { Value::Black => write!(f, "Black"), Value::White => write!(f, "White"), } } } singleton_type!(Color); impl HasType<Type> for Value { fn has_type(&self, _t: &Type) -> bool { true } } impl Data for Value { type Type = Type; fn parse<'a, I: Input<'a>>(i: I, _t: &Self::Type) -> IResult<I, Self> { #[rustfmt::skip] alt!(i, value!( Value::White, alt!(tag_no_case!("W") | tag_no_case!("white")) ) | value!( Value::Black, alt!(tag_no_case!("B") | tag_no_case!("black")) ) ) } }
true
f75ec2b2f15bd84d20f2a363894ec906bd7cecb0
Rust
skanev/playground
/advent-of-code/2021/day09/src/main.rs
UTF-8
1,989
3.328125
3
[]
no_license
use std::{collections::VecDeque, fs}; fn parse_input() -> Vec<Vec<u8>> { let text = fs::read_to_string("../inputs/09").unwrap(); let height = text.lines().count(); let width = text.lines().next().unwrap().len(); let mut result = vec![vec![9; width + 2]; height + 2]; for (i, line) in text.lines().enumerate() { for (j, byte) in line.bytes().enumerate() { result[i + 1][j + 1] = byte - b'0'; } } result } fn low_points(map: &Vec<Vec<u8>>) -> Vec<(usize, usize)> { let height = map.len(); let width = map[0].len(); let mut result = vec![]; for i in 1..(height - 2) { for j in 1..(width - 2) { if map[i][j] < map[i - 1][j] && map[i][j] < map[i + 1][j] && map[i][j] < map[i][j - 1] && map[i][j] < map[i][j + 1] { result.push((i, j)); } } } result } fn fill(map: &mut Vec<Vec<u8>>, point: (usize, usize)) -> usize { let mut left: VecDeque<(usize, usize)> = VecDeque::new(); let mut count = 0; left.push_back(point); while left.len() > 0 { let point = left.pop_front().unwrap(); if map[point.0][point.1] == 9 { continue; } map[point.0][point.1] = 9; count += 1; left.push_back((point.0 - 1, point.1)); left.push_back((point.0 + 1, point.1)); left.push_back((point.0, point.1 - 1)); left.push_back((point.0, point.1 + 1)); } count } fn main() { let mut map = parse_input(); let lows = low_points(&map); let first: usize = lows.iter().map(|&(x, y)| (map[x][y] as usize) + 1).sum(); let mut basins: Vec<usize> = vec![]; for point in lows { basins.push(fill(&mut map, point)); } basins.sort(); let second: usize = basins[basins.len() - 3..].iter().product(); println!("first = {}", first); println!("second = {}", second); }
true
9170d885608392e23cee3e89a0170fb7bf621d19
Rust
ArthurMatthys/Gomoku
/src/model/score_board.rs
UTF-8
2,434
2.875
3
[]
no_license
use super::super::render::board::SIZE_BOARD; #[derive(Clone, Copy)] pub struct ScoreBoard([[[(u8, Option<bool>, Option<bool>); 4]; SIZE_BOARD]; SIZE_BOARD]); impl ScoreBoard { /// Retrieve score_board[x][y][dir] pub fn get(&self, x: usize, y: usize, dir: usize) -> (u8, Option<bool>, Option<bool>) { self.0[x][y][dir] } /// Check and Retrieve score_board[x][y][dir] if possible pub fn get_check( &self, x: usize, y: usize, dir: usize, ) -> Option<(u8, Option<bool>, Option<bool>)> { self.0 .get(x) .map(|b| b.get(y).map(|c| c.get(dir))) .flatten() .flatten() .cloned() } /// Change value of score_board[x][y][dir] pub fn set( &mut self, x: usize, y: usize, dir: usize, score: (u8, Option<bool>, Option<bool>), ) -> () { self.0[x][y][dir] = score; } /// Retrieve score_board[x][y] pub fn get_arr(&self, x: usize, y: usize) -> [(u8, Option<bool>, Option<bool>); 4] { self.0[x][y] } pub fn reset(&mut self, x: usize, y: usize, dir: usize) -> () { self.0[x][y][dir] = (0, Some(false), Some(false)); } // Print score_board pub fn print(&self) -> () { self.0.iter().for_each(|x| { x.iter().for_each(|y| { y.iter().for_each(|el| print!("{:2}", el.0)); print!("||"); }); println!(); }) } } impl From<[[[(u8, Option<bool>, Option<bool>); 4]; SIZE_BOARD]; SIZE_BOARD]> for ScoreBoard { fn from(item: [[[(u8, Option<bool>, Option<bool>); 4]; SIZE_BOARD]; SIZE_BOARD]) -> Self { ScoreBoard(item) } } impl From<ScoreBoard> for [[[(u8, Option<bool>, Option<bool>); 4]; SIZE_BOARD]; SIZE_BOARD] { fn from(item: ScoreBoard) -> Self { item.0 } } impl PartialEq for ScoreBoard { fn eq(&self, other: &Self) -> bool { for x in 0..SIZE_BOARD { for y in 0..SIZE_BOARD { for dir in 0..4 { if self.0[x][y][dir].0 != other.0[x][y][dir].0 || self.0[x][y][dir].1 != other.0[x][y][dir].1 || self.0[x][y][dir].2 != other.0[x][y][dir].2 { return false; } } } } true } }
true
78e668f8d152738b18f2c4770faed77a5edf2d21
Rust
kerinin/email-rs
/src/rfc2822/quoted.rs
UTF-8
6,883
2.734375
3
[]
no_license
use bytes::{Bytes, ByteStr}; use chomp::*; use rfc2822::folding::*; use rfc2822::obsolete::*; use rfc2822::primitive::*; // quoted-pair = ("\" text) / obs-qp // Consumes & returns matches pub fn quoted_pair(i: Input<u8>) -> U8Result<u8> { parse!{i; or( |i| parse!{i; token(b'\\') >> text() }, obs_qp, )} } /* #[test] pub fn test_quoted_pair() { assert_eq!(parse_only(quoted_pair, "\\\n".as_bytes()), Ok("\n".as_bytes())); } */ // qtext = NO-WS-CTL / ; Non white space controls // // %d33 / ; The rest of the US-ASCII // %d35-91 / ; characters not including "\" // %d93-126 ; or the quote character const QTEXT: [bool; 256] = [ // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 false, true, true, true, true, true, true, true, true, false, false, true, true, false, true, true, true, true, true, true, // 0 - 19 true, true, true, true, true, true, true, true, true, true, true, true, false, true, false, true, true, true, true, true, // 20 - 39 true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // 40 - 59 true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // 60 - 79 true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, true, true, true, true, true, // 80 - 99 true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // 100 - 119 true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, // 120 - 139 false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 140 - 159 false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 160 - 179 false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 180 - 199 false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 200 - 219 false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 220 - 239 false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false // 240 - 256 ]; pub fn qtext(i: Input<u8>) -> U8Result<u8> { satisfy(i, |c| QTEXT[c as usize]) } // qcontent = qtext / quoted-pair pub fn qcontent(i: Input<u8>) -> U8Result<u8> { parse!{i; qtext() <|> quoted_pair() } } #[test] fn test_qcontent() { let i = b"G"; let msg = parse_only(qcontent, i); assert!(msg.is_ok()); assert_eq!(msg.unwrap(), b'G'); let i = b"\\\""; let msg = parse_only(qcontent, i); assert!(msg.is_ok()); assert_eq!(msg.unwrap(), b'\"'); } // quoted-string = [CFWS] // DQUOTE *([FWS] qcontent) [FWS] DQUOTE // [CFWS] // NOTE: in order to reduce allocations, this checks for runs of qtext // explicitly, so expanding things out: // quoted-string = [CFWS] DQUOTE *([FWS] qcontent) [FWS] DQUOTE [CFWS] // // substitute qcontent: // = [CFWS] DQUOTE *([FWS] (qtext / quoted-pair)) [FWS] DQUOTE [CFWS] // // associate many // = [CFWS] DQUOTE *([FWS] (1*qtext / quoted-pair)) [FWS] DQUOTE [CFWS] // pub fn quoted_string(i: Input<u8>) -> U8Result<Bytes> { option(i, cfws, Bytes::empty()).bind(|i, ws1| { dquote(i).then(|i| { let a = |i| { option(i, fws, Bytes::empty()).bind(|i, ws2| { or(i, |i| matched_by(i, |i| skip_many1(i, qtext)).map(|(v, _)| Bytes::from_slice(v)), |i| quoted_pair(i).map(|c| Bytes::from_slice(&[c][..])), ).bind(|i, cs| { i.ret(ws2.concat(&cs)) }) }) }; many(i, a).bind(|i, rs: Vec<Bytes>| { option(i, fws, Bytes::empty()).bind(|i, ws3| { dquote(i).then(|i| { option(i, cfws, Bytes::empty()).bind(|i, ws4| { let bs = rs.into_iter().fold(ws1, |acc, r| acc.concat(&r)); i.ret(bs.concat(&ws3).concat(&ws4)) }) }) }) }) }) }) } #[test] fn test_quoted_string() { let i = b"\"Giant; \\\"Big\\\" Box\""; let msg = parse_only(quoted_string, i); assert!(msg.is_ok()); assert_eq!(msg.unwrap(), Bytes::from_slice(b"Giant; \"Big\" Box")); } pub fn quoted_string_not<P>(i: Input<u8>, mut p: P) -> U8Result<Bytes> where P: FnMut(u8) -> bool, { option(i, cfws, Bytes::empty()).bind(|i, ws1| { dquote(i).then(|i| { many1(i, |i| { option(i, fws, Bytes::empty()).bind(|i, ws2| { matched_by(i, |i| { peek_next(i).bind(|i, next| { if p(next) { i.err(Error::Unexpected) } else { qcontent(i) } }) }).bind(|i, (v, _)| { i.ret(ws2.concat(&Bytes::from_slice(v))) }) }) }).bind(|i, rs: Vec<Bytes>| { option(i, fws, Bytes::empty()).bind(|i, ws3| { dquote(i).then(|i| { option(i, cfws, Bytes::empty()).bind(|i, ws4| { let bs = rs.into_iter().fold(ws1, |acc, r| acc.concat(&r)); i.ret(bs.concat(&ws3).concat(&ws4)) }) }) }) }) }) }) } #[test] fn test_quoted_string_not() { let i = b"\"jdoe\""; let msg = parse_only(|i| quoted_string_not(i, |c| c == b'@'), i); assert_eq!(msg, Ok(Bytes::from_slice(b"jdoe"))); let i = b"\"jdoe\"@example.com"; let msg = parse_only(|i| quoted_string_not(i, |c| c == b'@'), i); assert_eq!(msg, Ok(Bytes::from_slice(b"jdoe"))); }
true
50a892d11aded402f16b56046793a5e33e989d75
Rust
iCodeIN/rust-advent
/y2020/ex04/src/validators.rs
UTF-8
2,842
3.34375
3
[ "MIT" ]
permissive
use regex::Regex; use std::ops::RangeInclusive; pub trait Validator { fn validate(&self, value: &str) -> bool; } pub struct U16RangeValidator { range: RangeInclusive<u16>, } impl U16RangeValidator { pub fn new(range: RangeInclusive<u16>) -> Self { U16RangeValidator { range } } } impl Validator for U16RangeValidator { fn validate(&self, value: &str) -> bool { if let Ok(year) = value.parse::<u16>() { return self.range.contains(&year); } false } } pub struct RegexValidator { regex: Regex, } impl RegexValidator { pub fn new(regex: Regex) -> Self { RegexValidator { regex } } } impl Validator for RegexValidator { fn validate(&self, value: &str) -> bool { self.regex.is_match(value) } } // byr (Birth Year) - four digits; at least 1920 and at most 2002. pub fn create_byr_validator() -> U16RangeValidator { U16RangeValidator::new(1920..=2002) } // iyr (Issue Year) - four digits; at least 2010 and at most 2020. pub fn create_iyr_validator() -> U16RangeValidator { U16RangeValidator::new(2010..=2020) } // eyr (Expiration Year) - four digits; at least 2020 and at most 2030. pub fn create_eyr_validator() -> U16RangeValidator { U16RangeValidator::new(2020..=2030) } // hgt (Height) - a number followed by either cm or in. // If cm, the number must be at least 150 and at most 193. // If in, the number must be at least 59 and at most 76. pub struct HgtValidator { regex: Regex, } impl HgtValidator { pub fn new() -> Self { let regex = Regex::new(r"^(\d+)(in|cm)$").unwrap(); HgtValidator { regex } } } impl Validator for HgtValidator { fn validate(&self, value: &str) -> bool { if let Some(captures) = self.regex.captures(value) { let unit = captures.get(2).unwrap().as_str(); if let Ok(num) = captures.get(1).unwrap().as_str().parse::<u16>() { return (unit == "in" && (59..=76).contains(&num)) || (unit == "cm" && (150..=193).contains(&num)); } } false } } pub fn create_hgt_validator() -> HgtValidator { HgtValidator::new() } // hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f. pub fn create_hcl_validator() -> RegexValidator { let regex = Regex::new(r"^#[0-9a-fA-F]{6}$").unwrap(); RegexValidator::new(regex) } // ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth. pub fn create_ecl_validator() -> RegexValidator { let regex = Regex::new(r"^(amb|blu|brn|gry|grn|hzl|oth)$").unwrap(); RegexValidator::new(regex) } // pid (Passport ID) - a nine-digit number, including leading zeroes. pub fn create_pid_validator() -> RegexValidator { let regex = Regex::new(r"^\d{9}$").unwrap(); RegexValidator::new(regex) }
true
158bc4f31dcdf8670799376e3b8855835b601485
Rust
open-telemetry/opentelemetry-rust
/opentelemetry-sdk/src/testing/trace/in_memory_exporter.rs
UTF-8
4,403
2.734375
3
[ "Apache-2.0" ]
permissive
use crate::export::trace::{ExportResult, SpanData, SpanExporter}; use futures_util::future::BoxFuture; use opentelemetry::trace::{TraceError, TraceResult}; use std::sync::{Arc, Mutex}; /// An in-memory span exporter that stores span data in memory. /// /// This exporter is useful for testing and debugging purposes. It stores /// metric data in a `Vec<SpanData>`. Metrics can be retrieved /// using the `get_finished_spans` method. /// # Example /// ``` ///# use opentelemetry::trace::{SpanKind, TraceContextExt}; ///# use opentelemetry::{global, trace::Tracer, Context}; ///# use opentelemetry_sdk::propagation::TraceContextPropagator; ///# use opentelemetry_sdk::runtime; ///# use opentelemetry_sdk::testing::trace::InMemorySpanExporterBuilder; ///# use opentelemetry_sdk::trace::{BatchSpanProcessor, TracerProvider}; /// ///# #[tokio::main] ///# async fn main() { /// let exporter = InMemorySpanExporterBuilder::new().build(); /// let provider = TracerProvider::builder() /// .with_span_processor(BatchSpanProcessor::builder(exporter.clone(), runtime::Tokio).build()) /// .build(); /// /// global::set_tracer_provider(provider.clone()); /// /// let tracer = global::tracer("example/in_memory_exporter"); /// let span = tracer /// .span_builder("say hello") /// .with_kind(SpanKind::Server) /// .start(&tracer); /// /// let cx = Context::current_with_span(span); /// cx.span().add_event("handling this...", Vec::new()); /// cx.span().end(); /// /// let results = provider.force_flush(); /// for result in results { /// if let Err(e) = result { /// println!("{:?}", e) /// } /// } /// let spans = exporter.get_finished_spans().unwrap(); /// for span in spans { /// println!("{:?}", span) /// } ///# } /// ``` #[derive(Clone, Debug)] pub struct InMemorySpanExporter { spans: Arc<Mutex<Vec<SpanData>>>, } impl Default for InMemorySpanExporter { fn default() -> Self { InMemorySpanExporterBuilder::new().build() } } /// Builder for [`InMemorySpanExporter`]. /// # Example /// ``` ///# use opentelemetry_sdk::testing::trace::InMemorySpanExporterBuilder; /// /// let exporter = InMemorySpanExporterBuilder::new().build(); /// ``` #[derive(Clone, Debug)] pub struct InMemorySpanExporterBuilder {} impl Default for InMemorySpanExporterBuilder { fn default() -> Self { Self::new() } } impl InMemorySpanExporterBuilder { /// Creates a new instance of the `InMemorySpanExporterBuilder`. pub fn new() -> Self { Self {} } /// Creates a new instance of the `InMemorySpanExporter`. pub fn build(&self) -> InMemorySpanExporter { InMemorySpanExporter { spans: Arc::new(Mutex::new(Vec::new())), } } } impl InMemorySpanExporter { /// Returns the finished span as a vector of `SpanData`. /// /// # Errors /// /// Returns a `TraceError` if the internal lock cannot be acquired. /// /// # Example /// /// ``` /// # use opentelemetry_sdk::testing::trace::InMemorySpanExporter; /// /// let exporter = InMemorySpanExporter::default(); /// let finished_spans = exporter.get_finished_spans().unwrap(); /// ``` pub fn get_finished_spans(&self) -> TraceResult<Vec<SpanData>> { self.spans .lock() .map(|spans_guard| spans_guard.iter().cloned().collect()) .map_err(TraceError::from) } /// Clears the internal storage of finished spans. /// /// # Example /// /// ``` /// # use opentelemetry_sdk::testing::trace::InMemorySpanExporter; /// /// let exporter = InMemorySpanExporter::default(); /// exporter.reset(); /// ``` pub fn reset(&self) { let _ = self.spans.lock().map(|mut spans_guard| spans_guard.clear()); } } impl SpanExporter for InMemorySpanExporter { fn export(&mut self, batch: Vec<SpanData>) -> BoxFuture<'static, ExportResult> { if let Err(err) = self .spans .lock() .map(|mut spans_guard| spans_guard.append(&mut batch.clone())) .map_err(TraceError::from) { return Box::pin(std::future::ready(Err(Into::into(err)))); } Box::pin(std::future::ready(Ok(()))) } fn shutdown(&mut self) { self.reset() } }
true
2006d078ad47d36d15c36ed32964ca4e48ba983a
Rust
Jackywathy/mipsy
/crates/mipsy_web/src/components/pagebackground.rs
UTF-8
800
2.640625
3
[]
no_license
use yew::prelude::*; use yew::{Children, Properties}; #[derive(Properties, Clone)] pub struct Props { #[prop_or_default] pub children: Children, } pub struct PageBackground { pub props: Props, } impl Component for PageBackground { type Message = (); type Properties = Props; fn create(props: Self::Properties, _: ComponentLink<Self>) -> Self { PageBackground { props } } fn change(&mut self, props: Self::Properties) -> ShouldRender { self.props = props; true } fn update(&mut self, _: Self::Message) -> ShouldRender { true } fn view(&self) -> Html { html! { <div class="min-h-screen py-2 bg-th-primary"> { for self.props.children.iter() } </div> } } }
true
6f26f1b91aa0aa6fbc61955934f49b2b711a4f1e
Rust
cjoh88/Zombie
/src/editor/input.rs
UTF-8
2,246
2.921875
3
[]
no_license
use sfml::window::{Key}; use sfml::window::{event}; use sfml::window::MouseButton; use sfml::graphics::{RenderWindow}; use sfml::system::{Vector2i, Vector2f}; use sfml::graphics::RenderTarget; use editor::world::World; pub struct EditorInputHandler { dummy: i32 } impl EditorInputHandler { pub fn new() -> Self { EditorInputHandler { dummy: 0, } } pub fn handle_input(&mut self, world: &mut World, window: &mut RenderWindow) { for event in window.events() { match event { event::Closed => window.close(), event::KeyPressed{code, ..} => self.handle_key_pressed(world, window, code), //world, window, code event::KeyReleased{code, ..} => self.handle_key_released(world, window, code), //world, window, code event::MouseButtonPressed{button, x, y} => self.handle_mouse_pressed(world, window, button, x, y), //world, window, button, x, y _ => (), } } } fn handle_key_pressed(&mut self, world: &mut World, window: &mut RenderWindow, code: Key) { match code { Key::Escape => window.close(), Key::Right | Key::D => world.get_mut_camera().move_right(), Key::Left | Key::A => world.get_mut_camera().move_left(), Key::Up | Key::W => world.get_mut_camera().move_up(), Key::Down | Key::S => world.get_mut_camera().move_down(), _ => () } } fn handle_key_released(&mut self, world: &mut World, window: &mut RenderWindow, code: Key) { match code { Key::Right | Key::Left | Key::D | Key::A => world.get_mut_camera().stop_horizontal(), Key::Up | Key::Down | Key::W | Key::S => world.get_mut_camera().stop_vertical(), Key::Add => world.get_mut_camera().zoom(0.5), Key::Subtract => world.get_mut_camera().zoom(2.0), _ => () } } fn handle_mouse_pressed(&mut self, editor: &mut World, window: &mut RenderWindow, code: MouseButton, x: i32, y: i32) { /*let v = Vector2i::new(x,y); let v2: Vector2f = window.map_pixel_to_coords(&v, &editor.get_view()); let v3 = screen_to_map(v2); println!("Mouse({}, {})", v3.x, v3.y);*/ } }
true
9cfe05532aedfe26141eba73dd1bd0d2ee01e656
Rust
rust-lang/rust-analyzer
/crates/ide-diagnostics/src/handlers/unresolved_macro_call.rs
UTF-8
1,607
2.796875
3
[ "Apache-2.0", "MIT" ]
permissive
use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext}; // Diagnostic: unresolved-macro-call // // This diagnostic is triggered if rust-analyzer is unable to resolve the path // to a macro in a macro invocation. pub(crate) fn unresolved_macro_call( ctx: &DiagnosticsContext<'_>, d: &hir::UnresolvedMacroCall, ) -> Diagnostic { // Use more accurate position if available. let display_range = ctx.resolve_precise_location(&d.macro_call, d.precise_location); let bang = if d.is_bang { "!" } else { "" }; Diagnostic::new( DiagnosticCode::RustcHardError("unresolved-macro-call"), format!("unresolved macro `{}{bang}`", d.path.display(ctx.sema.db)), display_range, ) .experimental() } #[cfg(test)] mod tests { use crate::tests::check_diagnostics; #[test] fn unresolved_macro_diag() { check_diagnostics( r#" fn f() { m!(); } //^ error: unresolved macro `m!` "#, ); } #[test] fn test_unresolved_macro_range() { check_diagnostics( r#" foo::bar!(92); //^^^ error: unresolved macro `foo::bar!` "#, ); } #[test] fn unresolved_legacy_scope_macro() { check_diagnostics( r#" macro_rules! m { () => {} } m!(); m2!(); //^^ error: unresolved macro `m2!` "#, ); } #[test] fn unresolved_module_scope_macro() { check_diagnostics( r#" mod mac { #[macro_export] macro_rules! m { () => {} } } self::m!(); self::m2!(); //^^ error: unresolved macro `self::m2!` "#, ); } }
true
2d3c47f93338cb47dfcdef8c16ab9c8fa0fea7bf
Rust
zmbush/cargo
/src/cargo/core/resolver/mod.rs
UTF-8
22,960
2.546875
3
[ "GCC-exception-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "OpenSSL", "Zlib", "MIT", "curl", "GPL-2.0-only", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "Unlicense", "LGPL-2.1-only", "Apache-2.0" ]
permissive
use std::cell::RefCell; use std::collections::HashSet; use std::collections::hash_map::HashMap; use std::fmt; use std::rc::Rc; use semver; use core::{PackageId, Registry, SourceId, Summary, Dependency}; use core::PackageIdSpec; use util::{CargoResult, Graph, human, ChainError, CargoError}; use util::profile; use util::graph::{Nodes, Edges}; pub use self::encode::{EncodableResolve, EncodableDependency, EncodablePackageId}; pub use self::encode::Metadata; mod encode; /// Represents a fully resolved package dependency graph. Each node in the graph /// is a package and edges represent dependencies between packages. /// /// Each instance of `Resolve` also understands the full set of features used /// for each package as well as what the root package is. #[derive(PartialEq, Eq, Clone)] pub struct Resolve { graph: Graph<PackageId>, features: HashMap<PackageId, HashSet<String>>, root: PackageId, metadata: Option<Metadata>, } #[derive(Clone, Copy)] pub enum Method<'a> { Everything, Required{ dev_deps: bool, features: &'a [String], uses_default_features: bool, target_platform: Option<&'a str>}, } impl Resolve { fn new(root: PackageId) -> Resolve { let mut g = Graph::new(); g.add(root.clone(), &[]); Resolve { graph: g, root: root, features: HashMap::new(), metadata: None } } pub fn copy_metadata(&mut self, other: &Resolve) { self.metadata = other.metadata.clone(); } pub fn iter(&self) -> Nodes<PackageId> { self.graph.iter() } pub fn root(&self) -> &PackageId { &self.root } pub fn deps(&self, pkg: &PackageId) -> Option<Edges<PackageId>> { self.graph.edges(pkg) } pub fn query(&self, spec: &str) -> CargoResult<&PackageId> { let spec = try!(PackageIdSpec::parse(spec).chain_error(|| { human(format!("invalid package id specification: `{}`", spec)) })); let mut ids = self.iter().filter(|p| spec.matches(*p)); let ret = match ids.next() { Some(id) => id, None => return Err(human(format!("package id specification `{}` \ matched no packages", spec))), }; return match ids.next() { Some(other) => { let mut msg = format!("There are multiple `{}` packages in \ your project, and the specification \ `{}` is ambiguous.\n\ Please re-run this command \ with `-p <spec>` where `<spec>` is one \ of the following:", spec.name(), spec); let mut vec = vec![ret, other]; vec.extend(ids); minimize(&mut msg, vec, &spec); Err(human(msg)) } None => Ok(ret) }; fn minimize(msg: &mut String, ids: Vec<&PackageId>, spec: &PackageIdSpec) { let mut version_cnt = HashMap::new(); for id in ids.iter() { *version_cnt.entry(id.version()).or_insert(0) += 1; } for id in ids.iter() { if version_cnt[id.version()] == 1 { msg.push_str(&format!("\n {}:{}", spec.name(), id.version())); } else { msg.push_str(&format!("\n {}", PackageIdSpec::from_package_id(*id))); } } } } pub fn features(&self, pkg: &PackageId) -> Option<&HashSet<String>> { self.features.get(pkg) } } impl fmt::Debug for Resolve { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "graph: {:?}\n", self.graph)); try!(write!(fmt, "\nfeatures: {{\n")); for (pkg, features) in &self.features { try!(write!(fmt, " {}: {:?}\n", pkg, features)); } write!(fmt, "}}") } } #[derive(Clone)] struct Context { activations: HashMap<(String, SourceId), Vec<Rc<Summary>>>, resolve: Resolve, visited: Rc<RefCell<HashSet<PackageId>>>, } /// Builds the list of all packages required to build the first argument. pub fn resolve(summary: &Summary, method: Method, registry: &mut Registry) -> CargoResult<Resolve> { trace!("resolve; summary={}", summary.package_id()); let summary = Rc::new(summary.clone()); let cx = Box::new(Context { resolve: Resolve::new(summary.package_id().clone()), activations: HashMap::new(), visited: Rc::new(RefCell::new(HashSet::new())), }); let _p = profile::start(format!("resolving: {}", summary.package_id())); match try!(activate(cx, registry, &summary, method)) { Ok(cx) => { debug!("resolved: {:?}", cx.resolve); Ok(cx.resolve) } Err(e) => Err(e), } } fn activate(mut cx: Box<Context>, registry: &mut Registry, parent: &Rc<Summary>, method: Method) -> CargoResult<CargoResult<Box<Context>>> { // Dependency graphs are required to be a DAG, so we keep a set of // packages we're visiting and bail if we hit a dupe. let id = parent.package_id(); if !cx.visited.borrow_mut().insert(id.clone()) { return Err(human(format!("cyclic package dependency: package `{}` \ depends on itself", id))) } // If we're already activated, then that was easy! if flag_activated(&mut *cx, parent, &method) { cx.visited.borrow_mut().remove(id); return Ok(Ok(cx)) } debug!("activating {}", parent.package_id()); // Extracting the platform request. let platform = match method { Method::Required{target_platform: platform, ..} => platform, Method::Everything => None, }; // First, figure out our set of dependencies based on the requsted set of // features. This also calculates what features we're going to enable for // our own dependencies. let deps = try!(resolve_features(&mut cx, parent, method)); // Next, transform all dependencies into a list of possible candidates which // can satisfy that dependency. let mut deps = try!(deps.into_iter().map(|(_dep_name, (dep, features))| { let mut candidates = try!(registry.query(dep)); // When we attempt versions for a package, we'll want to start at the // maximum version and work our way down. candidates.sort_by(|a, b| { b.version().cmp(a.version()) }); let candidates = candidates.into_iter().map(Rc::new).collect::<Vec<_>>(); Ok((dep, candidates, features)) }).collect::<CargoResult<Vec<_>>>()); // When we recurse, attempt to resolve dependencies with fewer candidates // before recursing on dependencies with more candidates. This way if the // dependency with only one candidate can't be resolved we don't have to do // a bunch of work before we figure that out. deps.sort_by(|&(_, ref a, _), &(_, ref b, _)| { a.len().cmp(&b.len()) }); // Workaround compilation error: `deps` does not live long enough let platform = platform.map(|s| &*s); Ok(match try!(activate_deps(cx, registry, parent, platform, &deps, 0)) { Ok(cx) => { cx.visited.borrow_mut().remove(parent.package_id()); Ok(cx) } Err(e) => Err(e), }) } // Activate this summary by inserting it into our list of known activations. // // Returns if this summary with the given method is already activated. fn flag_activated(cx: &mut Context, summary: &Rc<Summary>, method: &Method) -> bool { let id = summary.package_id(); let key = (id.name().to_string(), id.source_id().clone()); let prev = cx.activations.entry(key).or_insert(Vec::new()); if !prev.iter().any(|c| c == summary) { cx.resolve.graph.add(id.clone(), &[]); prev.push(summary.clone()); return false } debug!("checking if {} is already activated", summary.package_id()); let (features, use_default) = match *method { Method::Required { features, uses_default_features, .. } => { (features, uses_default_features) } Method::Everything => return false, }; let has_default_feature = summary.features().contains_key("default"); match cx.resolve.features(id) { Some(prev) => { features.iter().all(|f| prev.contains(f)) && (!use_default || prev.contains("default") || !has_default_feature) } None => features.len() == 0 && (!use_default || !has_default_feature) } } fn activate_deps<'a>(cx: Box<Context>, registry: &mut Registry, parent: &Summary, platform: Option<&'a str>, deps: &'a [(&Dependency, Vec<Rc<Summary>>, Vec<String>)], cur: usize) -> CargoResult<CargoResult<Box<Context>>> { if cur == deps.len() { return Ok(Ok(cx)) } let (dep, ref candidates, ref features) = deps[cur]; let method = Method::Required{ dev_deps: false, features: &features, uses_default_features: dep.uses_default_features(), target_platform: platform}; let key = (dep.name().to_string(), dep.source_id().clone()); let prev_active = cx.activations.get(&key) .map(|v| &v[..]).unwrap_or(&[]); trace!("{}[{}]>{} {} candidates", parent.name(), cur, dep.name(), candidates.len()); trace!("{}[{}]>{} {} prev activations", parent.name(), cur, dep.name(), prev_active.len()); // Filter the set of candidates based on the previously activated // versions for this dependency. We can actually use a version if it // precisely matches an activated version or if it is otherwise // incompatible with all other activated versions. Note that we define // "compatible" here in terms of the semver sense where if the left-most // nonzero digit is the same they're considered compatible. let my_candidates = candidates.iter().filter(|&b| { prev_active.iter().any(|a| a == b) || prev_active.iter().all(|a| { !compatible(a.version(), b.version()) }) }); // Alright, for each candidate that's gotten this far, it meets the // following requirements: // // 1. The version matches the dependency requirement listed for this // package // 2. There are no activated versions for this package which are // semver-compatible, or there's an activated version which is // precisely equal to `candidate`. // // This means that we're going to attempt to activate each candidate in // turn. We could possibly fail to activate each candidate, so we try // each one in turn. let mut last_err = None; for candidate in my_candidates { trace!("{}[{}]>{} trying {}", parent.name(), cur, dep.name(), candidate.version()); let mut my_cx = cx.clone(); my_cx.resolve.graph.link(parent.package_id().clone(), candidate.package_id().clone()); // If we hit an intransitive dependency then clear out the visitation // list as we can't induce a cycle through transitive dependencies. if !dep.is_transitive() { my_cx.visited.borrow_mut().clear(); } let my_cx = match try!(activate(my_cx, registry, candidate, method)) { Ok(cx) => cx, Err(e) => { last_err = Some(e); continue } }; match try!(activate_deps(my_cx, registry, parent, platform, deps, cur + 1)) { Ok(cx) => return Ok(Ok(cx)), Err(e) => { last_err = Some(e); } } } trace!("{}[{}]>{} -- {:?}", parent.name(), cur, dep.name(), last_err); // Oh well, we couldn't activate any of the candidates, so we just can't // activate this dependency at all Ok(activation_error(&cx, registry, last_err, parent, dep, prev_active, &candidates)) } fn activation_error(cx: &Context, registry: &mut Registry, err: Option<Box<CargoError>>, parent: &Summary, dep: &Dependency, prev_active: &[Rc<Summary>], candidates: &[Rc<Summary>]) -> CargoResult<Box<Context>> { match err { Some(e) => return Err(e), None => {} } if candidates.len() > 0 { let mut msg = format!("failed to select a version for `{}` \ (required by `{}`):\n\ all possible versions conflict with \ previously selected versions of `{}`", dep.name(), parent.name(), dep.name()); 'outer: for v in prev_active.iter() { for node in cx.resolve.graph.iter() { let edges = match cx.resolve.graph.edges(node) { Some(edges) => edges, None => continue, }; for edge in edges { if edge != v.package_id() { continue } msg.push_str(&format!("\n version {} in use by {}", v.version(), edge)); continue 'outer; } } msg.push_str(&format!("\n version {} in use by ??", v.version())); } msg.push_str(&format!("\n possible versions to select: {}", candidates.iter() .map(|v| v.version()) .map(|v| v.to_string()) .collect::<Vec<_>>() .connect(", "))); return Err(human(msg)) } // Once we're all the way down here, we're definitely lost in the // weeds! We didn't actually use any candidates above, so we need to // give an error message that nothing was found. // // Note that we re-query the registry with a new dependency that // allows any version so we can give some nicer error reporting // which indicates a few versions that were actually found. let msg = format!("no matching package named `{}` found \ (required by `{}`)\n\ location searched: {}\n\ version required: {}", dep.name(), parent.name(), dep.source_id(), dep.version_req()); let mut msg = msg; let all_req = semver::VersionReq::parse("*").unwrap(); let new_dep = dep.clone().set_version_req(all_req); let mut candidates = try!(registry.query(&new_dep)); candidates.sort_by(|a, b| { b.version().cmp(a.version()) }); if candidates.len() > 0 { msg.push_str("\nversions found: "); for (i, c) in candidates.iter().take(3).enumerate() { if i != 0 { msg.push_str(", "); } msg.push_str(&c.version().to_string()); } if candidates.len() > 3 { msg.push_str(", ..."); } } // If we have a path dependency with a locked version, then this may // indicate that we updated a sub-package and forgot to run `cargo // update`. In this case try to print a helpful error! if dep.source_id().is_path() && dep.version_req().to_string().starts_with("=") && candidates.len() > 0 { msg.push_str("\nconsider running `cargo update` to update \ a path dependency's locked version"); } Err(human(msg)) } // Returns if `a` and `b` are compatible in the semver sense. This is a // commutative operation. // // Versions `a` and `b` are compatible if their left-most nonzero digit is the // same. fn compatible(a: &semver::Version, b: &semver::Version) -> bool { if a.major != b.major { return false } if a.major != 0 { return true } if a.minor != b.minor { return false } if a.minor != 0 { return true } a.patch == b.patch } fn resolve_features<'a>(cx: &mut Context, parent: &'a Summary, method: Method) -> CargoResult<HashMap<&'a str, (&'a Dependency, Vec<String>)>> { let dev_deps = match method { Method::Everything => true, Method::Required { dev_deps, .. } => dev_deps, }; // First, filter by dev-dependencies let deps = parent.dependencies(); let deps = deps.iter().filter(|d| d.is_transitive() || dev_deps); // Second, ignoring dependencies that should not be compiled for this platform let deps = deps.filter(|d| { match method { Method::Required{target_platform: Some(ref platform), ..} => { d.is_active_for_platform(platform) }, _ => true } }); let (mut feature_deps, used_features) = try!(build_features(parent, method)); let mut ret = HashMap::new(); // Next, sanitize all requested features by whitelisting all the requested // features that correspond to optional dependencies for dep in deps { // weed out optional dependencies, but not those required if dep.is_optional() && !feature_deps.contains_key(dep.name()) { continue } let mut base = feature_deps.remove(dep.name()).unwrap_or(vec![]); for feature in dep.features().iter() { base.push(feature.clone()); if feature.contains("/") { return Err(human(format!("features in dependencies \ cannot enable features in \ other dependencies: `{}`", feature))); } } ret.insert(dep.name(), (dep, base)); } // All features can only point to optional dependencies, in which case they // should have all been weeded out by the above iteration. Any remaining // features are bugs in that the package does not actually have those // features. if feature_deps.len() > 0 { let unknown = feature_deps.keys().map(|s| &s[..]) .collect::<Vec<&str>>(); if unknown.len() > 0 { let features = unknown.connect(", "); return Err(human(format!("Package `{}` does not have these features: \ `{}`", parent.package_id(), features))) } } // Record what list of features is active for this package. if used_features.len() > 0 { let pkgid = parent.package_id(); cx.resolve.features.entry(pkgid.clone()) .or_insert(HashSet::new()) .extend(used_features); } Ok(ret) } // Returns a pair of (feature dependencies, all used features) // // The feature dependencies map is a mapping of package name to list of features // enabled. Each package should be enabled, and each package should have the // specified set of features enabled. // // The all used features set is the set of features which this local package had // enabled, which is later used when compiling to instruct the code what // features were enabled. fn build_features(s: &Summary, method: Method) -> CargoResult<(HashMap<String, Vec<String>>, HashSet<String>)> { let mut deps = HashMap::new(); let mut used = HashSet::new(); let mut visited = HashSet::new(); match method { Method::Everything => { for key in s.features().keys() { try!(add_feature(s, key, &mut deps, &mut used, &mut visited)); } for dep in s.dependencies().iter().filter(|d| d.is_optional()) { try!(add_feature(s, dep.name(), &mut deps, &mut used, &mut visited)); } } Method::Required{features: requested_features, ..} => { for feat in requested_features.iter() { try!(add_feature(s, feat, &mut deps, &mut used, &mut visited)); } } } match method { Method::Everything | Method::Required { uses_default_features: true, .. } => { if s.features().get("default").is_some() { try!(add_feature(s, "default", &mut deps, &mut used, &mut visited)); } } Method::Required { uses_default_features: false, .. } => {} } return Ok((deps, used)); fn add_feature(s: &Summary, feat: &str, deps: &mut HashMap<String, Vec<String>>, used: &mut HashSet<String>, visited: &mut HashSet<String>) -> CargoResult<()> { if feat.is_empty() { return Ok(()) } // If this feature is of the form `foo/bar`, then we just lookup package // `foo` and enable its feature `bar`. Otherwise this feature is of the // form `foo` and we need to recurse to enable the feature `foo` for our // own package, which may end up enabling more features or just enabling // a dependency. let mut parts = feat.splitn(2, '/'); let feat_or_package = parts.next().unwrap(); match parts.next() { Some(feat) => { let package = feat_or_package; deps.entry(package.to_string()) .or_insert(Vec::new()) .push(feat.to_string()); } None => { let feat = feat_or_package; if !visited.insert(feat.to_string()) { return Err(human(format!("Cyclic feature dependency: \ feature `{}` depends on itself", feat))) } used.insert(feat.to_string()); match s.features().get(feat) { Some(recursive) => { for f in recursive { try!(add_feature(s, f, deps, used, visited)); } } None => { deps.entry(feat.to_string()).or_insert(Vec::new()); } } visited.remove(&feat.to_string()); } } Ok(()) } }
true
1b4b1f4dd67bdc635d7c5d9cf5b1e7eb4b3d0c49
Rust
superhawk610/too-many-lists
/src/first_improved.rs
UTF-8
1,590
3.984375
4
[]
no_license
/// some easy improvements over `first` /// /// 1) change `Link` to simply alias `Option<Box<Node>>` /// 2) substitute `std::mem::replace(x, None)` with `x.take()` (yay, options!) /// 3) substitute `match option { None => None, Some(x) => Some(y) }` with `option.map(|x| y)` pub struct List { head: Link, } struct Node { elem: i32, next: Link, } type Link = Option<Box<Node>>; impl List { pub fn new() -> Self { List { head: None } } pub fn push(&mut self, elem: i32) { let new_node = Box::new(Node { elem: elem, next: self.head.take(), }); self.head = Some(new_node); } pub fn pop(&mut self) -> Option<i32> { self.pop_node().map(|node| node.elem) } fn pop_node(&mut self) -> Link { self.head.take().map(|mut node| { self.head = node.next.take(); node }) } } impl Drop for List { fn drop(&mut self) { while let Some(_) = self.pop_node() {} } } #[cfg(test)] mod test { use super::*; #[test] fn basics() { let mut list = List::new(); list.push(1); list.push(2); list.push(3); // normal removal... assert_eq!(list.pop(), Some(3)); assert_eq!(list.pop(), Some(2)); list.push(4); list.push(5); // some more normal removal... assert_eq!(list.pop(), Some(5)); assert_eq!(list.pop(), Some(4)); // and exhaustion... assert_eq!(list.pop(), Some(1)); assert_eq!(list.pop(), None); } }
true
c5dcb378d3f65c5222879e2c91b862b6baf218aa
Rust
steveklabnik/clog
/src/main.rs
UTF-8
2,413
2.59375
3
[ "MIT" ]
permissive
#![crate_name = "clog"] #![comment = "A conventional changelog generator"] #![license = "MIT"] #![feature(macro_rules, phase)] extern crate regex; #[phase(plugin)] extern crate regex_macros; extern crate serialize; #[phase(plugin)] extern crate docopt_macros; extern crate docopt; extern crate time; use git::{ LogReaderConfig }; use log_writer::{ LogWriter, LogWriterOptions }; use std::io::{File, Open, Write}; use docopt::FlagParser; mod common; mod git; mod log_writer; mod section_builder; docopt!(Args, "clog Usage: clog [--repository=<link> --setversion=<version> --subtitle=<subtitle> --from=<from> --to=<to> --from-latest-tag] Options: -h --help Show this screen. --version Show version -r --repository=<link> e.g https://github.com/thoughtram/clog --setversion=<version> e.g. 0.1.0 --subtitle=<subtitle> e.g. crazy-release-name --from=<from> e.g. 12a8546 --to=<to> e.g. 8057684 --from-latest-tag uses the latest tag as starting point. Ignores other --from parameter") fn main () { let start_nsec = ::time::get_time().nsec; let args: Args = FlagParser::parse().unwrap_or_else(|e| e.exit()); let log_reader_config = LogReaderConfig { grep: "^feat|^fix|BREAKING'".to_string(), format: "%H%n%s%n%b%n==END==".to_string(), from: if args.flag_from_latest_tag { ::git::get_latest_tag() } else { args.flag_from }, to: args.flag_to }; let commits = ::git::get_log_entries(log_reader_config); let sections = ::section_builder::build_sections(commits.clone()); let contents = match File::open(&Path::new("changelog.md")).read_to_string() { Ok(content) => content, Err(_) => "".to_string() }; let mut file = File::open_mode(&Path::new("changelog.md"), Open, Write).ok().unwrap(); let mut writer = LogWriter::new(&mut file, LogWriterOptions { repository_link: args.flag_repository, version: args.flag_setversion, subtitle: args.flag_subtitle }); writer.write_header(); writer.write_section("Bug Fixes", &sections.fixes); writer.write_section("Features", &sections.features); writer.write(contents.as_slice()); let end_nsec = ::time::get_time().nsec; let elapsed_mssec = (end_nsec - start_nsec) / 1000000; println!("changelog updated. (took {} ms)", elapsed_mssec); }
true
62aae4363ffd1c7035a96dc556dd050825538727
Rust
geoffjay/codility-rs
/src/binary-gap/lib.rs
UTF-8
1,401
3.375
3
[]
no_license
#![feature(test)] extern crate test; pub fn solution(n: i32) -> i32 { let mut gap = 0; let mut largest = 0; let mut num = n; let mut init = false; loop { // increase gap size when number is zero, and count has been initialized if num & 1 == 0 { if init { gap += 1; } } else { if gap > largest { largest = gap; } gap = 0; // start the count once a 1 has been seen init = true; } num >>= 1; if num == 0 { break; } } largest } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[test] fn it_works() { assert_eq!(solution(9), 2); assert_eq!(solution(529), 4); assert_eq!(solution(20), 1); assert_eq!(solution(15), 0); assert_eq!(solution(1041), 5); assert_eq!(solution(32), 0); assert_eq!(solution(0b0000), 0); assert_eq!(solution(0b10000), 0); assert_eq!(solution(0b10000000), 0); assert_eq!(solution(0b10000001), 6); } #[bench] #[ignore] fn bench_solution(b: &mut Bencher) { b.iter(|| solution(204913)); } #[bench] #[ignore] fn bench_solution_many(b: &mut Bencher) { b.iter(|| (0..10000).map(solution).collect::<Vec<i32>>()) } }
true
7ead7a9fcd57b7a557255d3c2f5a347291de7637
Rust
rust-embedded/embedded-hal
/embedded-hal-nb/src/serial.rs
UTF-8
3,970
3.421875
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! Serial interface. /// Serial error. pub trait Error: core::fmt::Debug { /// Convert error to a generic serial error kind /// /// By using this method, serial errors freely defined by HAL implementations /// can be converted to a set of generic serial errors upon which generic /// code can act. fn kind(&self) -> ErrorKind; } impl Error for core::convert::Infallible { #[inline] fn kind(&self) -> ErrorKind { match *self {} } } /// Serial error kind. /// /// This represents a common set of serial operation errors. HAL implementations are /// free to define more specific or additional error types. However, by providing /// a mapping to these common serial errors, generic code can still react to them. #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] #[non_exhaustive] pub enum ErrorKind { /// The peripheral receive buffer was overrun. Overrun, /// Received data does not conform to the peripheral configuration. /// Can be caused by a misconfigured device on either end of the serial line. FrameFormat, /// Parity check failed. Parity, /// Serial line is too noisy to read valid data. Noise, /// A different error occurred. The original error may contain more information. Other, } impl Error for ErrorKind { #[inline] fn kind(&self) -> ErrorKind { *self } } impl core::fmt::Display for ErrorKind { #[inline] fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Self::Overrun => write!(f, "The peripheral receive buffer was overrun"), Self::Parity => write!(f, "Parity check failed"), Self::Noise => write!(f, "Serial line is too noisy to read valid data"), Self::FrameFormat => write!( f, "Received data does not conform to the peripheral configuration" ), Self::Other => write!( f, "A different error occurred. The original error may contain more information" ), } } } /// Serial error type trait. /// /// This just defines the error type, to be used by the other traits. pub trait ErrorType { /// Error type type Error: Error; } impl<T: ErrorType + ?Sized> ErrorType for &mut T { type Error = T::Error; } /// Read half of a serial interface. /// /// Some serial interfaces support different data sizes (8 bits, 9 bits, etc.); /// This can be encoded in this trait via the `Word` type parameter. pub trait Read<Word: Copy = u8>: ErrorType { /// Reads a single word from the serial interface fn read(&mut self) -> nb::Result<Word, Self::Error>; } impl<T: Read<Word> + ?Sized, Word: Copy> Read<Word> for &mut T { #[inline] fn read(&mut self) -> nb::Result<Word, Self::Error> { T::read(self) } } /// Write half of a serial interface. pub trait Write<Word: Copy = u8>: ErrorType { /// Writes a single word to the serial interface. fn write(&mut self, word: Word) -> nb::Result<(), Self::Error>; /// Ensures that none of the previously written words are still buffered. fn flush(&mut self) -> nb::Result<(), Self::Error>; } impl<T: Write<Word> + ?Sized, Word: Copy> Write<Word> for &mut T { #[inline] fn write(&mut self, word: Word) -> nb::Result<(), Self::Error> { T::write(self, word) } #[inline] fn flush(&mut self) -> nb::Result<(), Self::Error> { T::flush(self) } } /// Implementation of `core::fmt::Write` for the HAL's `serial::Write`. /// /// TODO write example of usage impl<Word, Error: self::Error> core::fmt::Write for dyn Write<Word, Error = Error> + '_ where Word: Copy + From<u8>, { #[inline] fn write_str(&mut self, s: &str) -> core::fmt::Result { let _ = s .bytes() .map(|c| nb::block!(self.write(Word::from(c)))) .last(); Ok(()) } }
true
963697e7187c6fc18e4ed1c62c6b6aff79afb9cb
Rust
MiyamonY/atcoder
/abc/036/d/01/src/main.rs
UTF-8
2,655
2.859375
3
[]
no_license
#[allow(unused_macros)] macro_rules! scan { () => { { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim().to_string() } }; (;;) => { { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim().split_whitespace().map(|s| s.to_string()).collect::<Vec<String>>() } }; (;;$n:expr) => { { (0..$n).map(|_| scan!()).collect::<Vec<_>>() } }; ($t:ty) => { { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim().parse::<$t>().unwrap() } }; ($($t:ty),*) => { { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let mut iter = line.split_whitespace(); ( $(iter.next().unwrap().parse::<$t>().unwrap(),)* ) } }; ($t:ty;;) => { { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.split_whitespace() .map(|t| t.parse::<$t>().unwrap()) .collect::<Vec<_>>() } }; ($t:ty;;$n:expr) => { (0..$n).map(|_| scan!($t;;)).collect::<Vec<_>>() }; ($t:ty; $n:expr) => { (0..$n).map(|_| scan!($t) ).collect::<Vec<_>>() }; ($($t:ty),*; $n:expr) => { (0..$n).map(|_| scan!($($t),*) ).collect::<Vec<_>>() }; } const MOD: i64 = 1_000_000_007; fn dfs_w(graph: &[Vec<usize>], p: usize, n: usize, dp: &mut [Option<i64>]) -> i64 { let mut whites = 1; for &g in &graph[n] { if g != p { whites *= dfs(graph, n, g, dp); whites %= MOD; } } whites } fn dfs(graph: &[Vec<usize>], p: usize, n: usize, dp: &mut [Option<i64>]) -> i64 { if let Some(v) = dp[n] { return v; } let mut whites = 1; for &g in &graph[n] { if g != p { whites *= dfs_w(graph, n, g, dp); whites %= MOD; } } let v = (dfs_w(graph, p, n, dp) + whites) % MOD; dp[n] = Some(v); v } fn main() { let n = scan!(usize); let mut graph = vec![vec![]; n + 1]; for _ in 0..n - 1 { let (a, b) = scan!(usize, usize); graph[a].push(b); graph[b].push(a); } let mut dp = vec![None; n + 1]; println!("{}", dfs(&graph, 0, 1, &mut dp)); }
true
c476bad1aefaa05cf003fa16b01a4248b0e75bc9
Rust
liu-hz18/rCore-v2
/src/process/kernel_stack.rs
UTF-8
3,748
3.5
4
[]
no_license
//! 内核栈 [`KernelStack`] //! //! 用户态的线程出现中断时,因为用户栈无法保证可用性,中断处理流程必须在内核栈上进行。 //! 所以我们创建一个公用的内核栈,即当发生中断时,会将 Context 写到内核栈顶。 //! //! ### 线程 [`Context`] 的存放 //! > 1. 线程初始化时,一个 `Context` 放置在内核栈顶,`sp` 指向 `Context` 的位置 //! > (即 栈顶 - `size_of::<Context>()`) //! > 2. 切换到线程,执行 `__restore` 时,将 `Context` 的数据恢复到寄存器中后, //! > 会将 `Context` 出栈(即 `sp += size_of::<Context>()`), //! > 然后保存 `sp` 至 `sscratch`(此时 `sscratch` 即为内核栈顶) //! > 3. 发生中断时,将 `sscratch` 和 `sp` 互换,入栈一个 `Context` 并保存数据 //! //! 容易发现,线程的 `Context` 一定保存在内核栈顶。因此,当线程需要运行(切换到)时, //! 从 [`Thread`] 中取出 `Context` 然后置于内核栈顶即可 // 做法: // 1. 预留一段空间作为内核栈 // 2. 运行线程时,在 sscratch 寄存器中保存内核栈顶指针 // 3. 如果线程遇到中断,则将 Context 压入 sscratch 指向的栈中(Context 的地址为 sscratch - size_of::<Context>()),同时用新的栈地址来替换 sp(此时 sp 也会被复制到 a0 作为 handle_interrupt 的参数) // 4. 从中断中返回时(__restore 时),a0 应指向被压在内核栈中的 Context。此时出栈 Context 并且将栈顶保存到 sscratch 中 use super::*; use core::mem::size_of; /// 内核栈 #[repr(align(16))] #[repr(C)] pub struct KernelStack([u8; KERNEL_STACK_SIZE]); /// 公用的内核栈 pub static mut KERNEL_STACK: KernelStack = KernelStack([0; KERNEL_STACK_SIZE]); // 创建线程时,需要使用的操作就是在内核栈顶压入一个初始状态 Context impl KernelStack { /// 在栈顶加入 Context 并且返回新的栈顶指针 pub fn push_context(&mut self, context: Context) -> *mut Context { // 栈顶sp let stack_top = &self.0 as *const _ as usize + size_of::<Self>(); // Context 的位置 let push_address = (stack_top - size_of::<Context>()) as *mut Context; // 编译器负责解析这个指针 // Context 压入栈顶 unsafe { *push_address = context; // 编译器负责对内存对应位置依次赋值 } push_address } } // 关于内核栈(和sscratch)的作用的探讨: /* 如果不使用 sscratch 提供内核栈,而是像原来一样,遇到中断就直接将上下文压栈, 会有什么问题? 1. 一种情况不会出现问题: 只运行一个非常善意的线程,比如 loop {} 2. 一种情况导致异常无法处理(指无法进入 handle_interrupt): 线程把自己的 sp 搞丢了,比如 mv sp, x0。此时无法保存寄存器,也没有能够支持操作系统正常运行的栈 3. 一种情况导致产生嵌套异常(指第二个异常能够进行到调用 handle_interrupt 时,不考虑后续执行情况) 运行两个线程。在两个线程切换的时候,会需要切换页表。但是此时操作系统运行在前一个线程的栈上,一旦切换,再访问栈就会导致缺页,因为每个线程的栈只在自己的页表中 4. 一种情况导致一个用户进程(先不考虑是怎么来的)可以将自己变为内核进程,或以内核态执行自己的代码 用户进程巧妙地设计 sp,使得它恰好落在内核的某些变量附近,于是在保存寄存器时就修改了变量的值。这相当于任意修改操作系统的控制信息 */
true
c35f2531daf6327618f829e4d7e15ea4dc61309f
Rust
gdoct/rustvm
/src/instructions/asl.rs
UTF-8
2,522
3.140625
3
[ "BSD-3-Clause" ]
permissive
use crate::traits::{ Instruction, VirtualCpu }; use crate::types::{ Byte }; use crate::instructions::generic::*; fn asl(cpu: &mut dyn VirtualCpu, num: Byte, with: Byte) { let asl = num << with; cpu.set_a(asl); } /// AslZp: ASL zeropage /// Arithmetic Shift Left (ASL) operation between /// the content of Accumulator and the content of /// the zero page address pub struct AslZp { } impl Instruction for AslZp { fn opcode (&self) -> &'static str { "ASL"} fn hexcode(&self) -> Byte { 0x06 } fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> { let zp = fetch_zp_val(cpu)?; let a = cpu.get_a(); asl(cpu, a, zp); Ok(()) } } /// Asl: ASL /// Arithmetic Shift Left (ASL) operation between immediate val /// and the content of the Accumulator pub struct Asl { } impl Instruction for Asl { fn opcode (&self) -> &'static str { "ASL"} fn hexcode(&self) -> Byte { 0x0A } fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> { let imm = fetch_imm_val(cpu)?; let a = cpu.get_a(); asl(cpu, imm, a); Ok(()) } } /// AslAbs: ASL absolute /// Arithmetic Shift Left (ASL) operation between the content of /// Accumulator and the content located at address $1234 pub struct AslAbs { } impl Instruction for AslAbs { fn opcode (&self) -> &'static str { "ASL"} fn hexcode(&self) -> Byte { 0x0E } fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> { let val = fetch_abs_val(cpu)?; let a = cpu.get_a(); asl(cpu, a, val); Ok(()) } } /// AslZpX: ASL absolute, indexed by X pub struct AslZpX { } impl Instruction for AslZpX { fn opcode (&self) -> &'static str { "ASL"} fn hexcode(&self) -> Byte { 0x16 } fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> { let val = fetch_absx_val(cpu)?; let a = cpu.get_a(); asl(cpu, a, val); Ok(()) } } /// AslAbsX: ASL absolute, indexed by X /// Arithmetic Shift Left (ASL) operation between the content of Accumulator and the content /// located at address calculated from $1234 adding content of X pub struct AslAbsX { } impl Instruction for AslAbsX { fn opcode (&self) -> &'static str { "ASL"} fn hexcode(&self) -> Byte { 0x1E } fn execute(&self, cpu: &mut dyn VirtualCpu) -> std::io::Result<()> { let val = fetch_absx_val(cpu)?; let a = cpu.get_a(); asl(cpu, a, val); Ok(()) } }
true
f7d335dc73bf00f15287442fb8a40d2d3abe1ccc
Rust
jamestthompson3/subtxt-rs
/src/lib.rs
UTF-8
2,535
3.75
4
[]
no_license
pub struct Parser<'a> { input: std::str::Lines<'a>, } impl<'a> Parser<'a> { pub fn new(text: &'a str) -> Self { Self { input: text.lines(), } } } impl<'a> Iterator for Parser<'a> { type Item = Event<'a>; fn next(&mut self) -> Option<Self::Item> { match self.input.next() { Some(line) => { if line.is_empty() { return Some(Event::Empty); } let mut chars = line.chars(); match (chars.next().unwrap(), chars.next().unwrap()) { ('#', ' ') => Some(Event::Heading(line.split_at(2).1)), ('-', ' ') => Some(Event::List(line.split_at(2).1)), ('&', ' ') => Some(Event::Link(line.split_at(2).1)), ('>', ' ') => Some(Event::Quote(line.split_at(2).1)), _ => Some(Event::Text(line)), } } None => None, } } } #[derive(Debug, PartialEq)] pub enum Event<'a> { Heading(&'a str), Text(&'a str), List(&'a str), Quote(&'a str), Link(&'a str), Empty, } #[cfg(test)] mod tests { use super::*; #[test] fn parse_normal_input() { let test_string = "# Heading\n- List1"; let parser = Parser::new(test_string); let events = parser.collect::<Vec<Event>>(); assert_eq!(events[0], Event::Heading("Heading")); assert_eq!(events[1], Event::List("List1")); } #[test] fn parse_malformed_input() { let test_string = "# "; let parser = Parser::new(test_string); let events = parser.collect::<Vec<Event>>(); assert_eq!(events[0], Event::Heading("")); } #[test] fn parse_malformed_and_normal_input() { let test_string = "# \n- List1"; let parser = Parser::new(test_string); let events = parser.collect::<Vec<Event>>(); assert_eq!(events[0], Event::Heading("")); assert_eq!(events[1], Event::List("List1")); } #[test] fn parse_typo_input() { let test_string = "-List1"; let parser = Parser::new(test_string); let events = parser.collect::<Vec<Event>>(); assert_eq!(events[0], Event::Text("-List1")); } #[test] fn parse_empty_lines() { let test_string = "asdf\n\nasdf"; let parser = Parser::new(test_string); let events = parser.collect::<Vec<Event>>(); assert_eq!(events[1], Event::Empty); } }
true
31e738f9fca604d1584626d02ea022781ef862b6
Rust
SymmetricChaos/project_euler_rust
/src/worked_problems/euler_76.rs
UTF-8
2,993
3.5625
4
[]
no_license
// Problem: How many different ways can one hundred be written as a sum of at least two positive integers? /* */ struct AllIntegers { ctr: i64, parity: u8, } impl Iterator for AllIntegers { type Item = i64; fn next(&mut self) -> Option<i64> { if self.parity == 0 { self.parity = 1; return Some(self.ctr) } else { self.parity = 0; self.ctr += 1; return Some(-(self.ctr-1)) } } } fn gen_pentagonal(n: i64) -> i64 { (3*n*n-n)/2 } pub fn euler76() -> u64 { let mut known_partitions = [0i64;101]; known_partitions[0] = 1; known_partitions[1] = 1; for n in 2..=100 { let mut ctr = AllIntegers{ctr: 1, parity: 0}; let mut p = gen_pentagonal(ctr.next().unwrap()); let mut sum = 0; let mut sign = [1,1,-1,-1].iter().cycle(); while p <= n { sum += known_partitions[(n-p) as usize]*sign.next().unwrap(); p = gen_pentagonal(ctr.next().unwrap()); } known_partitions[n as usize] = sum } // We need to subtract 1 because the partitions we calculated include the number itself as a partition (known_partitions[100]-1) as u64 } pub fn euler76_example() { println!("\nProblem: How many different ways can one hundred be written as a sum of at least two positive integers?"); println!("\n\nThis could possibly be done using brute force to calculate partitions of each integer and then memoizing the results. However Euler's Pentagonal Number Theorem gives us a much more efficient option where we don't need to brute force calculate any partitions except for 0 and 1, which both have a single partition."); let s = " struct AllIntegers { ctr: i64, parity: u8, } impl Iterator for AllIntegers { type Item = i64; fn next(&mut self) -> Option<i64> { if self.parity == 0 { self.parity = 1; return Some(self.ctr) } else { self.parity = 0; self.ctr += 1; return Some(-(self.ctr-1)) } } } fn gen_pentagonal(n: i64) -> i64 { (3*n*n-n)/2 } pub fn euler76() -> u64 { let mut known_partitions = [0i64;101]; known_partitions[0] = 1; known_partitions[1] = 1; for n in 2..=100 { let mut ctr = AllIntegers{ctr: 1, parity: 0}; let mut p = gen_pentagonal(ctr.next().unwrap()); let mut sum = 0; let mut sign = [1,1,-1,-1].iter().cycle(); while p <= n { sum += known_partitions[(n-p) as usize]*sign.next().unwrap(); p = gen_pentagonal(ctr.next().unwrap()); } known_partitions[n as usize] = sum } // We need to subtract 1 because the partitions we calculated include the number itself as a partition (known_partitions[100]-1) as u64 }"; println!("\n{}\n",s); println!("The answer is: {}",euler76()); } #[test] fn test76() { assert_eq!(euler76(),190569291) }
true
6d6eb9ccc92b1b7c0c047bbda5e8f96466302ad9
Rust
mandx/harplay
/src/har/mod.rs
UTF-8
1,559
2.9375
3
[ "MIT" ]
permissive
pub mod errors; pub mod generic; use std::fs::File; use std::io::{BufReader, Read}; use std::path::Path; use serde::{Deserialize, Serialize}; pub use errors::HarError; use errors::*; pub use generic::*; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] pub struct Har { pub log: Log, } /// Deserialize a HAR from a path #[cfg_attr(tarpaulin, skip)] pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Har, HarError> { from_reader(BufReader::new(File::open(path).context(Opening)?)) } /// Deserialize a HAR from type which implements Read pub fn from_reader<R: Read>(read: R) -> Result<Har, HarError> { Ok(serde_json::from_reader::<R, Har>(read).context(Reading)?) } #[cfg(test)] mod tests { use super::*; use assert_matches::assert_matches; #[test] fn load_from_not_json_or_har() { let json = br#"{"some": "json"}"#; assert_matches!(from_reader(&json[..]), Err(_)); let json = br#"{"log": {}}"#; assert_matches!(from_reader(&json[..]), Err(_)); let json = br#"{"log":{"version":"1.2","pages":[],"entries":[]}}"#; assert_matches!(from_reader(&json[..]), Err(_)); } #[test] fn load_from_har() { let json = br#"{"log":{"creator":{"name":"Creator?","version":"0.1"},"pages":[],"entries":[]}}"#; assert_matches!(from_reader(&json[..]), Ok(_)); let json = br#"{"log":{"version":"1.2","creator":{"name":"Creator?","version":"0.1"},"pages":[],"entries":[]}}"#; assert_matches!(from_reader(&json[..]), Ok(_)); } }
true
4f1f7675a2b1b60a4e4a2ee34b4bc0918db7bf77
Rust
arielb1/rustc-perf-collector
/src/execute.rs
UTF-8
3,855
2.609375
3
[ "MIT" ]
permissive
//! Execute benchmarks in a sysroot. use std::str; use std::path::{Path, PathBuf}; use std::process::Command; use tempdir::TempDir; use rustc_perf_collector::{Patch, Run}; use errors::{Result, ResultExt}; use rust_sysroot::sysroot::Sysroot; use time_passes::{PassAverager, process_output}; pub struct Benchmark { pub name: String, pub path: PathBuf } impl Benchmark { pub fn command<P: AsRef<Path>>(&self, sysroot: &Sysroot, path: P) -> Command { let mut command = sysroot.command(path); command.current_dir(&self.path); command } /// Run a specific benchmark on a specific commit pub fn run(&self, sysroot: &Sysroot) -> Result<Vec<Patch>> { info!("processing {}", self.name); let mut patch_runs: Vec<Patch> = Vec::new(); for _ in 0..3 { let tmp_dir = TempDir::new(&format!("rustc-benchmark-{}", self.name))?; info!("temporary directory is {}", tmp_dir.path().display()); info!("copying files to temporary directory"); let output = self.command(sysroot, "cp").arg("-r").arg("-T").arg("--") .arg(".").arg(tmp_dir.path()).output()?; if !output.status.success() { bail!("copy failed: {}", String::from_utf8_lossy(&output.stderr)); } let make = || { let mut command = sysroot.command("make"); command.current_dir(tmp_dir.path()); command }; let output = make().arg("patches").output()?; let mut patches = str::from_utf8(&output.stdout) .chain_err(|| format!("make patches in {} returned non UTF-8 output", self.path.display()))? .split_whitespace() .collect::<Vec<_>>(); if patches.is_empty() { patches.push(""); } for patch in &patches { info!("running `make all{}`", patch); let output = make().arg(&format!("all{}", patch)) .env("CARGO_OPTS", "") .env("CARGO_RUSTC_OPTS", "-Z time-passes") .output()?; if !output.status.success() { bail!("stderr non empty: {},\n\n stdout={}", String::from_utf8_lossy(&output.stderr), String::from_utf8_lossy(&output.stdout) ); } let patch_index = if let Some(p) = patch_runs.iter().position(|p_run| p_run.patch == *patch) { p } else { patch_runs.push(Patch { patch: patch.to_string(), name: self.name.clone(), runs: Vec::new(), }); patch_runs.len() - 1 }; let combined_name = format!("{}{}", self.name, patch); patch_runs[patch_index].runs.push(Run { passes: process_output(&combined_name, output.stdout)?, name: combined_name, }); } } let mut patches = Vec::new(); for patch_run in patch_runs { let mut runs = patch_run.runs.into_iter(); let mut pa = PassAverager::new(runs.next().unwrap().passes); for run in runs { pa.average_with(run.passes)?; } patches.push(Patch { name: patch_run.name.clone(), patch: patch_run.patch.clone(), runs: vec![ Run { name: patch_run.name + &patch_run.patch, passes: pa.state, } ], }); } Ok(patches) } }
true
9dbba9ca63b7899339ef99ae88d923535b42df89
Rust
matthew86707/PDESimulator
/PDESimulator/src/simulation.rs
UTF-8
3,612
2.890625
3
[]
no_license
use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use std::{thread, time}; pub fn simulation_loop(display_values_mutex : Arc<Mutex<[f32; 15000]>>, GRID_SIZE_X : usize, GRID_SIZE_Y : usize){ let TIME_SAMPLES_PER_PRINTOUT : u32 = 100; let mut time_samples : u32 = 0; let mut time_acc : u32 = 0; let mut tick_number : u32 = 0; loop { let start = Instant::now(); { let mut old_values = display_values_mutex.lock().unwrap(); let new_values = heat_simulation_loop(block_array(*old_values), tick_number); tick_number += 1; *old_values = serialize_array(new_values); } time_acc += Instant::now().duration_since(start).subsec_millis(); if (time_samples == TIME_SAMPLES_PER_PRINTOUT){ println!("Delay : {}ms", time_acc as f32 / TIME_SAMPLES_PER_PRINTOUT as f32); time_samples = 0; time_acc = 0; } time_samples += 1; let ten_millis = time::Duration::from_millis(5); thread::sleep(ten_millis); } } fn heat_simulation_loop(data : [[f32; 100];150], tick_number : u32) -> [[f32; 100];150] { let mut next_data : [[f32; 100];150] = data; //Actual simulation code { /* Heat equation : du/dt - (du/dx)^2, where u = temperature, t = time, and x = our spacial domain which, solved for du/dt : du/dt = (du/dx)^2 expanding spacial domain and therefor it's derivitive into two dimensions : du/dt = (du/dx)^2 + (du/dy)^2 From this PDE we can use the central difference method to approximate the 2nd spacial derivitives... From the difference quotient of the first derivitive... f(x - h) - f(x + h) / 2h We then derive the difference quotient of the 2nd derivitive... f(x - h) - 2 * f(x) + f(x + h) / h^2 In code, this recurrence equation implies... next_data[i][j] += ((data[i + 1][j] - (2.0 * data[i][j]) + data[i - 1][j]) + (data[i][j + 1] - (2.0 * data[i][j]) + data[i][j - 1])) / h ^ 2; Which is seen implemented below. A note on boundry conditions : First derivitive boundry conditions set du/dx on all walls to be 0.5 */ for i in 0..150 - 1{ for j in 0..100 - 1{ if i == 0 || i == 150 || j == 0 || j == 100{ //next_data[i][j] = 0.5; }else{ next_data[i][j] += ((data[i + 1][j] - (2.0 * data[i][j]) + data[i - 1][j]) + (data[i][j + 1] - (2.0 * data[i][j]) + data[i][j - 1])) / 4.00; } } } if(tick_number < 200){ next_data[75][20] = 1.0; next_data[75][40] = 1.0; next_data[75][60] = 1.0; next_data[75][80] = 1.0; next_data[95][20] = 1.0; next_data[95][40] = 1.0; next_data[95][60] = 1.0; next_data[95][80] = 1.0; } } return next_data; } fn serialize_array(array : [[f32; 100];150]) -> [f32; 15000]{ let mut to_return : [f32; 15000] = [0.0; 15000]; for i in 0..to_return.len() { to_return[i] = array[i % 150][i / 150]; } return to_return; } fn block_array(array : [f32; 15000]) -> [[f32; 100];150]{ let mut to_return : [[f32; 100];150] = [[0.0; 100]; 150]; for i in 0..150{ for j in 0..100{ to_return[i][j] = array[j * 150 + i]; } } return to_return; }
true
1f4d83c360620fae73a2f35780e132c22c51605e
Rust
kroeckx/ruma
/crates/ruma-events/src/room/redaction.rs
UTF-8
2,461
2.796875
3
[ "MIT" ]
permissive
//! Types for the *m.room.redaction* event. use ruma_common::MilliSecondsSinceUnixEpoch; use ruma_events_macros::{Event, EventContent}; use ruma_identifiers::{EventId, RoomId, UserId}; use serde::{Deserialize, Serialize}; use crate::Unsigned; /// Redaction event. #[derive(Clone, Debug, Event)] #[allow(clippy::exhaustive_structs)] pub struct RedactionEvent { /// Data specific to the event type. pub content: RedactionEventContent, /// The ID of the event that was redacted. pub redacts: EventId, /// The globally unique event identifier for the user who sent the event. pub event_id: EventId, /// The fully-qualified ID of the user who sent this event. pub sender: UserId, /// Timestamp in milliseconds on originating homeserver when this event was sent. pub origin_server_ts: MilliSecondsSinceUnixEpoch, /// The ID of the room associated with this event. pub room_id: RoomId, /// Additional key-value pairs not signed by the homeserver. pub unsigned: Unsigned, } /// Redaction event without a `room_id`. #[derive(Clone, Debug, Event)] #[allow(clippy::exhaustive_structs)] pub struct SyncRedactionEvent { /// Data specific to the event type. pub content: RedactionEventContent, /// The ID of the event that was redacted. pub redacts: EventId, /// The globally unique event identifier for the user who sent the event. pub event_id: EventId, /// The fully-qualified ID of the user who sent this event. pub sender: UserId, /// Timestamp in milliseconds on originating homeserver when this event was sent. pub origin_server_ts: MilliSecondsSinceUnixEpoch, /// Additional key-value pairs not signed by the homeserver. pub unsigned: Unsigned, } /// A redaction of an event. #[derive(Clone, Debug, Default, Deserialize, Serialize, EventContent)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] #[ruma_event(type = "m.room.redaction", kind = Message)] pub struct RedactionEventContent { /// The reason for the redaction, if any. #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option<String>, } impl RedactionEventContent { /// Creates an empty `RedactionEventContent`. pub fn new() -> Self { Self::default() } /// Creates a new `RedactionEventContent` with the given reason. pub fn with_reason(reason: String) -> Self { Self { reason: Some(reason) } } }
true
072a8fb46341d51bd070b776ebd1071a560ab6dc
Rust
KrutNA/huffman-coding
/src/queue.rs
UTF-8
462
2.640625
3
[]
no_license
use crate::types::node::*; use std::collections::BinaryHeap; pub fn update_with_data(heap_buffer: &mut [u32], data: &[u8]) { for &byte in data.iter() { heap_buffer[byte as usize] += 1; } } pub fn convert_to_heap( heap_buffer: &mut [u32] ) -> BinaryHeap<Element> { heap_buffer.iter().enumerate().filter_map(|(data, &priority)| { if priority > 0 { Some(Element::new_with_priority(data as u8, priority)) } else { None } }).collect() }
true
2706201ef1c85ac4eb4e84369f6783e76f71263d
Rust
KadoBOT/exercism-rust
/diamond/src/lib.rs
UTF-8
705
3.203125
3
[]
no_license
pub fn get_diamond(c: char) -> Vec<String> { let distance = ((c as u8) - b'A') as usize; let mut result = vec![" ".repeat(distance + distance + 1); distance + distance + 1]; let size = result.len(); let mut replace_char = |idx: usize, pos: usize, ch: char| { result[idx].replace_range(pos..=pos, &ch.to_string()); }; let mut replace_row = |idx: usize, n: usize| { replace_char(idx, distance - n, (b'A' + n as u8) as char); replace_char(idx, distance + n, (b'A' + n as u8) as char); }; (0..=distance).for_each(|n| { let tail = (size - n) - 1; replace_row(n as usize, n); replace_row(tail as usize, n); }); result }
true
a988a03a0c59f16e3b29b0bf32f34af8acf6ac10
Rust
andrew-johnson-4/rdxl_internals
/src/xtext_crumb.rs
UTF-8
2,887
2.5625
3
[ "MIT", "Apache-2.0" ]
permissive
// Copyright 2020, The rdxl Project Developers. // Dual Licensed under the MIT license and the Apache 2.0 license, // see the LICENSE file or <http://opensource.org/licenses/MIT> // also see LICENSE2 file or <https://www.apache.org/licenses/LICENSE-2.0> use quote::{quote_spanned, ToTokens}; use proc_macro2::{Span, Literal}; use syn::parse::{Parse, ParseStream, Result}; use syn::{Token}; use syn::token::{Bracket,Brace}; use crate::core::{TokenAsLiteral}; use crate::xtext::{XtextTag,XtextExpr,BracketedExpr,XtextClass}; pub enum XtextCrumb { S(String, Span), T(XtextTag), E(XtextExpr), F(BracketedExpr), C(XtextClass) } impl XtextCrumb { pub fn span(&self) -> Span { match self { XtextCrumb::S(_,sp) => { sp.clone() } XtextCrumb::T(t) => { t.outer_span.clone() } XtextCrumb::E(e) => { e.brace_token1.span.clone() } XtextCrumb::F(f) => { f.span() } XtextCrumb::C(c) => { c.open.span.join(c.close.span).unwrap_or(c.open.span) } } } pub fn parse_outer(input: ParseStream) -> Result<Vec<Self>> { let mut cs = vec!(); while !input.is_empty() && !(input.peek(Token![<]) && input.peek2(Token![/])) { let c: XtextCrumb = input.parse()?; cs.push(c); } Ok(cs) } } impl Parse for XtextCrumb { fn parse(input: ParseStream) -> Result<Self> { if input.peek(Token![<]) && input.peek2(Token![!]) { let c: XtextClass = input.parse()?; Ok(XtextCrumb::C(c)) } else if input.peek(Token![<]) { let t: XtextTag = input.parse()?; Ok(XtextCrumb::T(t)) } else if input.peek(Bracket) { let f: BracketedExpr = BracketedExpr::parse("markup".to_string(),input)?; Ok(XtextCrumb::F(f)) } else if input.peek(Brace) { let e: XtextExpr = input.parse()?; Ok(XtextCrumb::E(e)) } else { let t: TokenAsLiteral = input.parse()?; Ok(XtextCrumb::S(t.token_literal, t.span)) } } } impl ToTokens for XtextCrumb { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { match self { XtextCrumb::S(s,span) => { let l = Literal::string(&s); (quote_spanned!{span.clone()=> stream.push_str(#l); }).to_tokens(tokens); }, XtextCrumb::T(t) => { t.to_tokens(tokens); } XtextCrumb::E(e) => { e.to_tokens(tokens); } XtextCrumb::F(e) => { e.to_tokens(tokens); } XtextCrumb::C(c) => { let span = c.span(); (quote_spanned!{span=> stream.push_str(&#c.to_string()); }).to_tokens(tokens); } } } }
true
35e07ed8d1c382e5e625ba0beb0438033033b0fe
Rust
doytsujin/yew
/packages/yew/src/functional/hooks/use_transitive_state/feat_ssr.rs
UTF-8
2,278
2.6875
3
[ "Apache-2.0", "MIT" ]
permissive
//! The server-side rendering variant. use std::cell::RefCell; use std::rc::Rc; use base64ct::{Base64, Encoding}; use serde::de::DeserializeOwned; use serde::Serialize; use crate::functional::{Hook, HookContext, PreparedState}; use crate::suspense::SuspensionResult; pub(super) struct TransitiveStateBase<T, D, F> where D: Serialize + DeserializeOwned + PartialEq + 'static, T: Serialize + DeserializeOwned + 'static, F: 'static + FnOnce(Rc<D>) -> T, { pub state_fn: RefCell<Option<F>>, pub deps: Rc<D>, } impl<T, D, F> PreparedState for TransitiveStateBase<T, D, F> where D: Serialize + DeserializeOwned + PartialEq + 'static, T: Serialize + DeserializeOwned + 'static, F: 'static + FnOnce(Rc<D>) -> T, { fn prepare(&self) -> String { let f = self.state_fn.borrow_mut().take().unwrap(); let state = f(self.deps.clone()); let state = bincode::serialize(&(Some(&state), Some(&*self.deps))) .expect("failed to prepare state"); Base64::encode_string(&state) } } #[doc(hidden)] pub fn use_transitive_state<T, D, F>( f: F, deps: D, ) -> impl Hook<Output = SuspensionResult<Option<Rc<T>>>> where D: Serialize + DeserializeOwned + PartialEq + 'static, T: Serialize + DeserializeOwned + 'static, F: 'static + FnOnce(Rc<D>) -> T, { struct HookProvider<T, D, F> where D: Serialize + DeserializeOwned + PartialEq + 'static, T: Serialize + DeserializeOwned + 'static, F: 'static + FnOnce(Rc<D>) -> T, { deps: D, f: F, } impl<T, D, F> Hook for HookProvider<T, D, F> where D: Serialize + DeserializeOwned + PartialEq + 'static, T: Serialize + DeserializeOwned + 'static, F: 'static + FnOnce(Rc<D>) -> T, { type Output = SuspensionResult<Option<Rc<T>>>; fn run(self, ctx: &mut HookContext) -> Self::Output { let f = self.f; ctx.next_prepared_state(move |_re_render, _| -> TransitiveStateBase<T, D, F> { TransitiveStateBase { state_fn: Some(f).into(), deps: self.deps.into(), } }); Ok(None) } } HookProvider::<T, D, F> { deps, f } }
true
802004b243938e1da6cda1e4bfff6b4a6aab2d05
Rust
dollarkillerx/Learn-RUST-again
/day2_4/src/main.rs
UTF-8
695
3.453125
3
[ "MIT" ]
permissive
fn main() { hello1(); hello2(); } struct User; trait Hel { fn hello(&self) -> String; } trait Hum { fn hello(&self); fn hello_world<T: Hel>(&self, you: T); } struct DK; impl Hel for DK { fn hello(&self) -> String { "hello DK".to_string() } } impl Hum for User { fn hello(&self) { println!("Hello Hum"); } fn hello_world<T: Hel>(&self, you: T) { println!("{}",you.hello()); } } fn hello1() { let a = User; status_test(a); } fn hello2() { let a = User; dyn_test(&a); } fn status_test<T: Hum>(u: T) { let b = DK; u.hello_world(b); } fn dyn_test(c: &dyn Hum) { let b = DK; c.hello_world(b); }
true
1bc54ef27643c5b481231dd66aa5edd12898efb6
Rust
ScarboroughCoral/Notes
/剑指Offer/面试题56 - I. 数组中数字出现的次数.rs
UTF-8
421
3.265625
3
[]
no_license
impl Solution { pub fn single_numbers(nums: Vec<i32>) -> Vec<i32> { let mut r=0; for x in &nums{ r^=x; } let mut d=1; while (d&r)==0{ d<<=1; } let mut a=0; let mut b=0; for x in &nums{ if x&d==0{ a^=x; } else{ b^=x; } } return vec![a,b]; } }
true
e81986963f4f3f3a4fd322b1288ef3f58d4e9e99
Rust
ens-ds23/ensembl-client
/src/assets/browser/app/src/controller/output/report.rs
UTF-8
7,288
2.703125
3
[]
no_license
use std::collections::HashMap; use std::sync::{ Arc, Mutex }; use controller::global::{ App, AppRunner }; use controller::output::OutputAction; use serde_json::Map as JSONMap; use serde_json::Value as JSONValue; use serde_json::Number as JSONNumber; #[derive(Clone)] #[allow(unused)] pub enum StatusJigsawType { Number, String, Boolean } #[derive(Clone)] #[allow(unused)] pub enum StatusJigsaw { Atom(String,StatusJigsawType), Array(Vec<StatusJigsaw>), Object(HashMap<String,StatusJigsaw>) } struct StatusOutput { last_value: Option<JSONValue>, jigsaw: StatusJigsaw, last_sent: Option<f64>, send_every: Option<f64> } impl StatusOutput { fn new(jigsaw: StatusJigsaw) -> StatusOutput { StatusOutput { jigsaw, last_sent: None, send_every: Some(0.), last_value: None, } } fn is_send_now(&self, t: f64) -> bool { if let Some(interval) = self.send_every { if interval == 0. { return true; } if let Some(last_sent) = self.last_sent { if t - last_sent > interval { return true; } } else { return true; } } return false; } } lazy_static! { static ref REPORT_CONFIG: Vec<(&'static str,StatusJigsaw,Option<f64>)> = vec!{ ("location",StatusJigsaw::Array(vec!{ StatusJigsaw::Atom("stick".to_string(),StatusJigsawType::String), StatusJigsaw::Atom("start".to_string(),StatusJigsawType::Number), StatusJigsaw::Atom("end".to_string(),StatusJigsawType::Number), }),Some(500.)), ("bumper",StatusJigsaw::Array(vec!{ StatusJigsaw::Atom("bumper-top".to_string(),StatusJigsawType::Boolean), StatusJigsaw::Atom("bumper-bottom".to_string(),StatusJigsawType::Boolean), StatusJigsaw::Atom("bumper-out".to_string(),StatusJigsawType::Boolean), StatusJigsaw::Atom("bumper-in".to_string(),StatusJigsawType::Boolean), StatusJigsaw::Atom("bumper-left".to_string(),StatusJigsawType::Boolean), StatusJigsaw::Atom("bumper-right".to_string(),StatusJigsawType::Boolean), }),Some(500.)) }; } pub struct ReportImpl { pieces: HashMap<String,String>, outputs: HashMap<String,StatusOutput> } impl ReportImpl { pub fn new() -> ReportImpl { let out = ReportImpl { pieces: HashMap::<String,String>::new(), outputs: HashMap::<String,StatusOutput>::new() }; out } fn get_piece(&mut self, key: &str) -> Option<String> { self.pieces.get(key).map(|s| s.clone()) } fn get_output(&mut self, key: &str) -> Option<&mut StatusOutput> { self.outputs.get_mut(key) } fn add_output(&mut self, key: &str, jigsaw: StatusJigsaw) { self.outputs.insert(key.to_string(),StatusOutput::new(jigsaw)); } pub fn set_status(&mut self, key: &str, value: &str) { self.pieces.insert(key.to_string(),value.to_string()); } pub fn set_interval(&mut self, key: &str, interval: Option<f64>) { if let Some(ref mut p) = self.get_output(key) { p.send_every = interval; } } fn make_number(&self, data: &str) -> JSONValue { data.parse::<f64>().ok() .and_then(|v| JSONNumber::from_f64(v) ) .map(|v| JSONValue::Number(v) ) .unwrap_or(JSONValue::Null) } fn make_bool(&self, data: &str) -> JSONValue { data.parse::<bool>().ok() .map(|v| JSONValue::Bool(v)) .unwrap_or(JSONValue::Null) } fn make_atom(&self, key: &str, type_: &StatusJigsawType) -> Option<JSONValue> { let v = self.pieces.get(key); if let Some(ref v) = v { Some(match type_ { StatusJigsawType::Number => self.make_number(v), StatusJigsawType::String => JSONValue::String(v.to_string()), StatusJigsawType::Boolean => self.make_bool(v) }) } else { None } } fn make_array(&self, values: &Vec<StatusJigsaw>) -> Option<JSONValue> { let mut out = Vec::<JSONValue>::new(); for v in values { if let Some(value) = self.make_value(v) { out.push(value); } else { return None; } } Some(JSONValue::Array(out)) } fn make_object(&self, values: &HashMap<String,StatusJigsaw>) -> Option<JSONValue> { let mut out = JSONMap::<String,JSONValue>::new(); for (k,v) in values { if let Some(value) = self.make_value(v) { out.insert(k.to_string(),value); } else { return None; } } Some(JSONValue::Object(out)) } fn make_value(&self, j: &StatusJigsaw) -> Option<JSONValue> { match j { StatusJigsaw::Atom(key,type_) => self.make_atom(key,type_), StatusJigsaw::Array(values) => self.make_array(values), StatusJigsaw::Object(values) => self.make_object(values) } } fn new_report(&mut self, t: f64) -> Option<JSONValue> { let mut out = JSONMap::<String,JSONValue>::new(); for (k,s) in &self.outputs { if let Some(value) = self.make_value(&s.jigsaw) { if let Some(ref last_value) = s.last_value { if last_value == &value { continue; } } if s.is_send_now(t) { out.insert(k.to_string(),value.clone()); } } } for (k,v) in &out { if let Some(ref mut p) = self.outputs.get_mut(k) { p.last_value = Some(v.clone()); p.last_sent = Some(t); } } if out.len() > 0 { Some(JSONValue::Object(out)) } else { None } } } #[derive(Clone)] pub struct Report(Arc<Mutex<ReportImpl>>); impl Report { pub fn new(ar: &mut AppRunner) -> Report { let mut out = Report(Arc::new(Mutex::new(ReportImpl::new()))); for (k,j,v) in REPORT_CONFIG.iter() { { let mut imp = out.0.lock().unwrap(); imp.add_output(k,j.clone()); } out.set_interval(k,*v); } ar.add_timer(enclose! { (out) move |app,t| { if let Some(report) = out.new_report(t) { vec!{ OutputAction::SendCustomEvent("bpane-out".to_string(),report) } } else { vec!{} } }},None); out } pub fn set_status(&self, key: &str, value: &str) { let mut imp = self.0.lock().unwrap(); imp.set_status(key,value); } pub fn set_status_bool(&self, key: &str, value: bool) { self.set_status(key,&value.to_string()); } pub fn set_interval(&mut self, key: &str, interval: Option<f64>) { let mut imp = self.0.lock().unwrap(); imp.set_interval(key,interval); } pub fn new_report(&self, t: f64) -> Option<JSONValue> { self.0.lock().unwrap().new_report(t) } }
true
7cbe3f3c5c78b20de4c23dc0199e9d3f80a2c69e
Rust
pormeu/openbrush-contracts
/examples/reentrancy-guard/flip_on_me/lib.rs
UTF-8
708
2.65625
3
[ "MIT" ]
permissive
#![cfg_attr(not(feature = "std"), no_std)] #[ink_lang::contract] pub mod flip_on_me { use ink_env::call::FromAccountId; use my_flipper_guard::my_flipper_guard::MyFlipper; #[ink(storage)] #[derive(Default)] pub struct FlipOnMe {} impl FlipOnMe { #[ink(constructor)] pub fn new() -> Self { Self::default() } #[ink(message)] pub fn flip_on_me(&mut self) { let caller = self.env().caller(); // This method does a cross-contract call to caller contract and calls the `flip` method. let mut flipper: MyFlipper = FromAccountId::from_account_id(caller); flipper.flip(); } } }
true
7fd1fbd2faf430e8d8dfed2219562371e2ef46d0
Rust
RaymondK99/advent_of_code_2020_rs
/src/util/day_02.rs
UTF-8
2,057
3.421875
3
[]
no_license
use super::Part; pub fn solve(input : String, part: Part) -> String { let list = input.lines() .map(|line| parse_line(line)) .collect(); let result = match part { Part::Part1 => part1(list), Part::Part2 => part2(list) }; format!("{}",result) } fn parse_line(input:&str) -> (usize,usize,char,&str) { let cols:Vec<&str> = input.split(|c| c == ' ' || c == ':' || c == '-' ).collect(); let min = cols[0].parse().unwrap(); let max = cols[1].parse().unwrap(); let pattern = cols[2].as_bytes()[0] as char; let password = cols[4]; (min,max,pattern,password) } fn part1(list:Vec<(usize,usize,char,&str)>) -> usize { list.iter().filter( |&(min,max,ch,input)| { let cnt = input.chars().filter(|c| *c == *ch).count(); cnt >= *min && cnt <= *max }).count() } fn part2(list:Vec<(usize,usize,char,&str)>) -> usize { list.iter().filter( |&(index1,index2,ch,input)| { let ch1 = input.as_bytes()[index1-1] as char; let ch2 = input.as_bytes()[index2-1] as char; (*ch == ch1) ^ (*ch == ch2) }).count()} #[cfg(test)] mod tests { // Note this useful idiom: importing names from outer (for mod tests) scope. use super::*; use util::Part::{Part1, Part2}; #[test] fn test_parse() { let input = "1-3 a: abcde"; assert_eq!((1,3,'a',"abcde"), parse_line(input)); } #[test] fn test1() { let input = "1-3 a: abcde 1-3 b: cdefg 2-9 c: ccccccccc"; assert_eq!("2", solve(input.to_string(),Part1)); } #[test] fn test_part1() { let input = include_str!("../../input_02.txt"); assert_eq!("548", solve(input.to_string(), Part1)); } #[test] fn test2() { let input = "1-3 a: abcde 1-3 b: cdefg 2-9 c: ccccccccc"; assert_eq!("1", solve(input.to_string(),Part2)); } #[test] fn test_part2() { let input = include_str!("../../input_02.txt"); assert_eq!("502", solve(input.to_string(), Part2)); } }
true
974f376bbe0dfc6d2fe87d7bde6b2462456dd29a
Rust
YoshikawaMasashi/toid
/src/high_layer_trial/phrase_operation/split_by_condition.rs
UTF-8
680
2.71875
3
[]
no_license
use super::super::super::data::music_info::{Note, Phrase}; pub fn split_by_condition<N: Note + Eq + Ord + Clone>( phrase: Phrase<N>, condition: Vec<bool>, ) -> (Phrase<N>, Phrase<N>) { let mut true_phrase = Phrase::new(); let mut false_phrase = Phrase::new(); true_phrase = true_phrase.set_length(phrase.length); false_phrase = false_phrase.set_length(phrase.length); for (note, &cond) in phrase.note_vec().iter().zip(condition.iter()) { if cond { true_phrase = true_phrase.add_note(note.clone()); } else { false_phrase = false_phrase.add_note(note.clone()); } } (true_phrase, false_phrase) }
true
e221920e5dca5c1739194e031e0a40581847066d
Rust
RevelationOfTuring/Rust-exercise
/src/error_handling_result_early_returns.rs
UTF-8
1,265
4.09375
4
[ "Apache-2.0" ]
permissive
/* 我们可以显式地使用组合算子处理了错误。 另一种处理错误的方式是使用 `match 语句` 和 `提前返回`(early return)的结合。 也就是说: 如果发生错误,我们可以`停止`函数的执行然后返回错误。 这样的代码更好写,更易读。 */ #[cfg(test)] mod tests { use std::num::ParseIntError; // 如果遇到 fn multiply(first_num_str: &str, second_num_str: &str) -> Result<i32, ParseIntError> { let n1 = match first_num_str.parse::<i32>() { Ok(i) => i, // 提前返回,如果出了错误 Err(e) => return Err(e), }; let n2 = match second_num_str.parse::<i32>() { Ok(i) => i, Err(e) => return Err(e), }; // 正确的返回 Ok(n1 * n2) } fn print_result(result: Result<i32, ParseIntError>) { match result { Ok(i) => println!("{}", i), Err(e) => println!("Error: {}", e), } } #[test] fn test_error_handling_result_early_returns() { // 正常现象 print_result(multiply("10", "11")); // 返回错误(提前返回) print_result(multiply("michael.w", "11")); } }
true
a6f6c1b0a2a2212631a11f9881158a39ee17b1a3
Rust
villor/rustia
/crates/proxy/src/game.rs
UTF-8
1,857
2.859375
3
[]
no_license
use bytes::BytesMut; use protocol::{FrameType, packet::ClientPacket}; use crate::{Origin, ProxyConnection, ProxyEventHandler}; /// Event handler that will detect a game protocol handshake and enable XTEA with the correct key #[derive(Default)] pub struct GameHandshaker; impl GameHandshaker { pub fn new() -> Self { Self::default() } pub fn new_boxed() -> Box<Self> { Box::new(Self::new()) } } impl ProxyEventHandler for GameHandshaker { fn on_new_connection(&self, connection: &mut ProxyConnection) -> anyhow::Result<()> { // Because nonce is weird connection.set_frame_type(FrameType::LengthPrefixed); Ok(()) } fn on_frame(&self, connection: &mut ProxyConnection, from: Origin, frame: BytesMut) -> anyhow::Result<BytesMut> { if connection.first_frame() { // Nonce from server connection.set_frame_type(FrameType::Raw); } else if connection.current_frame_id() == 1 { // First frame from client match from { Origin::Client => { let mut frame = frame.clone(); // clone really needed? BytesMut is very non-intuitive, Frame-abstraction? match ClientPacket::read_from(&mut frame)? { ClientPacket::GameLogin(login_packet) => { connection.set_frame_type(FrameType::XTEA(login_packet.xtea_key)); }, packet => { anyhow::bail!(format!("Wrong first packet from client, expected GameLogin, got {:?}", packet)); }, }; }, Origin::Server => { anyhow::bail!("Unexpected frame order, client should send the second frame."); } } } Ok(frame) } }
true
7f5f0a9ae08b396e66daa292f60f500d7d3265cb
Rust
FreskyZ/fff-lang
/src/vm/builtin_impl.rs
UTF-8
48,766
2.671875
3
[ "Apache-2.0" ]
permissive
// Builtin methods implementation use std::str::FromStr; use std::fmt; use lexical::SeperatorKind; use codegen::FnName; use codegen::ItemID; use codegen::Type; use codegen::Operand; use codegen::TypeCollection; use super::runtime::Runtime; use super::runtime::RuntimeValue; // Based on the assumption that runtime will not meet invalid, return ItemID::Invalid for index out of bound fn prep_param_type(typeids: &Vec<ItemID>, index: usize) -> Option<usize> { if index >= typeids.len() { None } else { Some(typeids[index].as_option().unwrap()) // assume unwrap able } } fn prep_param(params: &Vec<Operand>, index: usize) -> Option<&Operand> { if index >= params.len() { None } else { Some(&params[index]) } } fn read_int_from_stdin<T>() -> T where T: FromStr, <T as FromStr>::Err: fmt::Debug { use std::io; let mut line = String::new(); io::stdin().read_line(&mut line).expect("Failed to read line"); line.trim().parse().expect("Wanted a number") } fn str_begin_with(source: &str, pattern: &str) -> bool { let mut source_chars = source.chars(); let mut pattern_chars = pattern.chars(); loop { match (source_chars.next(), pattern_chars.next()) { (Some(ch1), Some(ch2)) => if ch1 != ch2 { return false; }, // else continue (_, _) => return true, } } } pub fn dispatch_builtin(fn_sign: (FnName, Vec<ItemID>), params: &Vec<Operand>, types: &TypeCollection, rt: &mut Runtime) -> RuntimeValue { use super::runtime::RuntimeValue::*; let fn_name = fn_sign.0; let param_types = fn_sign.1; macro_rules! native_forward_2 { ($param0: expr, $param1: expr, $pat: pat => $stmt: block) => (match (rt.index($param0), rt.index($param1)) { $pat => $stmt, _ => unreachable!() }) } macro_rules! native_forward_1 { ($param0: expr, $pat: pat => $stmt: block) => (match rt.index($param0) { $pat => $stmt _ => unreachable!() }) } macro_rules! native_forward_mut_1 { ($param0: expr, $pat: pat => $stmt: block) => (match rt.index_mut($param0) { $pat => $stmt _ => unreachable!() }) } // Global match (&fn_name, prep_param_type(&param_types, 0), prep_param_type(&param_types, 1), prep_param(&params, 0), prep_param(&params, 1)) { (&FnName::Ident(ref ident_name), param_type0, param_type1, param0, param1) => match (ident_name.as_ref(), param_type0, param_type1, param0, param1) { ("write", Some(13), None, Some(ref operand), None) => { print!("{}", rt.index(operand).get_str_lit()); return RuntimeValue::Unit; } ("writeln", Some(13), None, Some(ref operand), None) => { println!("{}", rt.index(operand).get_str_lit()); return RuntimeValue::Unit; } ("read_i32", None, None, None, None) => return RuntimeValue::Int(read_int_from_stdin::<i32>() as u64), ("read_u64", None, None, None, None) => return RuntimeValue::Int(read_int_from_stdin::<u64>()), _ => (), }, _ => (), } // Builtin type match (&fn_name, prep_param_type(&param_types, 0), prep_param_type(&param_types, 1), prep_param(&params, 0), prep_param(&params, 1)) { // Integral Add (&FnName::Operator(SeperatorKind::Add), Some(1), Some(1), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Add), Some(2), Some(2), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Add), Some(3), Some(3), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Add), Some(4), Some(4), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Add), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Add), Some(6), Some(6), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Add), Some(7), Some(7), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Add), Some(8), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 + value1); } }, // Integral Sub (&FnName::Operator(SeperatorKind::Sub), Some(1), Some(1), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Sub), Some(2), Some(2), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Sub), Some(3), Some(3), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Sub), Some(4), Some(4), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Sub), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Sub), Some(6), Some(6), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Sub), Some(7), Some(7), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Sub), Some(8), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 - value1); } }, // Integral Mul (&FnName::Operator(SeperatorKind::Mul), Some(1), Some(1), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Mul), Some(2), Some(2), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Mul), Some(3), Some(3), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Mul), Some(4), Some(4), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Mul), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Mul), Some(6), Some(6), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Mul), Some(7), Some(7), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Mul), Some(8), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 * value1); } }, // Integral Div (&FnName::Operator(SeperatorKind::Div), Some(1), Some(1), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Div), Some(2), Some(2), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Div), Some(3), Some(3), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Div), Some(4), Some(4), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Div), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Div), Some(6), Some(6), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Div), Some(7), Some(7), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Div), Some(8), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 / value1); } }, // Integral Rem (&FnName::Operator(SeperatorKind::Rem), Some(1), Some(1), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Rem), Some(2), Some(2), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Rem), Some(3), Some(3), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Rem), Some(4), Some(4), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Rem), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Rem), Some(6), Some(6), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Rem), Some(7), Some(7), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Rem), Some(8), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 % value1); } }, // Integral ShiftLeft (&FnName::Operator(SeperatorKind::ShiftLeft), Some(1), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::ShiftLeft), Some(2), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::ShiftLeft), Some(3), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::ShiftLeft), Some(4), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::ShiftLeft), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::ShiftLeft), Some(6), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::ShiftLeft), Some(7), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::ShiftLeft), Some(8), Some(5), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 << value1); } }, // Integral ShiftRight (&FnName::Operator(SeperatorKind::ShiftRight), Some(1), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::ShiftRight), Some(2), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::ShiftRight), Some(3), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::ShiftRight), Some(4), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::ShiftRight), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::ShiftRight), Some(6), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::ShiftRight), Some(7), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::ShiftRight), Some(8), Some(5), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 >> value1); } }, // Integral BitAnd (&FnName::Operator(SeperatorKind::BitAnd), Some(1), Some(1), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitAnd), Some(2), Some(2), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitAnd), Some(3), Some(3), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitAnd), Some(4), Some(4), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitAnd), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitAnd), Some(6), Some(6), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitAnd), Some(7), Some(7), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitAnd), Some(8), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 & value1); } }, // Integral BitOr (&FnName::Operator(SeperatorKind::BitOr), Some(1), Some(1), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitOr), Some(2), Some(2), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitOr), Some(3), Some(3), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitOr), Some(4), Some(4), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitOr), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitOr), Some(6), Some(6), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitOr), Some(7), Some(7), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitOr), Some(8), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 | value1); } }, // Integral BitXor (&FnName::Operator(SeperatorKind::BitXor), Some(1), Some(1), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitXor), Some(2), Some(2), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitXor), Some(3), Some(3), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitXor), Some(4), Some(4), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitXor), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitXor), Some(6), Some(6), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitXor), Some(7), Some(7), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::BitXor), Some(8), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Int(value0 ^ value1); } }, // Integral Equal (&FnName::Operator(SeperatorKind::Equal), Some(1), Some(1), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Equal), Some(2), Some(2), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Equal), Some(3), Some(3), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Equal), Some(4), Some(4), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Equal), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Equal), Some(6), Some(6), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Equal), Some(7), Some(7), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Equal), Some(8), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 == value1); } }, // Integral NotEqual (&FnName::Operator(SeperatorKind::NotEqual), Some(1), Some(1), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::NotEqual), Some(2), Some(2), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::NotEqual), Some(3), Some(3), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::NotEqual), Some(4), Some(4), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::NotEqual), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::NotEqual), Some(6), Some(6), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::NotEqual), Some(7), Some(7), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::NotEqual), Some(8), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 != value1); } }, // Integral GreatEqual (&FnName::Operator(SeperatorKind::GreatEqual), Some(1), Some(1), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::GreatEqual), Some(2), Some(2), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::GreatEqual), Some(3), Some(3), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::GreatEqual), Some(4), Some(4), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::GreatEqual), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::GreatEqual), Some(6), Some(6), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::GreatEqual), Some(7), Some(7), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::GreatEqual), Some(8), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 >= value1); } }, // Integral LessEqual (&FnName::Operator(SeperatorKind::LessEqual), Some(1), Some(1), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::LessEqual), Some(2), Some(2), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::LessEqual), Some(3), Some(3), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::LessEqual), Some(4), Some(4), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::LessEqual), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::LessEqual), Some(6), Some(6), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::LessEqual), Some(7), Some(7), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::LessEqual), Some(8), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 <= value1); } }, // Integral Great (&FnName::Operator(SeperatorKind::Great), Some(1), Some(1), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Great), Some(2), Some(2), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Great), Some(3), Some(3), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Great), Some(4), Some(4), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Great), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Great), Some(6), Some(6), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Great), Some(7), Some(7), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Great), Some(8), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 > value1); } }, // Integral Less (&FnName::Operator(SeperatorKind::Less), Some(1), Some(1), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Less), Some(2), Some(2), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Less), Some(3), Some(3), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Less), Some(4), Some(4), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Less), Some(5), Some(5), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Less), Some(6), Some(6), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Less), Some(7), Some(7), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Less), Some(8), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Int(value0), Int(value1)) => { return Bool(value0 < value1); } }, // Integral BitNot (&FnName::Operator(SeperatorKind::BitNot), Some(1), None, Some(ref param0), None) | (&FnName::Operator(SeperatorKind::BitNot), Some(2), None, Some(ref param0), None) | (&FnName::Operator(SeperatorKind::BitNot), Some(3), None, Some(ref param0), None) | (&FnName::Operator(SeperatorKind::BitNot), Some(4), None, Some(ref param0), None) | (&FnName::Operator(SeperatorKind::BitNot), Some(5), None, Some(ref param0), None) | (&FnName::Operator(SeperatorKind::BitNot), Some(6), None, Some(ref param0), None) | (&FnName::Operator(SeperatorKind::BitNot), Some(7), None, Some(ref param0), None) | (&FnName::Operator(SeperatorKind::BitNot), Some(8), None, Some(ref param0), None) => native_forward_1!{ param0, Int(value) => { return Int(!value); } }, // // Integral Increase // (&FnName::Operator(SeperatorKind::Increase), Some(1), None, Some(ref param0), None) // | (&FnName::Operator(SeperatorKind::Increase), Some(2), None, Some(ref param0), None) // | (&FnName::Operator(SeperatorKind::Increase), Some(3), None, Some(ref param0), None) // | (&FnName::Operator(SeperatorKind::Increase), Some(4), None, Some(ref param0), None) // | (&FnName::Operator(SeperatorKind::Increase), Some(5), None, Some(ref param0), None) // | (&FnName::Operator(SeperatorKind::Increase), Some(6), None, Some(ref param0), None) // | (&FnName::Operator(SeperatorKind::Increase), Some(7), None, Some(ref param0), None) // | (&FnName::Operator(SeperatorKind::Increase), Some(8), None, Some(ref param0), None) // => native_forward_mut_1!{ param0, &mut Int(ref mut value) => { *value += 1; return Unit; } }, // // Integral Decrease // (&FnName::Operator(SeperatorKind::Decrease), Some(1), None, Some(ref param0), None) // | (&FnName::Operator(SeperatorKind::Decrease), Some(2), None, Some(ref param0), None) // | (&FnName::Operator(SeperatorKind::Decrease), Some(3), None, Some(ref param0), None) // | (&FnName::Operator(SeperatorKind::Decrease), Some(4), None, Some(ref param0), None) // | (&FnName::Operator(SeperatorKind::Decrease), Some(5), None, Some(ref param0), None) // | (&FnName::Operator(SeperatorKind::Decrease), Some(6), None, Some(ref param0), None) // | (&FnName::Operator(SeperatorKind::Decrease), Some(7), None, Some(ref param0), None) // | (&FnName::Operator(SeperatorKind::Decrease), Some(8), None, Some(ref param0), None) // => native_forward_mut_1!{ param0, &mut Int(ref mut value) => { *value -= 1; return Unit; } }, // Integral Cast to integral (&FnName::Cast(1), Some(1), None, Some(ref param0), None) | (&FnName::Cast(2), Some(1), None, Some(ref param0), None) | (&FnName::Cast(3), Some(1), None, Some(ref param0), None) | (&FnName::Cast(4), Some(1), None, Some(ref param0), None) | (&FnName::Cast(5), Some(1), None, Some(ref param0), None) | (&FnName::Cast(6), Some(1), None, Some(ref param0), None) | (&FnName::Cast(7), Some(1), None, Some(ref param0), None) | (&FnName::Cast(8), Some(1), None, Some(ref param0), None) | (&FnName::Cast(1), Some(2), None, Some(ref param0), None) | (&FnName::Cast(2), Some(2), None, Some(ref param0), None) | (&FnName::Cast(3), Some(2), None, Some(ref param0), None) | (&FnName::Cast(4), Some(2), None, Some(ref param0), None) | (&FnName::Cast(5), Some(2), None, Some(ref param0), None) | (&FnName::Cast(6), Some(2), None, Some(ref param0), None) | (&FnName::Cast(7), Some(2), None, Some(ref param0), None) | (&FnName::Cast(8), Some(2), None, Some(ref param0), None) | (&FnName::Cast(1), Some(3), None, Some(ref param0), None) | (&FnName::Cast(2), Some(3), None, Some(ref param0), None) | (&FnName::Cast(3), Some(3), None, Some(ref param0), None) | (&FnName::Cast(4), Some(3), None, Some(ref param0), None) | (&FnName::Cast(5), Some(3), None, Some(ref param0), None) | (&FnName::Cast(6), Some(3), None, Some(ref param0), None) | (&FnName::Cast(7), Some(3), None, Some(ref param0), None) | (&FnName::Cast(8), Some(3), None, Some(ref param0), None) | (&FnName::Cast(1), Some(4), None, Some(ref param0), None) | (&FnName::Cast(2), Some(4), None, Some(ref param0), None) | (&FnName::Cast(3), Some(4), None, Some(ref param0), None) | (&FnName::Cast(4), Some(4), None, Some(ref param0), None) | (&FnName::Cast(5), Some(4), None, Some(ref param0), None) | (&FnName::Cast(6), Some(4), None, Some(ref param0), None) | (&FnName::Cast(7), Some(4), None, Some(ref param0), None) | (&FnName::Cast(8), Some(4), None, Some(ref param0), None) | (&FnName::Cast(1), Some(5), None, Some(ref param0), None) | (&FnName::Cast(2), Some(5), None, Some(ref param0), None) | (&FnName::Cast(3), Some(5), None, Some(ref param0), None) | (&FnName::Cast(4), Some(5), None, Some(ref param0), None) | (&FnName::Cast(5), Some(5), None, Some(ref param0), None) | (&FnName::Cast(6), Some(5), None, Some(ref param0), None) | (&FnName::Cast(7), Some(5), None, Some(ref param0), None) | (&FnName::Cast(8), Some(5), None, Some(ref param0), None) | (&FnName::Cast(1), Some(6), None, Some(ref param0), None) | (&FnName::Cast(2), Some(6), None, Some(ref param0), None) | (&FnName::Cast(3), Some(6), None, Some(ref param0), None) | (&FnName::Cast(4), Some(6), None, Some(ref param0), None) | (&FnName::Cast(5), Some(6), None, Some(ref param0), None) | (&FnName::Cast(6), Some(6), None, Some(ref param0), None) | (&FnName::Cast(7), Some(6), None, Some(ref param0), None) | (&FnName::Cast(8), Some(6), None, Some(ref param0), None) | (&FnName::Cast(1), Some(7), None, Some(ref param0), None) | (&FnName::Cast(2), Some(7), None, Some(ref param0), None) | (&FnName::Cast(3), Some(7), None, Some(ref param0), None) | (&FnName::Cast(4), Some(7), None, Some(ref param0), None) | (&FnName::Cast(5), Some(7), None, Some(ref param0), None) | (&FnName::Cast(6), Some(7), None, Some(ref param0), None) | (&FnName::Cast(7), Some(7), None, Some(ref param0), None) | (&FnName::Cast(8), Some(7), None, Some(ref param0), None) | (&FnName::Cast(1), Some(8), None, Some(ref param0), None) | (&FnName::Cast(2), Some(8), None, Some(ref param0), None) | (&FnName::Cast(3), Some(8), None, Some(ref param0), None) | (&FnName::Cast(4), Some(8), None, Some(ref param0), None) | (&FnName::Cast(5), Some(8), None, Some(ref param0), None) | (&FnName::Cast(6), Some(8), None, Some(ref param0), None) | (&FnName::Cast(7), Some(8), None, Some(ref param0), None) | (&FnName::Cast(8), Some(8), None, Some(ref param0), None) => native_forward_1!{ param0, Int(value) => { return Int(value); } }, // Integral cast to float (&FnName::Cast(10), Some(1), None, Some(ref param0), None) | (&FnName::Cast(10), Some(2), None, Some(ref param0), None) | (&FnName::Cast(10), Some(3), None, Some(ref param0), None) | (&FnName::Cast(10), Some(4), None, Some(ref param0), None) | (&FnName::Cast(10), Some(5), None, Some(ref param0), None) | (&FnName::Cast(10), Some(6), None, Some(ref param0), None) | (&FnName::Cast(10), Some(7), None, Some(ref param0), None) | (&FnName::Cast(10), Some(8), None, Some(ref param0), None) => native_forward_1!{ param0, Int(value) => { return Float(value as f64); } }, // Float Add (&FnName::Operator(SeperatorKind::Add), Some(9), Some(9), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Add), Some(10), Some(10), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Float(value0 + value1); } }, (&FnName::Operator(SeperatorKind::Sub), Some(9), Some(9), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Sub), Some(10), Some(10), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Float(value0 - value1); } }, (&FnName::Operator(SeperatorKind::Mul), Some(9), Some(9), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Mul), Some(10), Some(10), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Float(value0 * value1); } }, (&FnName::Operator(SeperatorKind::Div), Some(9), Some(9), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Div), Some(10), Some(10), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Float(value0 / value1); } }, // Float Compare (&FnName::Operator(SeperatorKind::Equal), Some(9), Some(9), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Equal), Some(10), Some(10), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 == value1); } }, (&FnName::Operator(SeperatorKind::NotEqual), Some(9), Some(9), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::NotEqual), Some(10), Some(10), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 != value1); } }, (&FnName::Operator(SeperatorKind::GreatEqual), Some(9), Some(9), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::GreatEqual), Some(10), Some(10), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 >= value1); } }, (&FnName::Operator(SeperatorKind::LessEqual), Some(9), Some(9), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::LessEqual), Some(10), Some(10), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 <= value1); } }, (&FnName::Operator(SeperatorKind::Great), Some(9), Some(9), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Great), Some(10), Some(10), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 > value1); } }, (&FnName::Operator(SeperatorKind::Less), Some(9), Some(9), Some(ref param0), Some(ref param1)) | (&FnName::Operator(SeperatorKind::Less), Some(10), Some(10), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Float(value0), Float(value1)) => { return Bool(value0 < value1); } }, // Float cast to float (&FnName::Cast(9), Some(9), None, Some(ref param0), None) | (&FnName::Cast(10), Some(9), None, Some(ref param0), None) | (&FnName::Cast(9), Some(10), None, Some(ref param0), None) | (&FnName::Cast(10), Some(10), None, Some(ref param0), None) => native_forward_1!{ param0, Float(value) => { return Float(value); } }, // Float cast to integral (&FnName::Cast(8), Some(9), None, Some(ref param0), None) | (&FnName::Cast(8), Some(10), None, Some(ref param0), None) => native_forward_1!{ param0, Float(value) => { return Int(value as u64); } }, // Char Compare (&FnName::Operator(SeperatorKind::Equal), Some(11), Some(11), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 == value1); } }, (&FnName::Operator(SeperatorKind::NotEqual), Some(11), Some(11), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 != value1); } }, (&FnName::Operator(SeperatorKind::GreatEqual), Some(11), Some(11), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 >= value1); } }, (&FnName::Operator(SeperatorKind::LessEqual), Some(11), Some(11), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 <= value1); } }, (&FnName::Operator(SeperatorKind::Great), Some(11), Some(11), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 > value1); } }, (&FnName::Operator(SeperatorKind::Less), Some(11), Some(11), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Char(value0), Char(value1)) => { return Bool(value0 < value1); } }, // Char cast (&FnName::Cast(6), Some(11), None, Some(ref param0), None) => native_forward_1!{ param0, Char(value) => { return RuntimeValue::Int(value as u64); } }, // Bool (&FnName::Operator(SeperatorKind::Equal), Some(12), Some(12), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Bool(value0), Bool(value1)) => { return Bool(value0 == value1); } }, (&FnName::Operator(SeperatorKind::NotEqual), Some(12), Some(12), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Bool(value0), Bool(value1)) => { return Bool(value0 != value1); } }, (&FnName::Operator(SeperatorKind::LogicalAnd), Some(12), Some(12), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Bool(value0), Bool(value1)) => { return Bool(value0 && value1); } }, (&FnName::Operator(SeperatorKind::LogicalOr), Some(12), Some(12), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Bool(value0), Bool(value1)) => { return Bool(value0 || value1); } }, (&FnName::Operator(SeperatorKind::LogicalNot), Some(12), None, Some(ref param0), None) => native_forward_1!{ param0, Bool(value) => { return Bool(!value); } }, // Str (&FnName::Operator(SeperatorKind::Add), Some(13), Some(13), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Str(value0), Str(value1)) => { return Str(value0 + &value1); } }, (&FnName::Operator(SeperatorKind::Equal), Some(13), Some(13), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Str(value0), Str(value1)) => { return Bool(value0 == value1); } }, (&FnName::Operator(SeperatorKind::NotEqual), Some(13), Some(13), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Str(value0), Str(value1)) => { return Bool(value0 != value1); } }, // Special ident dispatcher (&FnName::Ident(ref ident_name), param_type0, param_type1, param0, param1) => match (ident_name.as_ref(), param_type0, param_type1, param0, param1) { // Integral is_odd ("is_odd", Some(1), None, Some(ref param0), None) | ("is_odd", Some(2), None, Some(ref param0), None) | ("is_odd", Some(3), None, Some(ref param0), None) | ("is_odd", Some(4), None, Some(ref param0), None) | ("is_odd", Some(5), None, Some(ref param0), None) | ("is_odd", Some(6), None, Some(ref param0), None) | ("is_odd", Some(7), None, Some(ref param0), None) | ("is_odd", Some(8), None, Some(ref param0), None) => native_forward_1!{ param0, Int(value) => { return Bool((value & 1) == 0); } }, // Integral to_string ("to_string", Some(1), None, Some(ref param0), None) | ("to_string", Some(2), None, Some(ref param0), None) | ("to_string", Some(3), None, Some(ref param0), None) | ("to_string", Some(4), None, Some(ref param0), None) | ("to_string", Some(5), None, Some(ref param0), None) | ("to_string", Some(6), None, Some(ref param0), None) | ("to_string", Some(7), None, Some(ref param0), None) | ("to_string", Some(8), None, Some(ref param0), None) => native_forward_1!{ param0, Int(value) => { return Str(format!("{}", value)); } }, // Float to_string ("to_string", Some(9), None, Some(ref param0), None) | ("to_string", Some(10), None, Some(ref param0), None) => native_forward_1!{ param0, Float(value) => { return Str(format!("{}", value)); } }, // Char to_string ("to_string", Some(11), None, Some(ref param0), None) => native_forward_1!{ param0, Char(value) => { return Str(format!("{}", value)); } }, // String ("length", Some(13), None, Some(ref param0), None) => native_forward_1!{ param0, Str(value) => { return Int(value.len() as u64); } }, ("get_index", Some(13), Some(5), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Str(value0), Int(value1)) => { return Char(value0.chars().nth(value1 as usize).unwrap()); } }, ("get_index", Some(13), Some(8), Some(ref param0), Some(ref param1)) => native_forward_2!{ param0, param1, (Str(value0), Int(value1)) => { return Char(value0.chars().nth(value1 as usize).unwrap()); } }, (_, _, _, _, _) => (), }, (_, _, _, _, _) => (), } // Builtin template type global if let &FnName::Ident(ref fn_name) = &fn_name { if fn_name == "?new_tuple" { // ?new_tuple(aaa, bbb, ccc) -> (aaa, bbb, ccc) let mut rt_values = Vec::new(); for param in params { rt_values.push(rt.index(param)); } return RuntimeValue::Tuple(rt_values); } else if fn_name == "?new_array" { // ?new_array(value, size) -> [value] // Currently 5 and 8 are all 8 at runtime, no more need to check if let RuntimeValue::Int(item_init_size) = rt.index(&params[1]) { let item_init_value = rt.index(&params[0]); let mut array_items = Vec::new(); for _ in 0..item_init_size { array_items.push(item_init_value.clone()); } return RuntimeValue::ArrayRef(rt.allocate_heap(RuntimeValue::Array(array_items))); } } else if str_begin_with(fn_name, "?new_array_") { // ?new_array_xxx() -> [xxx] return RuntimeValue::ArrayRef(rt.allocate_heap(RuntimeValue::Array(Vec::new()))); } else if str_begin_with(fn_name, "set_item") { let mut temp_id_str = String::new(); for i in 8..fn_name.len() { temp_id_str.push(fn_name.chars().nth(i).unwrap()); } let item_id = usize::from_str(&temp_id_str).unwrap(); if params.len() == 2 { let new_value = rt.index(&params[1]); match rt.index_mut(&params[0]) { &mut RuntimeValue::Tuple(ref mut items) => { items[item_id] = new_value; return RuntimeValue::Unit; } _ => unreachable!() } } else { unreachable!() } } } // Builtin template type instance if let Some(real_typeid) = prep_param_type(&param_types, 0) { match types.get_by_idx(real_typeid) { &Type::Base(_) => unreachable!(), &Type::Array(_item_real_typeid) => { match (&fn_name, prep_param_type(&param_types, 0), prep_param_type(&param_types, 1), prep_param_type(&param_types, 2), prep_param(&params, 0), prep_param(&params, 1), prep_param(&params, 2)) { (&FnName::Operator(SeperatorKind::Equal), _, _, _, Some(ref param0), Some(ref param1), None) => { match (rt.index(param0), rt.index(param1)) { (RuntimeValue::ArrayRef(heap_index1), RuntimeValue::ArrayRef(heap_index2)) => { let (array1_clone, array2_clone) = match (&rt.heap[heap_index1], &rt.heap[heap_index2]) { (&RuntimeValue::Array(ref array1), &RuntimeValue::Array(ref array2)) => (array1.clone(), array2.clone()), _ => unreachable!(), }; if array1_clone.len() != array2_clone.len() { return RuntimeValue::Bool(false); } else { let mut ret_val = true; for i in 0..array1_clone.len() { ret_val = ret_val && (array1_clone[i] == array2_clone[i]); // because cannot decide part of heap's operand, that's all } return RuntimeValue::Bool(ret_val); } } _ => unreachable!() } } (&FnName::Operator(SeperatorKind::NotEqual), _, _, _, Some(ref param0), Some(ref param1), None) => { match (rt.index(param0), rt.index(param1)) { (RuntimeValue::ArrayRef(heap_index1), RuntimeValue::ArrayRef(heap_index2)) => { let (array1_clone, array2_clone) = match (&rt.heap[heap_index1], &rt.heap[heap_index2]) { (&RuntimeValue::Array(ref array1), &RuntimeValue::Array(ref array2)) => (array1.clone(), array2.clone()), _ => unreachable!(), }; if array1_clone.len() != array2_clone.len() { return RuntimeValue::Bool(true); } else { let mut ret_val = false; for i in 0..array1_clone.len() { ret_val = ret_val || (array1_clone[i] != array2_clone[i]); } return RuntimeValue::Bool(ret_val); } } _ => unreachable!() } } (&FnName::Ident(ref ident_name), param_type0, param_type1, param_type2, param0, param1, param2) => match (ident_name.as_ref(), param_type0, param_type1, param_type2, param0, param1, param2) { ("set_index", _, Some(5), _, Some(ref param0), Some(ref param1), Some(ref param2)) | ("set_index", _, Some(8), _, Some(ref param0), Some(ref param1), Some(ref param2)) => { match (rt.index(param0), rt.index(param1), rt.index(param2)) { (RuntimeValue::ArrayRef(heap_index), RuntimeValue::Int(array_index), new_value) => { match &mut rt.heap[heap_index as usize] { &mut RuntimeValue::Array(ref mut array) => { array[array_index as usize] = new_value.clone(); return RuntimeValue::Unit; } _ => unreachable!() } } _ => unreachable!() } } ("get_index", _, Some(5), None, Some(ref param0), Some(ref param1), None) | ("get_index", _, Some(8), None, Some(ref param0), Some(ref param1), None) => { match (rt.index(param0), rt.index(param1)) { (RuntimeValue::ArrayRef(heap_index), RuntimeValue::Int(array_index)) => { match &mut rt.heap[heap_index as usize] { &mut RuntimeValue::Array(ref mut array) => return array[array_index as usize].clone(), _ => unreachable!() } } _ => unreachable!() } } ("push", _, _, None, Some(ref param0), Some(ref param1), None) => { match (rt.index(param0), rt.index(param1)) { (RuntimeValue::ArrayRef(heap_index), new_value) => { match &mut rt.heap[heap_index as usize] { &mut RuntimeValue::Array(ref mut array) => { array.push(new_value.clone()); return RuntimeValue::Unit; } _ => unreachable!() } } _ => unreachable!() } } ("pop", _, None, None, Some(ref param0), None, None) => { match rt.index(param0) { RuntimeValue::ArrayRef(heap_index) => { match &mut rt.heap[heap_index as usize] { &mut RuntimeValue::Array(ref mut array) => return array.pop().unwrap(), _ => unreachable!() } } _ => unreachable!() } } ("length", _, None, None, Some(ref param0), None, None) => { match rt.index(param0) { RuntimeValue::ArrayRef(heap_index) => { match &mut rt.heap[heap_index as usize] { &mut RuntimeValue::Array(ref mut array) => return RuntimeValue::Int(array.len() as u64), _ => unreachable!() } } _ => unreachable!() } } _ => unreachable!(), }, _ => unreachable!(), } } &Type::Tuple(ref _item_real_typeids) => { match (&fn_name, prep_param_type(&param_types, 0), prep_param_type(&param_types, 1), prep_param(&params, 0), prep_param(&params, 1)) { (&FnName::Operator(SeperatorKind::Equal), _, _, Some(ref param0), Some(ref param1)) => { match (rt.index(param0), rt.index(param1)) { (RuntimeValue::Tuple(values1), RuntimeValue::Tuple(values2)) => { let mut ret_val = true; for i in 0..values1.len() { ret_val = ret_val && values1[i] == values2[i]; } return RuntimeValue::Bool(ret_val); } _ => unreachable!() } } (&FnName::Operator(SeperatorKind::NotEqual), _, _, Some(ref param0), Some(ref param1)) => { match (rt.index(param0), rt.index(param1)) { (RuntimeValue::Tuple(values1), RuntimeValue::Tuple(values2)) => { let mut ret_val = false; for i in 0..values1.len() { ret_val = ret_val || values1[i] != values2[i]; } return RuntimeValue::Bool(ret_val); } _ => unreachable!() } } _ => unreachable!() } } } } unreachable!() }
true