{ // 获取包含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#[derive(Template)]\n#[template(path = \"teams.html\")]\nstruct Teams {\n year: u16,\n teams: Vec,\n}\n\nstruct Team {\n name: String,\n score: u8,\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":128,"cells":{"blob_id":{"kind":"string","value":"56fda6a82c3e79e7d839680c73599d4e831c27a0"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Jaxelr/RustTutorial"},"path":{"kind":"string","value":"/Rust Cookbook/12_01_1_read_and_write_files/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1491,"string":"1,491"},"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 std::fs::File;\nuse same_file::Handle;\nuse memmap::Mmap;\nuse std::io::{Write, BufReader, BufRead, Error, ErrorKind};\nuse std::path::Path;\n\nfn main() -> Result<(), Box > {\n read_write_file()?;\n same_file()?;\n random_memory()?;\n\n Ok(())\n}\n\nfn read_write_file() -> Result<(), Error> {\n let path = \"lines.txt\";\n\n let mut output = File::create(path)?;\n write!(output, \"Rust\\n💖\\nFun\")?;\n\n let input = File::open(path)?;\n let buffered = BufReader::new(input);\n\n for line in buffered.lines() {\n println!(\"{}\", line?);\n }\n\n Ok(())\n}\n\nfn same_file() -> Result<(), Error> {\n let path_to_read = Path::new(\"new.txt\");\n\n let stdout_handle = Handle::stdout()?;\n let handle = Handle::from_path(path_to_read)?;\n\n if stdout_handle == handle {\n return Err(Error::new(\n ErrorKind::Other,\n \"You are reading and writing to the same file\",\n ));\n } else {\n let file = File::open(&path_to_read)?;\n let file = BufReader::new(file);\n for (num, line) in file.lines().enumerate() {\n println!(\"{} : {}\", num, line?.to_uppercase());\n }\n }\n\n Ok(())\n}\n\nfn random_memory() -> Result<(), Error> {\n let file = File::open(\"content.txt\")?;\n let map = unsafe { Mmap::map(&file)? };\n\n let random_indexes = [0, 1, 2, 19, 22, 10, 11, 29];\n let _random_bytes: Vec = random_indexes.iter()\n .map(|&idx| map[idx])\n .collect();\n Ok(())\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":129,"cells":{"blob_id":{"kind":"string","value":"16d2253599b3a1fa9c3ec0e7e1a316a4ba3b4b27"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"modelflat/twitchbot"},"path":{"kind":"string","value":"/src/state.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1414,"string":"1,414"},"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 async_std::sync::RwLock;\nuse std::collections::{BTreeSet, HashMap};\n\nuse crate::executor::ShareableExecutableCommand;\nuse crate::irc;\nuse crate::permissions::PermissionList;\n\npub type Commands = HashMap>;\n\npub struct BotState {\n pub username: String,\n pub prefix: String,\n pub channels: BTreeSet,\n pub commands: Commands,\n pub permissions: PermissionList,\n pub data: RwLock,\n}\n\nimpl BotState {\n pub fn new(\n username: String,\n prefix: String,\n channels: Vec,\n commands: Commands,\n permissions: PermissionList,\n data: T,\n ) -> BotState {\n BotState {\n username,\n prefix,\n channels: channels.into_iter().map(|s| s.to_string()).collect(),\n commands,\n permissions,\n data: RwLock::new(data),\n }\n }\n\n pub fn try_convert_to_command(&self, message: &irc::Message) -> Option {\n if let Some(s) = message.trailing {\n if s.starts_with(&self.prefix) {\n return Some((&s[self.prefix.len()..]).trim_start().to_string());\n }\n if s.starts_with(&self.username) {\n return Some((&s[self.username.len()..]).trim_start().to_string());\n }\n }\n None\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":130,"cells":{"blob_id":{"kind":"string","value":"07bc5a3bb6501e0fabcb458956b399a89779f61e"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"tertsdiepraam/vrp"},"path":{"kind":"string","value":"/vrp-core/src/models/common/load.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":8491,"string":"8,491"},"score":{"kind":"number","value":3.09375,"string":"3.09375"},"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":"#[cfg(test)]\n#[path = \"../../../tests/unit/models/domain/load_test.rs\"]\nmod load_test;\n\nuse crate::models::common::{Dimensions, ValueDimension};\nuse std::cmp::Ordering;\nuse std::iter::Sum;\nuse std::ops::{Add, Mul, Sub};\n\nconst CAPACITY_DIMENSION_KEY: &str = \"cpc\";\nconst DEMAND_DIMENSION_KEY: &str = \"dmd\";\nconst LOAD_DIMENSION_SIZE: usize = 8;\n\n/// Represents a load type used to represent customer's demand or vehicle's load.\npub trait Load: Add + Sub + Ord + Copy + Default + Send + Sync {\n /// Returns true if it represents an empty load.\n fn is_not_empty(&self) -> bool;\n\n /// Returns max load value.\n fn max_load(self, other: Self) -> Self;\n\n /// Returns true if `other` can be loaded into existing capacity.\n fn can_fit(&self, other: &Self) -> bool;\n\n /// Returns ratio.\n fn ratio(&self, other: &Self) -> f64;\n}\n\n/// Represents job demand, both static and dynamic.\npub struct Demand + Sub + 'static> {\n /// Keeps static and dynamic pickup amount.\n pub pickup: (T, T),\n /// Keeps static and dynamic delivery amount.\n pub delivery: (T, T),\n}\n\n/// A trait to get or set vehicle's capacity.\npub trait CapacityDimension + Sub + 'static> {\n /// Sets capacity.\n fn set_capacity(&mut self, demand: T) -> &mut Self;\n /// Gets capacity.\n fn get_capacity(&self) -> Option<&T>;\n}\n\n/// A trait to get or set demand.\npub trait DemandDimension + Sub + 'static> {\n /// Sets demand.\n fn set_demand(&mut self, demand: Demand) -> &mut Self;\n /// Gets demand.\n fn get_demand(&self) -> Option<&Demand>;\n}\n\nimpl + Sub + 'static> Demand {\n /// Returns capacity change as difference between pickup and delivery.\n pub fn change(&self) -> T {\n self.pickup.0 + self.pickup.1 - self.delivery.0 - self.delivery.1\n }\n}\n\nimpl + Sub + 'static> Default for Demand {\n fn default() -> Self {\n Self { pickup: (Default::default(), Default::default()), delivery: (Default::default(), Default::default()) }\n }\n}\n\nimpl + Sub + 'static> Clone for Demand {\n fn clone(&self) -> Self {\n Self { pickup: self.pickup, delivery: self.delivery }\n }\n}\n\nimpl + Sub + 'static> CapacityDimension for Dimensions {\n fn set_capacity(&mut self, demand: T) -> &mut Self {\n self.set_value(CAPACITY_DIMENSION_KEY, demand);\n self\n }\n\n fn get_capacity(&self) -> Option<&T> {\n self.get_value(CAPACITY_DIMENSION_KEY)\n }\n}\n\nimpl + Sub + 'static> DemandDimension for Dimensions {\n fn set_demand(&mut self, demand: Demand) -> &mut Self {\n self.set_value(DEMAND_DIMENSION_KEY, demand);\n self\n }\n\n fn get_demand(&self) -> Option<&Demand> {\n self.get_value(DEMAND_DIMENSION_KEY)\n }\n}\n\n/// Specifies single dimensional load type.\n#[derive(Clone, Copy, Debug)]\npub struct SingleDimLoad {\n /// An actual load value.\n pub value: i32,\n}\n\nimpl SingleDimLoad {\n /// Creates a new instance of `SingleDimLoad`.\n pub fn new(value: i32) -> Self {\n Self { value }\n }\n}\n\nimpl Default for SingleDimLoad {\n fn default() -> Self {\n Self { value: 0 }\n }\n}\n\nimpl Load for SingleDimLoad {\n fn is_not_empty(&self) -> bool {\n self.value != 0\n }\n\n fn max_load(self, other: Self) -> Self {\n let value = self.value.max(other.value);\n Self { value }\n }\n\n fn can_fit(&self, other: &Self) -> bool {\n self.value >= other.value\n }\n\n fn ratio(&self, other: &Self) -> f64 {\n self.value as f64 / other.value as f64\n }\n}\n\nimpl Add for SingleDimLoad {\n type Output = Self;\n\n fn add(self, rhs: Self) -> Self::Output {\n let value = self.value + rhs.value;\n Self { value }\n }\n}\n\nimpl Sub for SingleDimLoad {\n type Output = Self;\n\n fn sub(self, rhs: Self) -> Self::Output {\n let value = self.value - rhs.value;\n Self { value }\n }\n}\n\nimpl Ord for SingleDimLoad {\n fn cmp(&self, other: &Self) -> Ordering {\n self.value.cmp(&other.value)\n }\n}\n\nimpl PartialOrd for SingleDimLoad {\n fn partial_cmp(&self, other: &Self) -> Option {\n Some(self.cmp(other))\n }\n}\n\nimpl Eq for SingleDimLoad {}\n\nimpl PartialEq for SingleDimLoad {\n fn eq(&self, other: &Self) -> bool {\n self.cmp(other) == Ordering::Equal\n }\n}\n\nimpl Mul for SingleDimLoad {\n type Output = Self;\n\n fn mul(self, value: f64) -> Self::Output {\n Self::new((self.value as f64 * value).round() as i32)\n }\n}\n\n/// Specifies multi dimensional load type.\n#[derive(Clone, Copy, Debug)]\npub struct MultiDimLoad {\n /// Load data.\n pub load: [i32; LOAD_DIMENSION_SIZE],\n /// Actual used size.\n pub size: usize,\n}\n\nimpl MultiDimLoad {\n /// Creates a new instance of `MultiDimLoad`.\n pub fn new(data: Vec) -> Self {\n assert!(data.len() <= LOAD_DIMENSION_SIZE);\n\n let mut load = [0; LOAD_DIMENSION_SIZE];\n for (idx, value) in data.iter().enumerate() {\n load[idx] = *value;\n }\n\n Self { load, size: data.len() }\n }\n\n fn get(&self, idx: usize) -> i32 {\n self.load[idx]\n }\n\n /// Converts to vector representation.\n pub fn as_vec(&self) -> Vec {\n if self.size == 0 {\n vec![0]\n } else {\n self.load[..self.size].to_vec()\n }\n }\n}\n\nimpl Load for MultiDimLoad {\n fn is_not_empty(&self) -> bool {\n self.size == 0 || self.load.iter().any(|v| *v != 0)\n }\n\n fn max_load(self, other: Self) -> Self {\n let mut result = self;\n result.load.iter_mut().zip(other.load.iter()).for_each(|(a, b)| *a = (*a).max(*b));\n\n result\n }\n\n fn can_fit(&self, other: &Self) -> bool {\n self.load.iter().zip(other.load.iter()).all(|(a, b)| a >= b)\n }\n\n fn ratio(&self, other: &Self) -> f64 {\n self.load.iter().zip(other.load.iter()).fold(0., |acc, (a, b)| (*a as f64 / *b as f64).max(acc))\n }\n}\n\nimpl Default for MultiDimLoad {\n fn default() -> Self {\n Self { load: [0; LOAD_DIMENSION_SIZE], size: 0 }\n }\n}\n\nimpl Add for MultiDimLoad {\n type Output = Self;\n\n fn add(self, rhs: Self) -> Self::Output {\n fn sum(acc: MultiDimLoad, rhs: &MultiDimLoad) -> MultiDimLoad {\n let mut dimens = acc;\n\n for (idx, value) in rhs.load.iter().enumerate() {\n dimens.load[idx] += *value;\n }\n\n dimens.size = dimens.size.max(rhs.size);\n\n dimens\n }\n\n if self.load.len() >= rhs.load.len() {\n sum(self, &rhs)\n } else {\n sum(rhs, &self)\n }\n }\n}\n\nimpl Sub for MultiDimLoad {\n type Output = Self;\n\n fn sub(self, rhs: Self) -> Self::Output {\n let mut dimens = self;\n\n for (idx, value) in rhs.load.iter().enumerate() {\n dimens.load[idx] -= *value;\n }\n\n dimens.size = dimens.size.max(rhs.size);\n\n dimens\n }\n}\n\nimpl Ord for MultiDimLoad {\n fn cmp(&self, other: &Self) -> Ordering {\n let size = self.load.len().max(other.load.len());\n (0..size).fold(Ordering::Equal, |acc, idx| match acc {\n Ordering::Greater => Ordering::Greater,\n Ordering::Equal => self.get(idx).cmp(&other.get(idx)),\n Ordering::Less => {\n if self.get(idx) > other.get(idx) {\n Ordering::Greater\n } else {\n Ordering::Less\n }\n }\n })\n }\n}\n\nimpl PartialOrd for MultiDimLoad {\n fn partial_cmp(&self, other: &Self) -> Option {\n Some(self.cmp(other))\n }\n}\n\nimpl Eq for MultiDimLoad {}\n\nimpl PartialEq for MultiDimLoad {\n fn eq(&self, other: &Self) -> bool {\n self.cmp(other) == Ordering::Equal\n }\n}\n\nimpl Mul for MultiDimLoad {\n type Output = Self;\n\n fn mul(self, value: f64) -> Self::Output {\n let mut dimens = self;\n\n dimens.load.iter_mut().for_each(|item| {\n *item = (*item as f64 * value).round() as i32;\n });\n\n dimens\n }\n}\n\nimpl Sum for MultiDimLoad {\n fn sum>(iter: I) -> Self {\n iter.fold(MultiDimLoad::default(), |acc, item| item + acc)\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":131,"cells":{"blob_id":{"kind":"string","value":"99dbc187a9b4dcacd3a9134ed884b8a22db1d95f"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"dpchamps/rust-exercism"},"path":{"kind":"string","value":"/raindrops/src/lib.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":459,"string":"459"},"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":"pub fn raindrops(n: u32) -> String {\n let result = vec![3, 5, 7].iter().fold(String::new(), |str, factor| {\n if n % factor != 0 {\n return str;\n }\n\n let noise = match factor {\n 3 => \"Pling\",\n 5 => \"Plang\",\n 7 => \"Plong\",\n _ => unreachable!(),\n };\n\n format!(\"{}{}\", str, noise)\n });\n\n if &result == \"\" {\n n.to_string()\n } else {\n result\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":132,"cells":{"blob_id":{"kind":"string","value":"7104fc0ed3eb38c354b90eb680965622f46fc511"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"RedEyedMars/AutoClaw"},"path":{"kind":"string","value":"/src/game/entities/combat.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5528,"string":"5,528"},"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 crate::game::battle::system::movement::MovementPath;\nuse crate::game::entities::skills::Skill;\nuse crate::game::entities::traits::TraitId;\nuse crate::game::entities::{Change, Entity, Idable, State};\nuse crate::game::{Event, Events, GameParts};\nuse generational_arena::Index;\n\n#[derive(Debug, Clone, Copy)]\npub enum CombatStance {\n FindingTarget,\n MovingCloser(Index, MovementPath),\n UsingSkill(Skill, Index),\n}\n\nimpl CombatStance {\n pub fn pump<'a>(&self, entity: &Entity, parts: &GameParts, events: &mut Events) {\n if let Some(board) = parts.get_board() {\n match self {\n CombatStance::FindingTarget => {\n if let Some(target) = board.get_target(entity, parts) {\n events.push(\n 2,\n Event::ChangeEntity(\n entity.id(),\n Change::State(State::Fighting {\n stance: CombatStance::UsingSkill(target.1, target.0.id()),\n }),\n ),\n );\n } else {\n if entity.has_trait(&TraitId::Priest) {\n if let Some(target) = board.get_closest_ally(entity.id(), parts) {\n events.push(\n 3,\n Event::ChangeEntity(\n entity.id(),\n Change::State(State::Fighting {\n stance: CombatStance::MovingCloser(\n target,\n board.get_path_to_target(\n entity.id(),\n target,\n parts,\n ),\n ),\n }),\n ),\n );\n }\n } else {\n if let Some(target) = board.get_closest_enemy(entity.id(), parts) {\n events.push(\n 3,\n Event::ChangeEntity(\n entity.id(),\n Change::State(State::Fighting {\n stance: CombatStance::MovingCloser(\n target,\n board.get_path_to_target(\n entity.id(),\n target,\n parts,\n ),\n ),\n }),\n ),\n );\n }\n }\n }\n }\n CombatStance::UsingSkill(skill, target) => {\n skill.act(parts, events, entity.id(), *target);\n events.push(\n 2,\n Event::ChangeEntity(\n entity.id(),\n Change::State(State::Fighting {\n stance: CombatStance::FindingTarget,\n }),\n ),\n );\n }\n CombatStance::MovingCloser(target, path) => {\n if let Some(new_path) = board.move_entity(entity.id(), path, events) {\n events.push(\n 2,\n Event::ChangeEntity(\n entity.id(),\n Change::State(State::Fighting {\n stance: CombatStance::MovingCloser(*target, new_path),\n }),\n ),\n );\n } else {\n if let Some(target) = board.get_target(entity, parts) {\n events.push(\n 2,\n Event::ChangeEntity(\n entity.id(),\n Change::State(State::Fighting {\n stance: CombatStance::UsingSkill(target.1, target.0.id()),\n }),\n ),\n );\n } else {\n events.push(\n 2,\n Event::ChangeEntity(\n entity.id(),\n Change::State(State::Fighting {\n stance: CombatStance::FindingTarget,\n }),\n ),\n );\n }\n }\n }\n }\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":133,"cells":{"blob_id":{"kind":"string","value":"5d5ec2b359cb4beaa13d08839ba6057d8492bd46"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"mkeeter/advent-of-code"},"path":{"kind":"string","value":"/2021/15/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2164,"string":"2,164"},"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 std::cmp::Reverse;\nuse std::collections::BinaryHeap;\nuse std::io::BufRead;\n\n#[derive(Ord, PartialOrd, Eq, PartialEq)]\nstruct Task {\n score: Reverse,\n pos: (usize, usize),\n}\n\nstruct Tile {\n weight: usize,\n score: Option,\n}\n\nfn search(map: &[Vec]) -> usize {\n let mut map: Vec> = map\n .iter()\n .map(|row| {\n row.iter()\n .map(|weight| Tile {\n weight: *weight as usize,\n score: None,\n })\n .collect()\n })\n .collect();\n\n let mut todo = BinaryHeap::new();\n todo.push(Task {\n score: Reverse(0),\n pos: (0, 0),\n });\n\n let xmax = map[0].len() as i64 - 1;\n let ymax = map.len() as i64 - 1;\n\n while let Some(task) = todo.pop() {\n let (x, y) = task.pos;\n let tile = &mut map[y][x];\n if let Some(s) = tile.score {\n assert!(s <= task.score.0);\n continue;\n }\n tile.score = Some(task.score.0);\n\n for (dx, dy) in &[(-1, 0), (1, 0), (0, 1), (0, -1)] {\n let (x, y) = (x as i64 + dx, y as i64 + dy);\n if x < 0 || y < 0 || x > xmax || y > ymax {\n continue;\n }\n let (x, y) = (x as usize, y as usize);\n todo.push(Task {\n score: Reverse(task.score.0 + map[y][x].weight),\n pos: (x, y),\n });\n }\n }\n map[ymax as usize][ymax as usize].score.unwrap()\n}\n\nfn main() {\n let minimap = std::io::stdin()\n .lock()\n .lines()\n .map(|line| line.unwrap().bytes().map(|c| c - b'0').collect())\n .collect::>>();\n\n println!(\"Part 1: {}\", search(&minimap));\n\n let xsize = minimap[0].len();\n let ysize = minimap.len();\n let mut megamap = vec![vec![0; xsize * 5]; xsize * 5];\n for (y, row) in megamap.iter_mut().enumerate() {\n for (x, c) in row.iter_mut().enumerate() {\n let risk = minimap[y % ysize][x % xsize];\n *c = ((risk + (x / xsize + y / ysize) as u8 - 1) % 9) + 1;\n }\n }\n println!(\"Part 2: {}\", search(&megamap));\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":134,"cells":{"blob_id":{"kind":"string","value":"2767ab826e2d1bf764a4c81631511d7641d4c003"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Deskbot/Advent-of-Code-2020"},"path":{"kind":"string","value":"/src/day/day07.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5480,"string":"5,480"},"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":"use std::collections::HashMap;\nuse std::fs;\nuse substring::Substring;\n\n#[derive(std::fmt::Debug)]\nstruct Rule<'a> (i32, &'a str);\n\npub fn day07() {\n let file = fs::read_to_string(\"input/day07.txt\").expect(\"input not found\");\n\n println!(\"Part 1: {}\", part1(&file));\n println!(\"Part 2: {}\", part2(&file));\n}\n\nfn part1(input: &str) -> i32 {\n let bag_to_rules = parse_input(input);\n\n let mut contains_golden = HashMap::new() as HashMap<&str, bool>;\n\n for &bag in bag_to_rules.keys() {\n let bag_deep_contains_golden = must_contain(bag, &bag_to_rules, &contains_golden);\n contains_golden.insert(bag, bag_deep_contains_golden);\n }\n\n return contains_golden\n .values()\n .filter(|&&b| b)\n .count() as i32;\n}\n\nfn must_contain(bag: &str, bag_to_rules: &HashMap<&str, Vec>, memo: &HashMap<&str, bool>) -> bool {\n return bag_to_rules\n .get(bag)\n .unwrap()\n .iter()\n .any(|&Rule(_, rule)| {\n if rule == \"shiny gold\" {\n return true;\n }\n\n if let Some(&this_was_less_annoying_than_unwrap_or_else) = memo.get(bag) {\n return this_was_less_annoying_than_unwrap_or_else;\n }\n\n return must_contain(rule, bag_to_rules, memo); // this ain't memoised :((((((((((\n // need to learn lifetime parameters\n });\n}\n\nfn part2(input: &str) -> i32 {\n let bag_to_rules = parse_input(input);\n\n // let mut memo = HashMap::new() as HashMap<&str, i32>;\n\n return contains(\"shiny gold\", &bag_to_rules, /*&mut memo*/);\n}\n\nfn contains(colour: &str, bag_to_rules: &HashMap<&str, Vec>, /*memo: &mut HashMap<&str, i32>*/) -> i32 {\n // if let Some(&result) = memo.get(bag) {\n // return result;\n // }\n\n let rules = bag_to_rules\n .get(colour)\n .unwrap()\n .into_iter();\n\n let poop = rules.map(|Rule(rule_count, rule_colour)| {\n return rule_count // this many bags directly inside\n + rule_count * contains(rule_colour, bag_to_rules, /*memo*/) // and each of those bags contains bags\n });\n\n return poop.fold(0, |sum, next| sum + next);\n}\n\nfn parse_input(input: &str) -> HashMap<&str, Vec>{\n input\n .lines()\n .map(|line| {\n let mut split = line.split(\" contain \");\n let bag = split.next().unwrap();\n let rules = split.next().unwrap();\n\n return (remove_last_word(bag), parse_rules(rules));\n })\n .collect()\n}\n\nfn parse_rules(rules: &str) -> Vec {\n if rules == \"no other bags.\" {\n return Vec::new();\n }\n\n // remove the trailing full-stop\n let rules = rules.substring(0, rules.len() - 1);\n\n return rules\n .split(\", \")\n .map(|rule| {\n let space = rule.find(\" \").unwrap();\n let number = rule.substring(0, space).parse::().unwrap();\n let non_number_part = rule.substring(space + 1, rule.len());\n return Rule(number, remove_last_word(non_number_part));\n })\n .collect();\n}\n\nfn remove_last_word(string: &str) -> &str {\n let last_space = string.rfind(\" \").unwrap();\n return string.substring(0, last_space);\n}\n\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n const EXAMPLE_INPUT: &str = \"light red bags contain 1 bright white bag, 2 muted yellow bags.\\n\\\n dark orange bags contain 3 bright white bags, 4 muted yellow bags.\\n\\\n bright white bags contain 1 shiny gold bag.\\n\\\n muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.\\n\\\n shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.\\n\\\n dark olive bags contain 3 faded blue bags, 4 dotted black bags.\\n\\\n vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.\\n\\\n faded blue bags contain no other bags.\\n\\\n dotted black bags contain no other bags.\";\n\n const EXAMPLE_PART2_INPUT: &str = \"shiny gold bags contain 2 dark red bags.\\n\\\n dark red bags contain 2 dark orange bags.\\n\\\n dark orange bags contain 2 dark yellow bags.\\n\\\n dark yellow bags contain 2 dark green bags.\\n\\\n dark green bags contain 2 dark blue bags.\\n\\\n dark blue bags contain 2 dark violet bags.\\n\\\n dark violet bags contain no other bags.\";\n\n #[test]\n fn part1_example() {\n assert_eq!(part1(EXAMPLE_INPUT), 4);\n }\n\n #[test]\n fn part2_example_1() {\n assert_eq!(part2(EXAMPLE_INPUT), 32);\n }\n\n #[test]\n fn part2_example_2() {\n assert_eq!(part2(EXAMPLE_PART2_INPUT), 126);\n }\n\n #[test]\n fn test() {\n assert_eq!(part1(\"bright white bags contain 1 shiny gold bag.\\n\"), 1);\n }\n\n #[test]\n fn test2() {\n let bag_to_rules = parse_input(EXAMPLE_INPUT);\n\n assert_eq!(contains(\"faded blue\", &bag_to_rules), 0);\n assert_eq!(contains(\"dotted black\", &bag_to_rules), 0);\n assert_eq!(contains(\"dark olive\", &bag_to_rules), 7);\n assert_eq!(contains(\"vibrant plum\", &bag_to_rules), 11);\n assert_eq!(contains(\"shiny gold\", &bag_to_rules), 32);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":135,"cells":{"blob_id":{"kind":"string","value":"d122241b1a5f2da0c0458e989b8813720783add5"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"nampdn/prisma-engines"},"path":{"kind":"string","value":"/query-engine/core/src/executor/interpreting_executor.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2339,"string":"2,339"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"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 super::{pipeline::QueryPipeline, QueryExecutor};\nuse crate::{Operation, QueryGraphBuilder, QueryInterpreter, QuerySchemaRef, Response, Responses};\nuse async_trait::async_trait;\nuse connector::{ConnectionLike, Connector};\n\n/// Central query executor and main entry point into the query core.\npub struct InterpretingExecutor {\n connector: C,\n primary_connector: &'static str,\n force_transactions: bool,\n}\n\n// Todo:\n// - Partial execution semantics?\nimpl InterpretingExecutor\nwhere\n C: Connector + Send + Sync,\n{\n pub fn new(connector: C, primary_connector: &'static str, force_transactions: bool) -> Self {\n InterpretingExecutor {\n connector,\n primary_connector,\n force_transactions,\n }\n }\n}\n\n#[async_trait]\nimpl QueryExecutor for InterpretingExecutor\nwhere\n C: Connector + Send + Sync,\n{\n async fn execute(&self, operation: Operation, query_schema: QuerySchemaRef) -> crate::Result {\n let conn = self.connector.get_connection().await?;\n\n // Parse, validate, and extract query graphs from query document.\n let (query, info) = QueryGraphBuilder::new(query_schema).build(operation)?;\n\n // Create pipelines for all separate queries\n let mut responses = Responses::with_capacity(1);\n let needs_transaction = self.force_transactions || query.needs_transaction();\n\n let result = if needs_transaction {\n let tx = conn.start_transaction().await?;\n\n let interpreter = QueryInterpreter::new(ConnectionLike::Transaction(tx.as_ref()));\n let result = QueryPipeline::new(query, interpreter, info).execute().await;\n\n if result.is_ok() {\n tx.commit().await?;\n } else {\n tx.rollback().await?;\n }\n\n result?\n } else {\n let interpreter = QueryInterpreter::new(ConnectionLike::Connection(conn.as_ref()));\n QueryPipeline::new(query, interpreter, info).execute().await?\n };\n\n match result {\n Response::Data(key, item) => responses.insert_data(key, item),\n Response::Error(error) => responses.insert_error(error),\n }\n\n Ok(responses)\n }\n\n fn primary_connector(&self) -> &'static str {\n self.primary_connector\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":136,"cells":{"blob_id":{"kind":"string","value":"04b6682d49dbf63b9576fb241f686404d1a04d3f"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"manuelleduc/awesome-software-language-engineering"},"path":{"kind":"string","value":"/ci/src/lib.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4816,"string":"4,816"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["CC0-1.0"],"string":"[\n \"CC0-1.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"// `error_chain!` can recurse deeply\n#![recursion_limit = \"1024\"]\n\n#[macro_use]\nextern crate failure;\n\n#[macro_use]\nextern crate lazy_static;\n\nextern crate regex;\n\nuse failure::{Error, err_msg};\nuse regex::Regex;\nuse std::fmt;\nuse std::cmp::Ordering;\n\nlazy_static! {\n static ref TOOL_REGEX: Regex = Regex::new(r\"\\*\\s\\[(?P.*)\\]\\((?Phttp[s]?://.*)\\)\\s(:copyright:\\s)?\\-\\s(?P.*)\").unwrap();\n static ref SUBSECTION_HEADLINE_REGEX: Regex = Regex::new(r\"[A-Za-z\\s]*\").unwrap();\n}\n\nstruct Tool {\n name: String,\n link: String,\n desc: String,\n}\n\nimpl Tool {\n fn new>(name: T, link: T, desc: T) -> Self {\n Tool {\n name: name.into(),\n link: link.into(),\n desc: desc.into(),\n }\n }\n}\n\nimpl PartialEq for Tool {\n fn eq(&self, other: &Tool) -> bool {\n self.name.to_lowercase() == other.name.to_lowercase()\n }\n}\n\nimpl Eq for Tool {}\n\nimpl PartialOrd for Tool {\n fn partial_cmp(&self, other: &Tool) -> Option {\n Some(self.cmp(other))\n }\n}\n\nimpl Ord for Tool {\n fn cmp(&self, other: &Tool) -> Ordering {\n self.name.to_lowercase().cmp(&other.name.to_lowercase())\n }\n}\n\nfn check_tool(tool: &str) -> Result {\n println!(\"Checking `{}`\", tool);\n // NoneError can not implement Fail at this time. That's why we use ok_or\n // See https://github.com/rust-lang-nursery/failure/issues/61\n let captures = TOOL_REGEX.captures(tool).ok_or(err_msg(format!(\"Tool does not match regex: {}\", tool)))?;\n\n let name = captures[\"name\"].to_string();\n let link = captures[\"link\"].to_string();\n let desc = captures[\"desc\"].to_string();\n\n if name.len() > 50 {\n bail!(\"Name of tool is suspiciously long: `{}`\", name);\n }\n\n // A somewhat arbitrarily chosen description length.\n // Note that this includes any markdown formatting\n // like links. Therefore we are quite generous for now.\n if desc.len() > 200 {\n bail!(\"Desription of `{}` is too long: {}\", name, desc);\n }\n\n Ok(Tool::new(name, link, desc))\n}\n\nfn check_section(section: String) -> Result<(), Error> {\n // Ignore license section\n if section.starts_with(\"License\") {\n return Ok(());\n }\n\n // Skip section headline\n let lines: Vec<_> = section.split('\\n').skip(1).collect();\n if lines.is_empty() {\n bail!(\"Empty section: {}\", section)\n };\n\n let mut tools = vec![];\n for line in lines {\n if line.is_empty() {\n continue;\n }\n // Exception for subsection headlines\n if !line.starts_with(\"*\") && line.ends_with(\":\") &&\n SUBSECTION_HEADLINE_REGEX.is_match(line)\n {\n continue;\n }\n tools.push(check_tool(line)?);\n }\n // Tools need to be alphabetically ordered\n check_ordering(tools)\n}\n\nfn check_ordering(tools: Vec) -> Result<(), Error> {\n match tools.windows(2).find(|t| t[0] > t[1]) {\n Some(tools) => bail!(\"`{}` does not conform to alphabetical ordering\", tools[0].name),\n None => Ok(()),\n }\n}\n\nfn check(text: String) -> Result<(), Error> {\n let sections = text.split(\"\\n# \");\n\n // Skip first two sections,\n // as they contain the prelude and the table of contents.\n for section in sections.skip(2) {\n let subsections = section.split(\"## \");\n for subsection in subsections.skip(1) {\n check_section(subsection.into())?;\n }\n }\n Ok(())\n}\n\nmod tests {\n use super::*;\n use std::fs::File;\n use std::io::Read;\n\n #[test]\n fn test_complete_file() {\n let mut file = File::open(\"../README.md\").expect(\"Can't open testfile\");\n let mut contents = String::new();\n file.read_to_string(&mut contents).expect(\"Can't read testfile contents\");\n let result = check(contents);\n if result.is_err() {\n println!(\"Error: {:?}\", result.err());\n assert!(false);\n } else {\n assert!(true);\n }\n }\n\n\n #[test]\n fn test_correct_ordering() {\n assert!(check_ordering(vec![]).is_ok());\n\n assert!(check_ordering(vec![Tool::new(\"a\", \"url\", \"desc\")]).is_ok());\n\n assert!(\n check_ordering(vec![\n Tool::new(\"0\", \"\", \"\"),\n Tool::new(\"1\", \"\", \"\"),\n Tool::new(\"a\", \"\", \"\"),\n Tool::new(\"Axx\", \"\", \"\"),\n Tool::new(\"B\", \"\", \"\"),\n Tool::new(\"b\", \"\", \"\"),\n Tool::new(\"c\", \"\", \"\"),\n ]).is_ok()\n );\n }\n\n #[test]\n fn test_incorrect_ordering() {\n assert!(\n check_ordering(vec![\n Tool::new(\"b\", \"\", \"\"),\n Tool::new(\"a\", \"\", \"\"),\n Tool::new(\"c\", \"\", \"\"),\n ]).is_err()\n );\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":137,"cells":{"blob_id":{"kind":"string","value":"7e359a5fc15b6bc0d512244d9217e24a8923a440"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"abhijat/invalidator"},"path":{"kind":"string","value":"/benches/benchmark.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":953,"string":"953"},"score":{"kind":"number","value":2.828125,"string":"2.828125"},"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":"#[macro_use]\nextern crate criterion;\n\nuse std::collections::HashSet;\n\nuse criterion::Criterion;\nuse rand::distributions::Alphanumeric;\nuse rand::Rng;\nuse rand::thread_rng;\n\nuse bloom_filter::BloomFilter;\n\nfn data_set_of_size(size: usize, word_size: usize) -> HashSet {\n let mut data = HashSet::with_capacity(size);\n for _ in 0..size {\n let s: String = thread_rng().sample_iter(&Alphanumeric).take(word_size).collect();\n data.insert(s);\n }\n data\n}\n\nfn false_negative_benchmark(c: &mut Criterion) {\n let data = data_set_of_size(1 * 100 * 100, 16);\n let mut filter = BloomFilter::new();\n\n data.iter().for_each(|w| filter.put(w));\n\n c.bench_function(\n \"false-negatives 100 * 100 problem size, 16 char words\",\n move |b| b.iter(|| {\n data.iter().for_each(|w| if !filter.get(w) { panic!(); });\n }));\n}\n\ncriterion_group!(benches, false_negative_benchmark);\ncriterion_main!(benches);\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":138,"cells":{"blob_id":{"kind":"string","value":"91b02a5a09ad5a9979113b7dfd51da71b27a4cdc"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"tobisako/rust-memo"},"path":{"kind":"string","value":"/rust_tutorial/s414/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5053,"string":"5,053"},"score":{"kind":"number","value":4.3125,"string":"4.3125"},"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":"struct Point {\n x: i32,\n y: i32,\n}\n\n// use std::result::Result;\n\nfn main() {\n // パターン\n // パターンには一つ落とし穴があります。\n // 新しい束縛を導入する他の構文と同様、パターンはシャドーイングをします。例えば:\n let x = 'x';\n let c = 'c';\n match c {\n x => println!(\"x: {} c: {}\", x, c), // 元のxがシャドーイングされて、別のxとして動作している。\n }\n println!(\"x: {}\", x);\n // x => は値をパターンにマッチさせ、マッチの腕内で有効な x という名前の束縛を導入します。\n // 既に x という束縛が存在していたので、新たに導入した x は、その古い x をシャドーイングします。\n\n // 複式パターン\n let x2 = 1;\n match x2 {\n 1 | 2 => println!(\"one or two\"),\n 3 => println!(\"three\"),\n _ => println!(\"anything\"),\n }\n\n // 分配束縛\n let origin = Point { x: 0, y: 0 };\n match origin {\n Point { x, y } => println!(\"({},{})\", x, y),\n }\n\n // 値に別の名前を付けたいときは、 : を使うことができます。\n let origin2 = Point { x: 0, y: 0 };\n match origin2 {\n Point { x: x1, y: y1 } => println!(\"({},{})\", x1, y1),\n }\n\n // 値の一部にだけ興味がある場合は、値のすべてに名前を付ける必要はありません。\n let origin = Point { x: 0, y: 0 };\n match origin {\n Point { x, .. } => println!(\"x is {}\", x),\n }\n\n // 最初のメンバだけでなく、どのメンバに対してもこの種のマッチを行うことができます。\n let origin = Point { x: 0, y: 0 };\n match origin {\n Point { y, .. } => println!(\"y is {}\", y),\n }\n\n // 束縛の無視\n let some_value: Result = Err(\"There was an error\");\n match some_value {\n Ok(value) => println!(\"got a value: {}\", value),\n Err(_) => println!(\"an error occurred\"),\n }\n\n // ここでは、タプルの最初と最後の要素に x と z を束縛します。\n fn coordinate() -> (i32, i32, i32) {\n // generate and return some sort of triple tuple\n // 3要素のタプルを生成して返す\n (1, 2, 3)\n }\n let (x, _, z) = coordinate();\n\n // 同様に .. でパターン内の複数の値を無視することができます。\n enum OptionalTuple {\n Value(i32, i32, i32),\n Missing,\n }\n let x = OptionalTuple::Value(5, -2, 3);\n match x {\n OptionalTuple::Value(..) => println!(\"Got a tuple!\"),\n OptionalTuple::Missing => println!(\"No such luck.\"),\n }\n\n // ref と ref mut\n // 参照 を取得したいときは ref キーワードを使いましょう。\n let x3 = 5;\n match x3 {\n ref r => println!(\"Got a reference to {}\", r),\n }\n // ミュータブルな参照が必要な場合は、同様に ref mut を使います。\n let mut x = 5;\n match x {\n ref mut mr => {\n *mr += 1;\n println!(\"Got a mutable reference to {}\", mr);\n },\n }\n println!(\"x = {}\", x); // 値が書き換わっている。\n\n // 範囲\n let x = 1;\n match x {\n 1 ... 5 => println!(\"one through five\"),\n _ => println!(\"anything\"),\n }\n // 範囲は多くの場合、整数か char 型で使われます:\n let x = '💅';\n match x {\n 'a' ... 'j' => println!(\"early letter\"),\n 'k' ... 'z' => println!(\"late letter\"),\n _ => println!(\"something else\"),\n }\n\n // 束縛\n let x = 1;\n match x {\n e @ 1 ... 5 => println!(\"got a range element {}\", e),\n _ => println!(\"anything\"),\n }\n\n // 内側の name の値への参照に a を束縛します。\n #[derive(Debug)]\n struct Person {\n name: Option,\n }\n let name = \"Steve\".to_string();\n let mut x: Option = Some(Person { name: Some(name) });\n match x {\n Some(Person { name: ref a @ Some(_), .. }) => println!(\"{:?}\", a),\n _ => {}\n }\n\n // @ を | と組み合わせて使う場合は、それぞれのパターンで同じ名前が束縛されるようにする必要があります:\n let x = 5;\n match x {\n e @ 1 ... 5 | e @ 8 ... 10 => println!(\"got a range element {}\", e),\n _ => println!(\"anything\"),\n }\n\n // ガード\n // if を使うことでマッチガードを導入することができます:\n enum OptionalInt {\n Value(i32),\n Missing,\n }\n let x = OptionalInt::Value(5);\n match x {\n OptionalInt::Value(i) if i > 5 => println!(\"Got an int bigger than five!\"),\n OptionalInt::Value(..) => println!(\"Got an int!\"),\n OptionalInt::Missing => println!(\"No such luck.\"),\n }\n\n // 複式パターンで if を使うと、 if は | の両側に適用されます:\n let x = 4;\n let y = false;\n match x {\n 4 | 5 if y => println!(\"yes\"),\n _ => println!(\"no\"),\n }\n // イメージ: (4 | 5) if y => ...\n\n // 混ぜてマッチ\n // やりたいことに応じて、それらを混ぜてマッチさせることもできます:\n // match x {\n // Foo { x: Some(ref name), y: None } => { println!(\"foo\"); },\n // }\n // パターンはとても強力です。上手に使いましょう。\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":139,"cells":{"blob_id":{"kind":"string","value":"8926b758fe04817f945d6b6738733e09b81a05ed"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"elipmoc/Ruscall"},"path":{"kind":"string","value":"/src/compile/semantic_analysis/variable_table.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1738,"string":"1,738"},"score":{"kind":"number","value":2.921875,"string":"2.921875"},"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;\n\n#[derive(Clone)]\npub struct VariableTable {\n local_var_names: Vec>,\n global_var_names: HashMap,\n nest_level: usize,\n}\n\nuse super::super::ir::ast::VariableAST;\nuse super::type_inference::type_env::TypeEnv;\nuse super::mir::ExprMir;\n\n//変数の管理\nimpl VariableTable {\n pub fn new(global_var_names: HashMap) -> VariableTable {\n VariableTable { global_var_names, local_var_names: vec![], nest_level: 0 }\n }\n\n //de bruijn indexを割り当てたVariableIrの生成\n //またはGlobalVariableIrの生成\n pub fn get_variable_ir(&self, var: VariableAST, ty_env: &mut TypeEnv) -> Option {\n let a = self.local_var_names[self.nest_level - 1]\n .iter().rev().enumerate()\n .find(|(_, name)| *name == &var.id)\n .map(|(id, _)| id);\n match a {\n Some(id) => Some(ExprMir::create_variable_mir(id, var.pos, ty_env.fresh_type_id())),\n _ => {\n if self.global_var_names.contains_key(&var.id) {\n Some(ExprMir::create_global_variable_mir(var.id, var.pos, ty_env.fresh_type_id()))\n } else {\n None\n }\n }\n }\n }\n pub fn in_nest(&mut self, iter: T)\n where T: IntoIterator {\n if self.local_var_names.len() <= self.nest_level {\n self.local_var_names.push(iter.into_iter().collect());\n } else {\n self.local_var_names[self.nest_level].clear();\n self.local_var_names[self.nest_level].extend(iter);\n }\n self.nest_level += 1;\n }\n pub fn out_nest(&mut self) {\n self.nest_level -= 1;\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":140,"cells":{"blob_id":{"kind":"string","value":"194d5312513ad7060b2c4dc623f33fbdf1ae4875"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"pwwolff/RussianRust"},"path":{"kind":"string","value":"/src/settings_factory.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":474,"string":"474"},"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":"extern crate glob;\nextern crate config;\n\nuse std::collections::HashMap;\nuse config::*;\nuse glob::glob;\n\npub fn get_settings() -> HashMap{\n let mut settings = Config::default();\n settings\n .merge(glob(\"config/*\")\n .unwrap()\n .map(|path| File::from(path.unwrap()))\n .collect::>())\n .unwrap();\n\n // Print out our settings (as a HashMap)\n settings.try_into::>().unwrap()\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":141,"cells":{"blob_id":{"kind":"string","value":"dad6bfdbdf27b7f5223322bdee6c1fbc32195b04"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"payload/asciii-rs"},"path":{"kind":"string","value":"/src/actions/mod.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":11758,"string":"11,758"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"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":"//! General actions\n\n#![allow(unused_imports)]\n#![allow(dead_code)]\n\n\nuse chrono::*;\n\nuse std::{env,fs};\nuse std::time;\nuse std::fmt::Write;\nuse std::path::{Path,PathBuf};\n\nuse util;\nuse super::BillType;\nuse storage::{Storage,StorageDir,Storable,StorageResult};\nuse project::Project;\n\n#[cfg(feature=\"document_export\")]\nuse fill_docs::fill_template;\n\npub mod error;\nuse self::error::*;\n\n/// Sets up an instance of `Storage`.\npub fn setup_luigi() -> Result> {\n trace!(\"setup_luigi()\");\n let working = try!(::CONFIG.get_str(\"dirs/working\").ok_or(\"Faulty config: dirs/working does not contain a value\"));\n let archive = try!(::CONFIG.get_str(\"dirs/archive\").ok_or(\"Faulty config: dirs/archive does not contain a value\"));\n let templates = try!(::CONFIG.get_str(\"dirs/templates\").ok_or(\"Faulty config: dirs/templates does not contain a value\"));\n let storage = try!(Storage::new(util::get_storage_path(), working, archive, templates));\n Ok(storage)\n}\n\n/// Sets up an instance of `Storage`, with git turned on.\npub fn setup_luigi_with_git() -> Result> {\n trace!(\"setup_luigi()\");\n let working = try!(::CONFIG.get_str(\"dirs/working\").ok_or(\"Faulty config: dirs/working does not contain a value\"));\n let archive = try!(::CONFIG.get_str(\"dirs/archive\").ok_or(\"Faulty config: dirs/archive does not contain a value\"));\n let templates = try!(::CONFIG.get_str(\"dirs/templates\").ok_or(\"Faulty config: dirs/templates does not contain a value\"));\n let storage = try!(Storage::new_with_git(util::get_storage_path(), working, archive, templates));\n Ok(storage)\n}\n\n\npub fn simple_with_projects(dir:StorageDir, search_terms:&[&str], f:F)\n where F:Fn(&Project)\n{\n match with_projects(dir, search_terms, |p| {f(p);Ok(())}){\n Ok(_) => {},\n Err(e) => error!(\"{}\",e)\n }\n}\n\n/// Helper method that passes projects matching the `search_terms` to the passt closure `f`\npub fn with_projects(dir:StorageDir, search_terms:&[&str], f:F) -> Result<()>\n where F:Fn(&Project)->Result<()>\n{\n trace!(\"with_projects({:?})\", search_terms);\n let luigi = try!(setup_luigi());\n let projects = try!(luigi.search_projects_any(dir, search_terms));\n if projects.is_empty() {\n return Err(format!(\"Nothing found for {:?}\", search_terms).into())\n }\n for project in &projects{\n try!(f(project));\n }\n Ok(())\n}\n\npub fn csv(year:i32) -> Result {\n let luigi = try!(setup_luigi());\n let mut projects = try!(luigi.open_projects(StorageDir::Year(year)));\n projects.sort_by(|pa,pb| pa.index().unwrap_or_else(||\"zzzz\".to_owned()).cmp( &pb.index().unwrap_or(\"zzzz\".to_owned())));\n projects_to_csv(&projects)\n}\n\n/// Produces a csv string from a list of `Project`s\n/// TODO this still contains german terms\npub fn projects_to_csv(projects:&[Project]) -> Result{\n let mut string = String::new();\n let splitter = \";\";\n try!(writeln!(&mut string, \"{}\", [ \"Rnum\", \"Bezeichnung\", \"Datum\", \"Rechnungsdatum\", \"Betreuer\", \"Verantwortlich\", \"Bezahlt am\", \"Betrag\", \"Canceled\"].join(splitter)));\n for project in projects{\n try!(writeln!(&mut string, \"{}\", [\n project.get(\"InvoiceNumber\").unwrap_or_else(|| String::from(r#\"\"\"\"#)),\n project.get(\"Name\").unwrap_or_else(|| String::from(r#\"\"\"\"#)),\n project.get(\"event/dates/0/begin\").unwrap_or_else(|| String::from(r#\"\"\"\"#)),\n project.get(\"invoice/date\").unwrap_or_else(|| String::from(r#\"\"\"\"#)),\n project.get(\"Caterers\").unwrap_or_else(|| String::from(r#\"\"\"\"#)),\n project.get(\"Responsible\").unwrap_or_else(|| String::from(r#\"\"\"\"#)),\n project.get(\"invoice/payed_date\").unwrap_or_else(|| String::from(r#\"\"\"\"#)),\n project.get(\"Final\").unwrap_or_else(|| String::from(r#\"\"\"\"#)),\n project.canceled_string().to_owned()\n ].join(splitter)));\n }\n Ok(string)\n}\n\n/// Creates the latex files within each projects directory, either for Invoice or Offer.\n#[cfg(feature=\"document_export\")]\npub fn project_to_doc(project: &Project, template_name:&str, bill_type:&Option, dry_run:bool, force:bool) -> Result<()> {\n let template_ext = ::CONFIG.get_str(\"extensions/output_template\").expect(\"Faulty default config\");\n let output_ext = ::CONFIG.get_str(\"extensions/output_file\").expect(\"Faulty default config\");\n let convert_ext = ::CONFIG.get_str(\"convert/output_extension\").expect(\"Faulty default config\");\n let trash_exts = ::CONFIG.get(\"convert/trash_extensions\") .expect(\"Faulty default config\")\n .as_vec().expect(\"Faulty default config\")\n .into_iter()\n .map(|v|v.as_str()).collect::>();\n\n let mut template_path = PathBuf::new();\n\n template_path.push(util::get_storage_path());\n template_path.push(::CONFIG.get_str(\"dirs/templates\").expect(\"Faulty config: dirs/templates does not contain a value\"));\n template_path.push(template_name);\n template_path.set_extension(template_ext);\n\n debug!(\"template file={:?} exists={}\", template_path, template_path.exists());\n if !template_path.exists() {\n return Err(format!(\"Template not found at {}\", template_path.display()).into())\n }\n\n let convert_tool = ::CONFIG.get_str(\"convert/tool\");\n let output_folder = ::CONFIG.get_str(\"output_path\").and_then(util::get_valid_path).expect(\"Faulty config \\\"output_path\\\"\");\n\n let ready_for_offer = project.is_ready_for_offer();\n let ready_for_invoice = project.is_ready_for_invoice();\n let project_file = project.file();\n\n // tiny little helper\n let to_local_file = |file:&Path, ext| {\n let mut _tmpfile = file.to_owned();\n _tmpfile.set_extension(ext);\n Path::new(_tmpfile.file_name().unwrap().into()).to_owned()\n };\n\n use BillType::*;\n let (dyn_bill_type, outfile_tex):\n (Option, Option) =\n match (bill_type, ready_for_offer, ready_for_invoice)\n {\n (&Some(Offer), Ok(_), _ ) |\n (&None, Ok(_), Err(_)) => (Some(Offer), Some(project.dir().join(project.offer_file_name(output_ext).expect(\"this should have been cought by ready_for_offer()\")))),\n (&Some(Invoice), _, Ok(_)) |\n (&None, _, Ok(_)) => (Some(Invoice), Some(project.dir().join(project.invoice_file_name(output_ext).expect(\"this should have been cought by ready_for_invoice()\")))),\n (&Some(Offer), Err(e), _ ) => {error!(\"cannot create an offer, check out:{:#?}\",e);(None,None)},\n (&Some(Invoice), _, Err(e)) => {error!(\"cannot create an invoice, check out:{:#?}\",e);(None,None)},\n (_, Err(e), Err(_)) => {error!(\"Neither an Offer nor an Invoice can be created from this project\\n please check out {:#?}\", e);(None,None)}\n };\n\n //debug!(\"{:?} -> {:?}\",(bill_type, project.is_ready_for_offer(), project.is_ready_for_invoice()), (dyn_bill_type, outfile_tex));\n\n if let (Some(outfile), Some(dyn_bill)) = (outfile_tex, dyn_bill_type) {\n let filled = try!(fill_template(project, &dyn_bill, &template_path));\n\n let pdffile = to_local_file(&outfile, convert_ext);\n let target = output_folder.join(&pdffile);\n\n // ok, so apparently we can create a tex file, so lets do it\n if !force && target.exists() && try!(file_age(&target)) < try!(file_age(&project_file)){\n // no wait, nothing has changed, so lets save ourselves the work\n info!(\"nothing to be done, {} is younger than {}\\n use -f if you don't agree\", target.display(), project_file.display());\n } else {\n // \\o/ we created a tex file\n\n if dry_run{\n warn!(\"Dry run! This does not produce any output:\\n * {}\\n * {}\", outfile.display(), pdffile.display());\n } else {\n let outfileb = try!(project.write_to_file(&filled,&dyn_bill,output_ext));\n debug!(\"{} vs\\n {}\", outfile.display(), outfileb.display());\n util::pass_to_command(&convert_tool, &[&outfileb]);\n }\n // clean up expected trash files\n for trash_ext in trash_exts.iter().filter_map(|x|*x){\n let trash_file = to_local_file(&outfile, trash_ext);\n if trash_file.exists() {\n try!(fs::remove_file(&trash_file));\n debug!(\"just deleted: {}\", trash_file.display())\n }\n else {\n debug!(\"I expected there to be a {}, but there wasn't any ?\", trash_file.display())\n }\n }\n if pdffile.exists(){\n debug!(\"now there is be a {:?} -> {:?}\", pdffile, target);\n try!(fs::rename(&pdffile, &target));\n }\n }\n }\n\n Ok(())\n\n}\n\n/// Creates the latex files within each projects directory, either for Invoice or Offer.\n#[cfg(feature=\"document_export\")]\npub fn projects_to_doc(dir:StorageDir, search_term:&str, template_name:&str, bill_type:&Option, dry_run:bool, force:bool) -> Result<()> {\n with_projects(dir, &[search_term], |p| project_to_doc(p, template_name, bill_type, dry_run, force) )\n}\n\nfn file_age(path:&Path) -> Result {\n let metadata = try!(fs::metadata(path));\n let accessed = try!(metadata.accessed());\n Ok(try!(accessed.elapsed()))\n}\n\n/// Testing only, tries to run complete spec on all projects.\n/// TODO make this not panic :D\n/// TODO move this to `spec::all_the_things`\npub fn spec() -> Result<()> {\n use project::spec::*;\n let luigi = try!(setup_luigi());\n //let projects = super::execute(||luigi.open_projects(StorageDir::All));\n let projects = try!(luigi.open_projects(StorageDir::Working));\n for project in projects{\n info!(\"{}\", project.dir().display());\n\n let yaml = project.yaml();\n client::validate(&yaml).map_err(|errors|for error in errors{\n println!(\" error: {}\", error);\n }).unwrap();\n\n client::full_name(&yaml);\n client::first_name(&yaml);\n client::title(&yaml);\n client::email(&yaml);\n\n\n hours::caterers_string(&yaml);\n invoice::number_long_str(&yaml);\n invoice::number_str(&yaml);\n offer::number(&yaml);\n project.age().map(|a|format!(\"{} days\", a)).unwrap();\n project.date().map(|d|d.year().to_string()).unwrap();\n project.sum_sold().map(|c|util::currency_to_string(&c)).unwrap();\n project::manager(&yaml).map(|s|s.to_owned()).unwrap();\n project::name(&yaml).map(|s|s.to_owned()).unwrap();\n }\n\n Ok(())\n}\n\npub fn delete_project_confirmation(dir: StorageDir, search_terms:&[&str]) -> Result<()> {\n let luigi = try!(setup_luigi());\n for project in try!(luigi.search_projects_any(dir, search_terms)) {\n try!(project.delete_project_dir_if(\n || util::really(&format!(\"you want me to delete {:?} [y/N]\", project.dir())) && util::really(\"really? [y/N]\")\n ))\n }\n Ok(())\n}\n\npub fn archive_projects(search_terms:&[&str], manual_year:Option, force:bool) -> Result>{\n trace!(\"archive_projects matching ({:?},{:?},{:?})\", search_terms, manual_year,force);\n let luigi = try!(setup_luigi_with_git());\n Ok(try!( luigi.archive_projects_if(search_terms, manual_year, || force) ))\n}\n\n/// Command UNARCHIVE \n/// TODO: return a list of files that have to be updated in git\npub fn unarchive_projects(year:i32, search_terms:&[&str]) -> Result> {\n let luigi = try!(setup_luigi_with_git());\n Ok(try!( luigi.unarchive_projects(year, search_terms) ))\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":142,"cells":{"blob_id":{"kind":"string","value":"26801c3acd5afe03a2f81242e2d991bf6fc3b719"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Strum355/lsif-lang-server"},"path":{"kind":"string","value":"/src/reader/interner.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5093,"string":"5,093"},"score":{"kind":"number","value":3.734375,"string":"3.734375"},"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 std::collections::HashMap;\nuse std::marker::Sync;\nuse std::sync::{Arc, Mutex};\n\n/// Interner converts strings into unique identifers. Submitting the same byte value to\n/// the interner will result in the same identifier being produced. Each unique input is\n/// guaranteed to have a unique output (no two inputs share the same identifier). The\n/// identifier space of two distinct interner instances may overlap.\n///\n/// Assumption: The output of LSIF indexers will not generally mix types of identifiers.\n/// If integers are used, they are used for all ids. If strings are used, they are used\n/// for all ids.\n#[derive(Clone)]\npub struct Interner {\n map: Arc>>,\n}\n\nunsafe impl Sync for Interner {}\n\nimpl Interner {\n pub fn new() -> Interner {\n Interner {\n map: Arc::new(Mutex::new(HashMap::new())),\n }\n }\n\n /// Intern returns the unique identifier for the given byte value. The byte value should\n /// be a raw LSIF input identifier, which should be a JSON-encoded number or quoted string.\n /// This method is safe to call from multiple goroutines.\n pub fn intern(&self, raw: &[u8]) -> Result {\n if raw.is_empty() {\n return Ok(0);\n }\n\n if raw[0] != b'\"' {\n unsafe { return String::from_utf8_unchecked(raw.to_vec()).parse::() }\n }\n\n let s = unsafe { String::from_utf8_unchecked(raw[1..raw.len() - 1].to_vec()) };\n\n match s.parse::() {\n Ok(num) => return Ok(num),\n Err(_) => {}\n }\n\n let mut map = self.map.lock().unwrap();\n if map.contains_key(&s) {\n return Ok(*map.get(&s).unwrap());\n }\n\n let id: u64 = (map.len() + 1) as u64;\n map.insert(s, id);\n Ok(id)\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use anyhow::{format_err, Result};\n use std::collections::HashSet;\n\n fn compare_from_vec(input: &[Vec]) -> Result> {\n let mut results = HashSet::with_capacity(input.len());\n let interner = Interner::new();\n\n for num in input {\n let x = interner.intern(num).unwrap();\n results.insert(x);\n }\n\n for num in input {\n let x = interner.intern(num).unwrap();\n results\n .get(&x)\n .ok_or(format_err!(\"result not found in previous set\"))?;\n }\n\n Ok(results)\n }\n\n fn string_vec_to_bytes(values: Vec<&str>) -> Vec> {\n values.iter().map(|s| s.as_bytes().to_vec()).collect()\n }\n\n #[test]\n fn empty_data_doesnt_throw() {\n let interner = Interner::new();\n\n assert_eq!(interner.intern(&Vec::new()).unwrap(), 0);\n }\n\n #[test]\n fn numbers_test() {\n let values = string_vec_to_bytes(vec![\"1\", \"2\", \"3\", \"4\", \"100\", \"500\"]);\n\n let results = compare_from_vec(&values).unwrap();\n\n assert_eq!(results.len(), values.len());\n }\n\n #[test]\n fn numbers_in_strings_test() {\n let values = string_vec_to_bytes(vec![\n r#\"\"1\"\"#, r#\"\"2\"\"#, r#\"\"3\"\"#, r#\"\"4\"\"#, r#\"\"100\"\"#, r#\"\"500\"\"#,\n ]);\n\n let results = compare_from_vec(&values).unwrap();\n\n assert_eq!(results.len(), values.len());\n }\n\n #[test]\n fn normal_strings_test() {\n let values = string_vec_to_bytes(vec![\n r#\"\"assert_eq!(results.len(), values.len());\"\"#,\n r#\"\"sample text\"\"#,\n r#\"\"why must this be utf16. Curse you javascript\"\"#,\n r#\"\"I'd just like to interject for a moment. What you're referring to as Linux,\n is in fact, GNU/Linux, or as I've recently taken to calling it, GNU plus Linux.\n Linux is not an operating system unto itself, but rather another free component\n of a fully functioning GNU system made useful by the GNU corelibs, shell\n utilities and vital system components comprising a full OS as defined by POSIX.\"\"#,\n ]);\n\n let results = compare_from_vec(&values).unwrap();\n\n assert_eq!(results.len(), values.len());\n }\n\n #[test]\n fn duplicate_string() {\n let values = string_vec_to_bytes(vec![\n r#\"\"assert_eq!(results.len(), values.len());\"\"#,\n r#\"\"sample text\"\"#,\n r#\"\"why must this be utf16. Curse you javascript\"\"#,\n r#\"\"why must this be utf16. Curse you javascript\"\"#,\n r#\"\"why must this be utf16. Curse you javascript\"\"#,\n r#\"\"I'd just like to interject for a moment. What you're referring to as Linux,\n is in fact, GNU/Linux, or as I've recently taken to calling it, GNU plus Linux.\n Linux is not an operating system unto itself, but rather another free component\n of a fully functioning GNU system made useful by the GNU corelibs, shell\n utilities and vital system components comprising a full OS as defined by POSIX.\"\"#,\n ]);\n\n let results = compare_from_vec(&values).unwrap();\n\n assert_eq!(results.len(), values.len() - 2);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":143,"cells":{"blob_id":{"kind":"string","value":"d04135f099f39bfa1d16d4b9fd189ce9e97ad955"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"JesterOrNot/Rust-Playground"},"path":{"kind":"string","value":"/functimer.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":299,"string":"299"},"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":"fn main() {\n timeFunction(&printer);\n}\nfn timeFunction(func: &dyn Fn()) {\n let time1 = std::time::Instant::now();\n func();\n let time2 = std::time::Instant::now().duration_since(time1);\n println!(\"{:?}\", time2);\n}\nfn printer() {\n for i in 0..100 {\n println!(\"{}\", i);\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":144,"cells":{"blob_id":{"kind":"string","value":"fdbfd5baeee2106b2b6fc3e9f75a672229b84644"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"IGBC/Cursive"},"path":{"kind":"string","value":"/src/backend/mod.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1176,"string":"1,176"},"score":{"kind":"number","value":2.71875,"string":"2.71875"},"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 event;\nuse theme;\n\n#[cfg(feature = \"termion\")]\nmod termion;\n#[cfg(feature = \"bear-lib-terminal\")]\nmod blt;\n#[cfg(any(feature = \"ncurses\", feature = \"pancurses\"))]\nmod curses;\n\n#[cfg(feature = \"bear-lib-terminal\")]\npub use self::blt::*;\n#[cfg(any(feature = \"ncurses\", feature = \"pancurses\"))]\npub use self::curses::*;\n#[cfg(feature = \"termion\")]\npub use self::termion::*;\n\npub trait Backend {\n fn init() -> Box where Self: Sized;\n // TODO: take `self` by value?\n // Or implement Drop?\n fn finish(&mut self);\n\n fn refresh(&mut self);\n\n fn has_colors(&self) -> bool;\n fn screen_size(&self) -> (usize, usize);\n\n /// Main input method\n fn poll_event(&mut self) -> event::Event;\n\n /// Main method used for printing\n fn print_at(&self, (usize, usize), &str);\n fn clear(&self, color: theme::Color);\n\n fn set_refresh_rate(&mut self, fps: u32);\n\n // This sets the Colours and returns the previous colours\n // to allow you to set them back when you're done.\n fn set_color(&self, colors: theme::ColorPair) -> theme::ColorPair;\n\n fn set_effect(&self, effect: theme::Effect);\n fn unset_effect(&self, effect: theme::Effect);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":145,"cells":{"blob_id":{"kind":"string","value":"c7fc2c95c9f9f77f9516ad734f36661fd188d607"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Agile-Llama/Ackermann"},"path":{"kind":"string","value":"/ackermann.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1727,"string":"1,727"},"score":{"kind":"number","value":3.453125,"string":"3.453125"},"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::cmp::max;\n\n// Naive approach\nfn ack(m: isize, n: isize) -> isize {\n if m == 0 {\n n + 1\n } else if n == 0 {\n ack(m - 1, 1)\n } else {\n ack(m - 1, ack(m, n - 1))\n }\n}\n\n// More optimzed approach using a cache\nfn ack_with_cache(m: u64, n: u64) -> u64 {\n let mut cache: HashMap<(u64, u64), u64> = HashMap::new();\n\n _ack_with_cache(&mut cache, m, n)\n}\n\nfn _ack_with_cache(cache: &mut HashMap<(u64, u64), u64>, m: u64, n: u64) -> u64 {\n match (m, n) {\n (0, n) => n + 1,\n (1, n) => n + 2,\n (m, 0) => _ack_with_cache(cache, m - 1, 1),\n (m, 1) => {\n let n = _ack_with_cache(cache, m - 1, 1);\n _ack_with_cache(cache, m - 1, n)\n }\n (m, n) => {\n if cache.contains_key(&(m, n)) {\n *cache.get(&(m, n)).unwrap()\n } else {\n let s = _ack_with_cache(cache, m, n - 2);\n let t = _ack_with_cache(cache, m, n - 1);\n\n let res = (s..(t + 1)).fold(0, |acc, x| _ack_comparator(cache, m, acc, x));\n cache.insert((m, n), res);\n res\n }\n }\n }\n}\n\nfn _ack_comparator(cache: &mut HashMap<(u64, u64), u64>, m: u64, acc: u64, x: u64) -> u64 {\n let c = _ack_with_cache(cache, m - 1, x);\n max(acc, c)\n}\n\nfn main() {\n use std::time::Instant;\n\n //let before_naive = Instant::now();\n //let a = ack(4, 1);\n //println!(\"Naive Elapsed time: {:.2?}\", before_naive.elapsed());\n //println!(\"Answer: {}\", a); \n\n let before = Instant::now();\n let b = ack_with_cache(4, 2);\n println!(\"Optimzed Elapsed time: {:.2?}\", before.elapsed());\n println!(\"Answer: {}\", b); \n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":146,"cells":{"blob_id":{"kind":"string","value":"8f476860cad08c7542d752279426b2b2e2708f58"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"mfarzamalam/Rust"},"path":{"kind":"string","value":"/Rust_challenge/divisible/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":587,"string":"587"},"score":{"kind":"number","value":3.171875,"string":"3.171875"},"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 read_input::prelude::*;\n\nfn main() {\n\n let number = input::()\n .msg(\"Enter numerator : \")\n .err(\"Please input positive integer\")\n .get();\n\n let divisible = input::()\n .msg(\"Enter denominator : \")\n .err(\"Please input positive integer\")\n .get();\n\n if number % divisible == 0 {\n println!(\"Number {} is completely divisible by {} ! \",number,divisible);\n }\n else {\n println!(\"Number {} is not completely divisible by {} ! \",number,divisible); \n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":147,"cells":{"blob_id":{"kind":"string","value":"a5320d31e9d5b7833e7236c58c84865f0c51b007"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"zhaoyao/rust-lab"},"path":{"kind":"string","value":"/dns-server/src/packet/record_type.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1199,"string":"1,199"},"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 super::error::*;\r\n\r\n#[derive(Debug)]\r\npub enum RecordType {\r\n A,\r\n NS,\r\n MD,\r\n MF,\r\n CNAME,\r\n SOA,\r\n MB,\r\n MG,\r\n MR,\r\n NULL,\r\n WKS,\r\n PTR,\r\n HINFO,\r\n MINFO,\r\n MX,\r\n TXT,\r\n AXFR,\r\n MAILB,\r\n MAILA,\r\n Any\r\n}\r\n\r\nimpl RecordType {\r\n pub fn from_u16(i: u16) -> Result {\r\n match i {\r\n 1 => Ok(RecordType::A),\r\n 2 => Ok(RecordType::NS),\r\n 3 => Ok(RecordType::MD),\r\n 4 => Ok(RecordType::MF),\r\n 5 => Ok(RecordType::CNAME),\r\n 6 => Ok(RecordType::SOA),\r\n 7 => Ok(RecordType::MB),\r\n 8 => Ok(RecordType::MG),\r\n 9 => Ok(RecordType::MR),\r\n 10 => Ok(RecordType::NULL),\r\n 11 => Ok(RecordType::WKS),\r\n 12 => Ok(RecordType::PTR),\r\n 13 => Ok(RecordType::HINFO),\r\n 14 => Ok(RecordType::MINFO),\r\n 15 => Ok(RecordType::MX),\r\n 16 => Ok(RecordType::TXT),\r\n 252 => Ok(RecordType::AXFR),\r\n 253 => Ok(RecordType::MAILA),\r\n 255 => Ok(RecordType::Any),\r\n _ => Err(ErrorKind::InvalidRecordType(i).into())\r\n }\r\n }\r\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":148,"cells":{"blob_id":{"kind":"string","value":"0feafd9f6d9c3cad0a2254ecfa847e5ee4146f30"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"angelini/entity-query"},"path":{"kind":"string","value":"/src/csv_parser.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":5337,"string":"5,337"},"score":{"kind":"number","value":2.6875,"string":"2.6875"},"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 csv;\nuse scoped_threadpool::Pool;\nuse std::collections::HashMap;\n\nuse ast::AstNode;\nuse cli::Join;\nuse data::{Datum, Db, Ref, Error};\nuse filter::Filter;\n\n#[derive(Debug)]\npub struct CsvParser<'a> {\n filename: &'a str,\n entity: &'a str,\n time: &'a str,\n joins: &'a [Join],\n}\n\nimpl<'a> CsvParser<'a> {\n pub fn new(filename: &'a str, entity: &'a str, time: &'a str, joins: &'a [Join]) -> CsvParser<'a> {\n CsvParser {\n filename: filename,\n entity: entity,\n time: time,\n joins: joins,\n }\n }\n\n pub fn parse(self, db: &Db, pool: &mut Pool) -> Result<(Vec, Vec, usize), Error> {\n let mut rdr = try!(csv::Reader::from_file(self.filename));\n let headers = rdr.headers().expect(\"headers required to convert CSV\");\n\n let time_index = match headers.iter()\n .enumerate()\n .find(|&(_, h)| h == self.time) {\n Some((idx, _)) => idx,\n None => return Err(Error::MissingTimeHeader(self.time.to_owned())),\n };\n\n let mut eid = db.offset;\n let datums_res = rdr.records()\n .map(|row_res| {\n let row = try!(row_res);\n eid += 1;\n let datums = try!(Self::parse_row(row,\n &headers,\n time_index,\n eid,\n self.entity));\n Ok(datums)\n })\n .collect::>, Error>>();\n\n let datums = match datums_res {\n Ok(d) => d.into_iter().flat_map(|v| v).collect::>(),\n Err(e) => return Err(e),\n };\n\n let refs = self.find_refs(&datums, &db, pool);\n Ok((datums, refs, eid))\n }\n\n fn find_refs(&self, datums: &[Datum], db: &Db, pool: &mut Pool) -> Vec {\n self.joins\n .iter()\n .flat_map(|join| {\n let (column, query) = (&join.0, &join.1);\n let filter = Filter::new(&db, pool);\n self.find_refs_for_join(datums, column, query, filter)\n })\n .collect::>()\n }\n\n fn find_refs_for_join(&self, datums: &[Datum], column: &str, query: &str, filter: Filter)\n -> Vec {\n let attribute = format!(\"{}/{}\", self.entity, robotize(&column));\n let ast = AstNode::parse(&query).unwrap();\n\n let new_datums = datums.iter()\n .filter(|d| d.a == attribute)\n .cloned()\n .collect::>();\n let old_datums = filter.execute(&ast).datums;\n\n let index = index_by_value(old_datums);\n\n new_datums.iter()\n .flat_map(|new| Self::generate_refs(new, &index))\n .filter(|o| o.is_some())\n .map(|o| o.unwrap())\n .collect()\n }\n\n fn generate_refs(new: &Datum, index: &HashMap<&str, Vec<&Datum>>) -> Vec> {\n let new_entity = new.a.split('/').next().unwrap();\n\n match index.get(new.v.as_str()) {\n Some(old_matches) => {\n old_matches.iter()\n .map(|old| {\n let old_entity = old.a.split('/').next().unwrap();\n Some(Ref::new(new.e,\n format!(\"{}/{}\", new_entity, old_entity),\n old.e,\n new.t))\n })\n .collect()\n }\n None => vec![None],\n }\n }\n\n fn parse_row(row: Vec, headers: &[String], time_index: usize, eid: usize, entity: &str)\n -> Result, Error> {\n let time = match row[time_index].parse::() {\n Ok(t) => t,\n Err(_) => return Err(Error::TimeColumnTypeError(row[time_index].to_owned())),\n };\n let datums = headers.iter()\n .enumerate()\n .filter(|&(i, _)| i != time_index)\n .map(|(_, h)| h)\n .zip(row)\n .map(|(header, val)| {\n Datum::new(eid,\n format!(\"{}/{}\", entity, robotize(header)),\n val,\n time)\n })\n .collect();\n Ok(datums)\n }\n}\n\nfn robotize(string: &str) -> String {\n string.replace(\" \", \"_\")\n .to_lowercase()\n}\n\nfn index_by_value(datums: Vec<&Datum>) -> HashMap<&str, Vec<&Datum>> {\n let mut index = HashMap::new();\n for datum in datums {\n if let Some(mut foo) = index.insert(datum.v.as_str(), vec![datum]) {\n foo.push(datum)\n }\n }\n index\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":149,"cells":{"blob_id":{"kind":"string","value":"032882d7e5d528a62e79500f5598b67488a2df6f"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"luqmana/cgmath-rs"},"path":{"kind":"string","value":"/src/cgmath/vector.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":11652,"string":"11,652"},"score":{"kind":"number","value":2.59375,"string":"2.59375"},"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":"// Copyright 2013 The CGMath Developers. For a full listing of the authors,\n// refer to the AUTHORS file at the top-level directory of this distribution.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nuse std::fmt;\nuse std::num::{Zero, zero, One, one};\n\nuse angle::{Rad, atan2, acos};\nuse approx::ApproxEq;\nuse array::{Array, build};\nuse partial_ord::{PartOrdPrim, PartOrdFloat};\n\n/// A trait that specifies a range of numeric operations for vectors. Not all\n/// of these make sense from a linear algebra point of view, but are included\n/// for pragmatic reasons.\npub trait Vector\n<\n S: PartOrdPrim,\n Slice\n>\n: Array\n+ Neg\n+ Zero + One\n{\n #[inline] fn add_s(&self, s: S) -> Self { build(|i| self.i(i).add(&s)) }\n #[inline] fn sub_s(&self, s: S) -> Self { build(|i| self.i(i).sub(&s)) }\n #[inline] fn mul_s(&self, s: S) -> Self { build(|i| self.i(i).mul(&s)) }\n #[inline] fn div_s(&self, s: S) -> Self { build(|i| self.i(i).div(&s)) }\n #[inline] fn rem_s(&self, s: S) -> Self { build(|i| self.i(i).rem(&s)) }\n\n #[inline] fn add_v(&self, other: &Self) -> Self { build(|i| self.i(i).add(other.i(i))) }\n #[inline] fn sub_v(&self, other: &Self) -> Self { build(|i| self.i(i).sub(other.i(i))) }\n #[inline] fn mul_v(&self, other: &Self) -> Self { build(|i| self.i(i).mul(other.i(i))) }\n #[inline] fn div_v(&self, other: &Self) -> Self { build(|i| self.i(i).div(other.i(i))) }\n #[inline] fn rem_v(&self, other: &Self) -> Self { build(|i| self.i(i).rem(other.i(i))) }\n\n #[inline] fn neg_self(&mut self) { self.each_mut(|_, x| *x = x.neg()) }\n\n #[inline] fn add_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.add(&s)) }\n #[inline] fn sub_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.sub(&s)) }\n #[inline] fn mul_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.mul(&s)) }\n #[inline] fn div_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.div(&s)) }\n #[inline] fn rem_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.rem(&s)) }\n\n #[inline] fn add_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.add(other.i(i))) }\n #[inline] fn sub_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.sub(other.i(i))) }\n #[inline] fn mul_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.mul(other.i(i))) }\n #[inline] fn div_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.div(other.i(i))) }\n #[inline] fn rem_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.rem(other.i(i))) }\n\n /// The sum of each component of the vector.\n #[inline] fn comp_add(&self) -> S { self.fold(|a, b| a.add(b)) }\n\n /// The product of each component of the vector.\n #[inline] fn comp_mul(&self) -> S { self.fold(|a, b| a.mul(b)) }\n\n /// Vector dot product.\n #[inline] fn dot(&self, other: &Self) -> S { self.mul_v(other).comp_add() }\n\n /// The minimum component of the vector.\n #[inline] fn comp_min(&self) -> S { self.fold(|a, b| if *a < *b { *a } else {*b }) }\n\n /// The maximum component of the vector.\n #[inline] fn comp_max(&self) -> S { self.fold(|a, b| if *a > *b { *a } else {*b }) }\n}\n\n#[inline] pub fn dot>(a: V, b: V) -> S { a.dot(&b) }\n\n// Utility macro for generating associated functions for the vectors\nmacro_rules! vec(\n ($Self:ident <$S:ident> { $($field:ident),+ }, $n:expr) => (\n #[deriving(Eq, TotalEq, Clone, Hash)]\n pub struct $Self { $(pub $field: S),+ }\n\n impl<$S: Primitive> $Self<$S> {\n #[inline]\n pub fn new($($field: $S),+) -> $Self<$S> {\n $Self { $($field: $field),+ }\n }\n\n /// Construct a vector from a single value.\n #[inline]\n pub fn from_value(value: $S) -> $Self<$S> {\n $Self { $($field: value.clone()),+ }\n }\n\n /// The additive identity of the vector.\n #[inline]\n pub fn zero() -> $Self<$S> { $Self::from_value(zero()) }\n\n /// The multiplicative identity of the vector.\n #[inline]\n pub fn ident() -> $Self<$S> { $Self::from_value(one()) }\n }\n\n impl Add<$Self, $Self> for $Self {\n #[inline] fn add(&self, other: &$Self) -> $Self { self.add_v(other) }\n }\n\n impl Sub<$Self, $Self> for $Self {\n #[inline] fn sub(&self, other: &$Self) -> $Self { self.sub_v(other) }\n }\n\n impl Zero for $Self {\n #[inline] fn zero() -> $Self { $Self::from_value(zero()) }\n #[inline] fn is_zero(&self) -> bool { *self == zero() }\n }\n\n impl Neg<$Self> for $Self {\n #[inline] fn neg(&self) -> $Self { build(|i| self.i(i).neg()) }\n }\n\n impl Mul<$Self, $Self> for $Self {\n #[inline] fn mul(&self, other: &$Self) -> $Self { self.mul_v(other) }\n }\n\n impl One for $Self {\n #[inline] fn one() -> $Self { $Self::from_value(one()) }\n }\n\n impl Vector for $Self {}\n )\n)\n\nvec!(Vector2 { x, y }, 2)\nvec!(Vector3 { x, y, z }, 3)\nvec!(Vector4 { x, y, z, w }, 4)\n\narray!(impl Vector2 -> [S, ..2] _2)\narray!(impl Vector3 -> [S, ..3] _3)\narray!(impl Vector4 -> [S, ..4] _4)\n\n/// Operations specific to numeric two-dimensional vectors.\nimpl Vector2 {\n #[inline] pub fn unit_x() -> Vector2 { Vector2::new(one(), zero()) }\n #[inline] pub fn unit_y() -> Vector2 { Vector2::new(zero(), one()) }\n\n /// The perpendicular dot product of the vector and `other`.\n #[inline]\n pub fn perp_dot(&self, other: &Vector2) -> S {\n (self.x * other.y) - (self.y * other.x)\n }\n\n #[inline]\n pub fn extend(&self, z: S)-> Vector3 {\n Vector3::new(self.x.clone(), self.y.clone(), z)\n }\n}\n\n/// Operations specific to numeric three-dimensional vectors.\nimpl Vector3 {\n #[inline] pub fn unit_x() -> Vector3 { Vector3::new(one(), zero(), zero()) }\n #[inline] pub fn unit_y() -> Vector3 { Vector3::new(zero(), one(), zero()) }\n #[inline] pub fn unit_z() -> Vector3 { Vector3::new(zero(), zero(), one()) }\n\n /// Returns the cross product of the vector and `other`.\n #[inline]\n pub fn cross(&self, other: &Vector3) -> Vector3 {\n Vector3::new((self.y * other.z) - (self.z * other.y),\n (self.z * other.x) - (self.x * other.z),\n (self.x * other.y) - (self.y * other.x))\n }\n\n /// Calculates the cross product of the vector and `other`, then stores the\n /// result in `self`.\n #[inline]\n pub fn cross_self(&mut self, other: &Vector3) {\n *self = self.cross(other)\n }\n\n #[inline]\n pub fn extend(&self, w: S)-> Vector4 {\n Vector4::new(self.x.clone(), self.y.clone(), self.z.clone(), w)\n }\n\n #[inline]\n pub fn truncate(&self)-> Vector2 {\n Vector2::new(self.x.clone(), self.y.clone()) //ignore Z\n }\n}\n\n/// Operations specific to numeric four-dimensional vectors.\nimpl Vector4 {\n #[inline] pub fn unit_x() -> Vector4 { Vector4::new(one(), zero(), zero(), zero()) }\n #[inline] pub fn unit_y() -> Vector4 { Vector4::new(zero(), one(), zero(), zero()) }\n #[inline] pub fn unit_z() -> Vector4 { Vector4::new(zero(), zero(), one(), zero()) }\n #[inline] pub fn unit_w() -> Vector4 { Vector4::new(zero(), zero(), zero(), one()) }\n\n #[inline]\n pub fn truncate(&self)-> Vector3 {\n Vector3::new(self.x.clone(), self.y.clone(), self.z.clone()) //ignore W\n }\n}\n\n/// Specifies geometric operations for vectors. This is only implemented for\n/// 2-dimensional and 3-dimensional vectors.\npub trait EuclideanVector\n<\n S: PartOrdFloat,\n Slice\n>\n: Vector\n+ ApproxEq\n{\n /// Returns `true` if the vector is perpendicular (at right angles to)\n /// the other vector.\n fn is_perpendicular(&self, other: &Self) -> bool {\n self.dot(other).approx_eq(&zero())\n }\n\n /// Returns the squared length of the vector. This does not perform an\n /// expensive square root operation like in the `length` method and can\n /// therefore be more efficient for comparing the lengths of two vectors.\n #[inline]\n fn length2(&self) -> S {\n self.dot(self)\n }\n\n /// The norm of the vector.\n #[inline]\n fn length(&self) -> S {\n self.dot(self).sqrt()\n }\n\n /// The angle between the vector and `other`.\n fn angle(&self, other: &Self) -> Rad;\n\n /// Returns a vector with the same direction, but with a `length` (or\n /// `norm`) of `1`.\n #[inline]\n fn normalize(&self) -> Self {\n self.normalize_to(one::())\n }\n\n /// Returns a vector with the same direction and a given `length`.\n #[inline]\n fn normalize_to(&self, length: S) -> Self {\n self.mul_s(length / self.length())\n }\n\n /// Returns the result of linarly interpolating the length of the vector\n /// towards the length of `other` by the specified amount.\n #[inline]\n fn lerp(&self, other: &Self, amount: S) -> Self {\n self.add_v(&other.sub_v(self).mul_s(amount))\n }\n\n /// Normalises the vector to a length of `1`.\n #[inline]\n fn normalize_self(&mut self) {\n let rlen = self.length().recip();\n self.mul_self_s(rlen);\n }\n\n /// Normalizes the vector to `length`.\n #[inline]\n fn normalize_self_to(&mut self, length: S) {\n let n = length / self.length();\n self.mul_self_s(n);\n }\n\n /// Linearly interpolates the length of the vector towards the length of\n /// `other` by the specified amount.\n fn lerp_self(&mut self, other: &Self, amount: S) {\n let v = other.sub_v(self).mul_s(amount);\n self.add_self_v(&v);\n }\n}\n\nimpl>\nEuclideanVector for Vector2 {\n #[inline]\n fn angle(&self, other: &Vector2) -> Rad {\n atan2(self.perp_dot(other), self.dot(other))\n }\n}\n\nimpl>\nEuclideanVector for Vector3 {\n #[inline]\n fn angle(&self, other: &Vector3) -> Rad {\n atan2(self.cross(other).length(), self.dot(other))\n }\n}\n\nimpl>\nEuclideanVector for Vector4 {\n #[inline]\n fn angle(&self, other: &Vector4) -> Rad {\n acos(self.dot(other) / (self.length() * other.length()))\n }\n}\n\nimpl fmt::Show for Vector2 {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f.buf, \"[{}, {}]\", self.x, self.y)\n }\n}\n\nimpl fmt::Show for Vector3 {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f.buf, \"[{}, {}, {}]\", self.x, self.y, self.z)\n }\n}\n\nimpl fmt::Show for Vector4 {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f.buf, \"[{}, {}, {}, {}]\", self.x, self.y, self.z, self.w)\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":150,"cells":{"blob_id":{"kind":"string","value":"aa2133a0602ed220752e77bbc052bd17dd1913e8"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"mac-l1/RemarkableFramebuffer"},"path":{"kind":"string","value":"/rust-implementation/librustpad/src/ev.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1309,"string":"1,309"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"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 evdev;\nuse epoll;\nuse std;\n\npub trait EvdevHandler {\n fn on_init(&mut self, name: String, device: &mut evdev::Device);\n fn on_event(&mut self, device: &String, event: evdev::raw::input_event);\n}\n\npub fn start_evdev(path: String, handler: &mut H) {\n let mut dev = evdev::Device::open(&path).unwrap();\n let devn = unsafe {\n let mut ptr = std::mem::transmute(dev.name().as_ptr());\n std::ffi::CString::from_raw(ptr).into_string().unwrap()\n };\n\n let mut v = vec![\n epoll::Event {\n events: (epoll::Events::EPOLLET | epoll::Events::EPOLLIN | epoll::Events::EPOLLPRI)\n .bits(),\n data: 0,\n },\n ];\n\n let epfd = epoll::create(false).unwrap();\n epoll::ctl(epfd, epoll::ControlOptions::EPOLL_CTL_ADD, dev.fd(), v[0]).unwrap();\n\n // init callback\n handler.on_init(devn.clone(), &mut dev);\n\n loop {\n // -1 indefinite wait but it is okay because our EPOLL FD is watching on ALL input devices at once\n let res = epoll::wait(epfd, -1, &mut v[0..1]).unwrap();\n if res != 1 {\n println!(\"WARN: epoll_wait returned {0}\", res);\n }\n\n for ev in dev.events_no_sync().unwrap() {\n // event callback\n handler.on_event(&devn, ev);\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":151,"cells":{"blob_id":{"kind":"string","value":"3bde34b786d73b595b467dc049cf9385c9d19032"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"scottschroeder/storyestimate"},"path":{"kind":"string","value":"/src/webapp/apikey.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2398,"string":"2,398"},"score":{"kind":"number","value":3.25,"string":"3.25"},"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 hyper::header::Basic;\nuse rocket::Outcome;\nuse rocket::http::Status;\nuse rocket::request::{self, FromRequest, Request};\nuse std::str::FromStr;\n\n#[derive(Serialize, Deserialize)]\n#[derive(Debug, PartialEq, Eq, Clone)]\npub struct APIKey {\n pub user_id: String,\n pub user_key: Option,\n}\n\nimpl<'a, 'r> FromRequest<'a, 'r> for APIKey {\n type Error = ();\n\n fn from_request(request: &'a Request<'r>) -> request::Outcome {\n let basic_auth = get_basic_auth(request);\n let token_auth = get_token_auth(request);\n match (basic_auth, token_auth) {\n (None, None) => Outcome::Failure((Status::Unauthorized, ())),\n (Some(_), Some(_)) => {\n warn!(\"User passed both a TOK header and HTTP Basic Auth\");\n Outcome::Failure((Status::Unauthorized, ()))\n },\n (Some(auth), None) => Outcome::Success(auth),\n (None, Some(auth)) => Outcome::Success(auth),\n }\n }\n}\n\n\nfn get_basic_auth<'a, 'r>(request: &'a Request<'r>) -> Option {\n let user_auth: String = match request.headers().get_one(\"Authorization\") {\n Some(auth_data) => auth_data.to_string(),\n None => return None,\n };\n\n let base64_encoded_auth = user_auth.replace(\"Basic \", \"\");\n let authdata: Basic = match Basic::from_str(&base64_encoded_auth) {\n Ok(authdata) => authdata,\n Err(_) => return None,\n };\n Some(APIKey {\n user_id: authdata.username,\n user_key: authdata.password,\n })\n}\n\nfn get_token_auth<'a, 'r>(request: &'a Request<'r>) -> Option {\n let user_token: String = match request.headers().get_one(\"X-API-Key\") {\n Some(auth_data) => auth_data.to_string(),\n None => return None,\n };\n\n let user_data: Vec<&str> = user_token.split(':').collect();\n match user_data.len() {\n 0 => {\n warn!(\"User passed empty token\");\n None\n },\n 1 => {\n Some(APIKey {\n user_id: user_data[0].to_string(),\n user_key: None,\n })\n },\n 2 => {\n Some(APIKey {\n user_id: user_data[0].to_string(),\n user_key: Some(user_data[1].to_string()),\n })\n },\n x => {\n warn!(\"User passed token with too many fields ({})\", x);\n None\n },\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":152,"cells":{"blob_id":{"kind":"string","value":"61759363a0b5888bd9ee9423e9cd5a7d9ebab4a3"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"lutostag/pincers"},"path":{"kind":"string","value":"/src/read.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1110,"string":"1,110"},"score":{"kind":"number","value":2.859375,"string":"2.859375"},"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 anyhow::Result;\nuse reqwest;\n\nuse std::collections::HashSet;\nuse std::fs::File;\nuse std::io::{self, Read};\n\nlazy_static! {\n static ref REMOTE_SCHEMES: HashSet<&'static str> = hashset! {\n \"https\", \"http\", \"ftps\", \"ftp\"\n };\n}\n\npub fn is_remote(url: &str) -> bool {\n if let Ok(url) = reqwest::Url::parse(url) {\n return REMOTE_SCHEMES.contains(&url.scheme());\n }\n false\n}\n\npub fn download(url: &str) -> Result> {\n info!(\"Getting script: {}\", url);\n let mut body = Vec::::new();\n\n if url == \"-\" {\n debug!(\"Trying to read from stdin\");\n io::stdin().read_to_end(&mut body)?;\n } else if is_remote(&url) {\n debug!(\"Trying to read from remote {}\", &url);\n reqwest::get(url)?\n .error_for_status()?\n .read_to_end(&mut body)?;\n } else {\n debug!(\"Trying to read from local {}\", &url);\n File::open(url)?.read_to_end(&mut body)?;\n };\n match std::str::from_utf8(&body) {\n Ok(val) => debug!(\"Read contents\\n{}\", val),\n Err(_) => debug!(\"Read content is binary\"),\n }\n Ok(body)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":153,"cells":{"blob_id":{"kind":"string","value":"d5ad882aa012e47f2a4a629d9c9b00c41c9215b8"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"sdenel/tiny-static-web-server"},"path":{"kind":"string","value":"/src/path_to_key.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1707,"string":"1,707"},"score":{"kind":"number","value":3.40625,"string":"3.40625"},"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::HashSet;\nuse std::sync::Mutex;\n\n// TODO: this function should return the nearest existing index.html, not root\n// TODO: Should the webapp behavior be activated with a flag? Currently, 404 requests are redirected to /index.html with no warning even for non webapps.\npub fn path_to_key(path: &str, known_keys: &Mutex>) -> String {\n let key = path.to_string();\n if key.ends_with(\"/\") {\n let key_with_index = key.to_owned() + \"index.html\";\n if known_keys.lock().unwrap().contains(&key_with_index) {\n return key_with_index;\n }\n }\n if !key.contains(\".\") {\n // We suppose that is the request is not for a file, and we can't find the associated /index.html, then the path is aimed for a webapp in index.html\n return \"/index.html\".to_string();\n }\n return key;\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn path_to_key1() {\n assert_eq!(\n \"/hello.html\",\n path_to_key(\"/hello.html\", &Mutex::new(HashSet::new()))\n );\n }\n\n #[test]\n fn path_to_key2() {\n assert_eq!(\n \"/index.html\",\n path_to_key(\"/\", &Mutex::new(HashSet::new()))\n );\n }\n\n #[test]\n fn path_to_key3() {\n assert_eq!(\n \"/index.html\",\n path_to_key(\"/stuart/\", &Mutex::new(HashSet::new()))\n );\n }\n\n #[test]\n fn path_to_key4() {\n assert_eq!(\n \"/stuart/index.html\",\n path_to_key(\n \"/stuart/\",\n &Mutex::new(\n vec!(\"/stuart/index.html\".to_string())\n .into_iter().collect()),\n )\n );\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":154,"cells":{"blob_id":{"kind":"string","value":"9bd150b9f60cc944de9853f6f305b8a9e3e2f106"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"iamparnab/rusty-tree"},"path":{"kind":"string","value":"/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1261,"string":"1,261"},"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":"fn main() {\n for i in 1..4 {\n draw_tree_segment(i);\n }\n draw_stem();\n draw_base();\n}\n\nconst HEIGHT: i32 = 12;\nconst WIDTH: i32 = 1 + (HEIGHT - 1) * 2; // AP\nconst STEM_WIDTH: i32 = HEIGHT / 3;\nconst STEM_HEIGHT: i32 = HEIGHT / 3;\nconst BASE_WIDTH: i32 = WIDTH * 2;\n\nfn draw_tree_segment(level: i32) {\n let mut stars = 1;\n\n for i in 1..(HEIGHT + 1) {\n // Chop off the head if level is not 1\n if !(level > 1 && i < HEIGHT * 10 / 15) {\n add_padding();\n // i - 1, because, we need zero space at last row\n for _ in 1..((WIDTH / 2) - (i - 1) + 1) {\n print!(\" \");\n }\n for _ in 1..(stars + 1) {\n print!(\"^\");\n }\n println!();\n }\n\n stars += 2;\n }\n}\n\nfn draw_stem() {\n for _ in 1..(STEM_HEIGHT + 1) {\n add_padding();\n for _ in 1..(WIDTH / 2 - STEM_WIDTH / 2 + 1) {\n print!(\" \")\n }\n for _ in 1..(STEM_WIDTH + 1) {\n print!(\"|\")\n }\n println!()\n }\n}\n\nfn draw_base() {\n for _ in 1..(BASE_WIDTH + 1) {\n print!(\"*\")\n }\n println!()\n}\n\nfn add_padding() {\n for _ in 1..BASE_WIDTH / 2 - WIDTH / 2 + 1 {\n print!(\" \")\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":155,"cells":{"blob_id":{"kind":"string","value":"1a7d103e7b9a678d8265489b1b92fb76d6a6420f"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"madskjeldgaard/nannou"},"path":{"kind":"string","value":"/nannou_laser/src/ffi.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":26593,"string":"26,593"},"score":{"kind":"number","value":2.953125,"string":"2.953125"},"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":"//! Expose a C compatible interface.\n\nuse std::collections::HashMap;\nuse std::ffi::CString;\nuse std::fmt;\nuse std::io;\nuse std::os::raw;\nuse std::sync::{Arc, Mutex};\nuse std::time::{Duration, Instant};\n\n/// Allows for detecting and enumerating laser DACs on a network and establishing new streams of\n/// communication with them.\n#[repr(C)]\npub struct Api {\n inner: *mut ApiInner,\n}\n\n/// A handle to a non-blocking DAC detection thread.\n#[repr(C)]\npub struct DetectDacsAsync {\n inner: *mut DetectDacsAsyncInner,\n}\n\n/// Represents a DAC that has been detected on the network along with any information collected\n/// about the DAC in the detection process.\n#[repr(C)]\n#[derive(Clone, Copy)]\npub struct DetectedDac {\n pub kind: DetectedDacKind,\n}\n\n/// A union for distinguishing between the kind of LASER DAC that was detected. Currently, only\n/// EtherDream is supported, however this will gain more variants as more protocols are added (e.g.\n/// AVB).\n#[repr(C)]\n#[derive(Clone, Copy)]\npub union DetectedDacKind {\n pub ether_dream: DacEtherDream,\n}\n\n/// An Ether Dream DAC that was detected on the network.\n#[repr(C)]\n#[derive(Clone, Copy, Debug)]\npub struct DacEtherDream {\n pub broadcast: ether_dream::protocol::DacBroadcast,\n pub source_addr: SocketAddr,\n}\n\n/// A set of stream configuration parameters applied to the initialisation of both `Raw` and\n/// `Frame` streams.\n#[repr(C)]\n#[derive(Clone, Copy, Debug)]\npub struct StreamConfig {\n /// A valid pointer to a `DetectedDac` that should be targeted.\n pub detected_dac: *const DetectedDac,\n /// The rate at which the DAC should process points per second.\n ///\n /// This value should be no greater than the detected DAC's `max_point_hz`.\n pub point_hz: raw::c_uint,\n /// The maximum latency specified as a number of points.\n ///\n /// Each time the laser indicates its \"fullness\", the raw stream will request enough points\n /// from the render function to fill the DAC buffer up to `latency_points`.\n ///\n /// This value should be no greaterthan the DAC's `buffer_capacity`.\n pub latency_points: raw::c_uint,\n}\n\n#[repr(C)]\n#[derive(Clone, Copy, Debug)]\npub enum IpAddrVersion {\n V4,\n V6,\n}\n\n#[repr(C)]\n#[derive(Clone, Copy, Debug)]\npub struct IpAddr {\n pub version: IpAddrVersion,\n /// 4 bytes used for `V4`, 16 bytes used for `V6`.\n pub bytes: [raw::c_uchar; 16],\n}\n\n#[repr(C)]\n#[derive(Clone, Copy, Debug)]\npub struct SocketAddr {\n pub ip: IpAddr,\n pub port: raw::c_ushort,\n}\n\n/// A handle to a stream that requests frames of LASER data from the user.\n///\n/// Each \"frame\" has an optimisation pass applied that optimises the path for inertia, minimal\n/// blanking, point de-duplication and segment order.\n#[repr(C)]\npub struct FrameStream {\n inner: *mut FrameStreamInner,\n}\n\n/// A handle to a raw LASER stream that requests the exact number of points that the DAC is\n/// awaiting in each call to the user's callback.\n#[repr(C)]\npub struct RawStream {\n inner: *mut RawStreamInner,\n}\n\n#[repr(C)]\n#[derive(Clone, Copy)]\npub enum Result {\n Success = 0,\n DetectDacFailed,\n BuildStreamFailed,\n DetectDacsAsyncFailed,\n}\n\n/// A set of stream configuration parameters unique to `Frame` streams.\n#[repr(C)]\n#[derive(Clone, Debug)]\npub struct FrameStreamConfig {\n pub stream_conf: StreamConfig,\n /// The rate at which the stream will attempt to present images via the DAC. This value is used\n /// in combination with the DAC's `point_hz` in order to determine how many points should be\n /// used to draw each frame. E.g.\n ///\n /// ```ignore\n /// let points_per_frame = point_hz / frame_hz;\n /// ```\n ///\n /// This is simply used as a minimum value. E.g. if some very simple geometry is submitted, this\n /// allows the DAC to spend more time creating the path for the image. However, if complex geometry\n /// is submitted that would require more than the ideal `points_per_frame`, the DAC may not be able\n /// to achieve the desired `frame_hz` when drawing the path while also taking the\n /// `distance_per_point` and `radians_per_point` into consideration.\n pub frame_hz: u32,\n /// Configuration options for eulerian circuit interpolation.\n pub interpolation_conf: crate::stream::frame::opt::InterpolationConfig,\n}\n\n#[repr(C)]\npub struct Frame {\n inner: *mut FrameInner,\n}\n\n#[repr(C)]\npub struct Buffer {\n inner: *mut BufferInner,\n}\n\nstruct FrameInner(*mut crate::stream::frame::Frame);\n\nstruct BufferInner(*mut crate::stream::raw::Buffer);\n\nstruct ApiInner {\n inner: crate::Api,\n last_error: Option,\n}\n\nstruct DetectDacsAsyncInner {\n _inner: crate::DetectDacsAsync,\n dacs: Arc>>,\n last_error: Arc>>,\n}\n\nstruct FrameStreamModel(*mut raw::c_void, FrameRenderCallback, RawRenderCallback);\nstruct RawStreamModel(*mut raw::c_void, RawRenderCallback);\n\nunsafe impl Send for FrameStreamModel {}\nunsafe impl Send for RawStreamModel {}\n\nstruct FrameStreamInner(crate::FrameStream);\nstruct RawStreamInner(crate::RawStream);\n\n/// Cast to `extern fn(*mut raw::c_void, *mut Frame)` internally.\n//pub type FrameRenderCallback = *const raw::c_void;\npub type FrameRenderCallback = extern \"C\" fn(*mut raw::c_void, *mut Frame);\n/// Cast to `extern fn(*mut raw::c_void, *mut Buffer)` internally.\n//pub type RawRenderCallback = *const raw::c_void;\npub type RawRenderCallback = extern \"C\" fn(*mut raw::c_void, *mut Buffer);\n\n/// Given some uninitialized pointer to an `Api` struct, fill it with a new Api instance.\n#[no_mangle]\npub unsafe extern \"C\" fn api_new(api: *mut Api) {\n let inner = crate::Api::new();\n let last_error = None;\n let boxed_inner = Box::new(ApiInner { inner, last_error });\n (*api).inner = Box::into_raw(boxed_inner);\n}\n\n/// Given some uninitialised pointer to a `DetectDacsAsync` struct, fill it with a new instance.\n///\n/// If the given `timeout_secs` is `0`, DAC detection will never timeout and detected DACs that no\n/// longer broadcast will remain accessible in the device map.\n#[no_mangle]\npub unsafe extern \"C\" fn detect_dacs_async(\n api: *mut Api,\n timeout_secs: raw::c_float,\n detect_dacs: *mut DetectDacsAsync,\n) -> Result {\n let api: &mut ApiInner = &mut (*(*api).inner);\n let duration = if timeout_secs == 0.0 {\n None\n } else {\n let secs = timeout_secs as u64;\n let nanos = ((timeout_secs - secs as raw::c_float) * 1_000_000_000.0) as u32;\n Some(std::time::Duration::new(secs, nanos))\n };\n let boxed_detect_dacs_inner = match detect_dacs_async_inner(&api.inner, duration) {\n Ok(detector) => Box::new(detector),\n Err(err) => {\n api.last_error = Some(err_to_cstring(&err));\n return Result::DetectDacsAsyncFailed;\n }\n };\n (*detect_dacs).inner = Box::into_raw(boxed_detect_dacs_inner);\n Result::Success\n}\n\n/// Retrieve a list of the currently available DACs.\n///\n/// Calling this function should never block, and simply provide the list of DACs that have\n/// broadcast their availability within the last specified DAC timeout duration.\n#[no_mangle]\npub unsafe extern \"C\" fn available_dacs(\n detect_dacs_async: *mut DetectDacsAsync,\n first_dac: *mut *mut DetectedDac,\n len: *mut raw::c_uint,\n) {\n let detect_dacs_async: &mut DetectDacsAsyncInner = &mut (*(*detect_dacs_async).inner);\n *first_dac = std::ptr::null_mut();\n *len = 0;\n if let Ok(dacs) = detect_dacs_async.dacs.lock() {\n if !dacs.is_empty() {\n let mut dacs: Box<[_]> = dacs\n .values()\n .map(|&(_, ref dac)| detected_dac_to_ffi(dac.clone()))\n .collect();\n *len = dacs.len() as _;\n *first_dac = dacs.as_mut_ptr();\n std::mem::forget(dacs);\n }\n }\n}\n\n/// Block the current thread until a new DAC is detected and return it.\n#[no_mangle]\npub unsafe extern \"C\" fn detect_dac(api: *mut Api, detected_dac: *mut DetectedDac) -> Result {\n let api: &mut ApiInner = &mut (*(*api).inner);\n let mut iter = match api.inner.detect_dacs() {\n Err(err) => {\n api.last_error = Some(err_to_cstring(&err));\n return Result::DetectDacFailed;\n }\n Ok(iter) => iter,\n };\n match iter.next() {\n None => return Result::DetectDacFailed,\n Some(res) => match res {\n Ok(dac) => {\n *detected_dac = detected_dac_to_ffi(dac);\n return Result::Success;\n }\n Err(err) => {\n api.last_error = Some(err_to_cstring(&err));\n return Result::DetectDacFailed;\n }\n },\n }\n}\n\n/// Initialise the given frame stream configuration with default values.\n#[no_mangle]\npub unsafe extern \"C\" fn frame_stream_config_default(conf: *mut FrameStreamConfig) {\n let stream_conf = default_stream_config();\n let frame_hz = crate::stream::DEFAULT_FRAME_HZ;\n let interpolation_conf = crate::stream::frame::opt::InterpolationConfig::start().build();\n *conf = FrameStreamConfig {\n stream_conf,\n frame_hz,\n interpolation_conf,\n };\n}\n\n/// Initialise the given raw stream configuration with default values.\n#[no_mangle]\npub unsafe extern \"C\" fn stream_config_default(conf: *mut StreamConfig) {\n *conf = default_stream_config();\n}\n\n/// Spawn a new frame rendering stream.\n///\n/// The `frame_render_callback` is called each time the stream is ready for a new `Frame` of laser\n/// points. Each \"frame\" has an optimisation pass applied that optimises the path for inertia,\n/// minimal blanking, point de-duplication and segment order.\n///\n/// The `process_raw_callback` allows for optionally processing the raw points before submission to\n/// the DAC. This might be useful for:\n///\n/// - applying post-processing effects onto the optimised, interpolated points.\n/// - monitoring the raw points resulting from the optimisation and interpolation processes.\n/// - tuning brightness of colours based on safety zones.\n///\n/// The given function will get called right before submission of the optimised, interpolated\n/// buffer.\n#[no_mangle]\npub unsafe extern \"C\" fn new_frame_stream(\n api: *mut Api,\n stream: *mut FrameStream,\n config: *const FrameStreamConfig,\n callback_data: *mut raw::c_void,\n frame_render_callback: FrameRenderCallback,\n process_raw_callback: RawRenderCallback,\n) -> Result {\n let api: &mut ApiInner = &mut (*(*api).inner);\n let model = FrameStreamModel(callback_data, frame_render_callback, process_raw_callback);\n\n fn render_fn(model: &mut FrameStreamModel, frame: &mut crate::stream::frame::Frame) {\n let FrameStreamModel(callback_data_ptr, frame_render_callback, _) = *model;\n let mut inner = FrameInner(frame);\n let mut frame = Frame { inner: &mut inner };\n frame_render_callback(callback_data_ptr, &mut frame);\n }\n\n let mut builder = api\n .inner\n .new_frame_stream(model, render_fn)\n .point_hz((*config).stream_conf.point_hz as _)\n .latency_points((*config).stream_conf.latency_points as _)\n .frame_hz((*config).frame_hz as _);\n\n fn process_raw_fn(model: &mut FrameStreamModel, buffer: &mut crate::stream::raw::Buffer) {\n let FrameStreamModel(callback_data_ptr, _, process_raw_callback) = *model;\n let mut inner = BufferInner(buffer);\n let mut buffer = Buffer { inner: &mut inner };\n process_raw_callback(callback_data_ptr, &mut buffer);\n }\n\n builder = builder.process_raw(process_raw_fn);\n\n if (*config).stream_conf.detected_dac != std::ptr::null() {\n let ffi_dac = (*(*config).stream_conf.detected_dac).clone();\n let detected_dac = detected_dac_from_ffi(ffi_dac);\n builder = builder.detected_dac(detected_dac);\n }\n\n let inner = match builder.build() {\n Err(err) => {\n api.last_error = Some(err_to_cstring(&err));\n return Result::BuildStreamFailed;\n }\n Ok(stream) => Box::new(FrameStreamInner(stream)),\n };\n (*stream).inner = Box::into_raw(inner);\n Result::Success\n}\n\n/// Spawn a new frame rendering stream.\n///\n/// A raw LASER stream requests the exact number of points that the DAC is awaiting in each call to\n/// the user's `process_raw_callback`. Keep in mind that no optimisation passes are applied. When\n/// using a raw stream, this is the responsibility of the user.\n#[no_mangle]\npub unsafe extern \"C\" fn new_raw_stream(\n api: *mut Api,\n stream: *mut RawStream,\n config: *const StreamConfig,\n callback_data: *mut raw::c_void,\n process_raw_callback: RawRenderCallback,\n) -> Result {\n let api: &mut ApiInner = &mut (*(*api).inner);\n let model = RawStreamModel(callback_data, process_raw_callback);\n\n fn render_fn(model: &mut RawStreamModel, buffer: &mut crate::stream::raw::Buffer) {\n let RawStreamModel(callback_data_ptr, raw_render_callback) = *model;\n let mut inner = BufferInner(buffer);\n let mut buffer = Buffer { inner: &mut inner };\n raw_render_callback(callback_data_ptr, &mut buffer);\n }\n\n let mut builder = api\n .inner\n .new_raw_stream(model, render_fn)\n .point_hz((*config).point_hz as _)\n .latency_points((*config).latency_points as _);\n\n if (*config).detected_dac != std::ptr::null() {\n let ffi_dac = (*(*config).detected_dac).clone();\n let detected_dac = detected_dac_from_ffi(ffi_dac);\n builder = builder.detected_dac(detected_dac);\n }\n\n let inner = match builder.build() {\n Err(err) => {\n api.last_error = Some(err_to_cstring(&err));\n return Result::BuildStreamFailed;\n }\n Ok(stream) => Box::new(RawStreamInner(stream)),\n };\n (*stream).inner = Box::into_raw(inner);\n\n Result::Success\n}\n\n/// Update the rate at which the DAC should process points per second.\n///\n/// This value should be no greater than the detected DAC's `max_point_hz`.\n///\n/// By default this value is `stream::DEFAULT_POINT_HZ`.\n///\n/// Returns `true` on success or `false` if the communication channel was closed.\npub unsafe extern \"C\" fn frame_stream_set_point_hz(\n stream: *const FrameStream,\n point_hz: u32,\n) -> bool {\n let stream: &FrameStream = &*stream;\n (*stream.inner).0.set_point_hz(point_hz).is_ok()\n}\n\n/// The maximum latency specified as a number of points.\n///\n/// Each time the laser indicates its \"fullness\", the raw stream will request enough points\n/// from the render function to fill the DAC buffer up to `latency_points`.\n///\n/// This value should be no greaterthan the DAC's `buffer_capacity`.\n///\n/// Returns `true` on success or `false` if the communication channel was closed.\npub unsafe extern \"C\" fn frame_stream_set_latency_points(\n stream: *const FrameStream,\n points: u32,\n) -> bool {\n let stream: &FrameStream = &*stream;\n (*stream.inner).0.set_latency_points(points).is_ok()\n}\n\n/// Update the `distance_per_point` field of the interpolation configuration used within the\n/// optimisation pass for frames. This represents the minimum distance the interpolator can travel\n/// along an edge before a new point is required.\n///\n/// The value will be updated on the laser thread prior to requesting the next frame.\n///\n/// Returns `true` on success or `false` if the communication channel was closed.\npub unsafe extern \"C\" fn frame_stream_set_distance_per_point(\n stream: *const FrameStream,\n distance_per_point: f32,\n) -> bool {\n let stream: &FrameStream = &*stream;\n (*stream.inner)\n .0\n .set_distance_per_point(distance_per_point)\n .is_ok()\n}\n\n/// Update the `blank_delay_points` field of the interpolation configuration. This represents the\n/// number of points to insert at the end of a blank to account for light modulator delay.\n///\n/// The value will be updated on the laser thread prior to requesting the next frame.\n///\n/// Returns `true` on success or `false` if the communication channel was closed.\npub unsafe extern \"C\" fn frame_stream_set_blank_delay_points(\n stream: *const FrameStream,\n points: u32,\n) -> bool {\n let stream: &FrameStream = &*stream;\n (*stream.inner).0.set_blank_delay_points(points).is_ok()\n}\n\n/// Update the `radians_per_point` field of the interpolation configuration. This represents the\n/// amount of delay to add based on the angle of the corner in radians.\n///\n/// The value will be updated on the laser thread prior to requesting the next frame.\n///\n/// Returns `true` on success or `false` if the communication channel was closed.\npub unsafe extern \"C\" fn frame_stream_set_radians_per_point(\n stream: *const FrameStream,\n radians_per_point: f32,\n) -> bool {\n let stream: &FrameStream = &*stream;\n (*stream.inner)\n .0\n .set_radians_per_point(radians_per_point)\n .is_ok()\n}\n\n/// Update the rate at which the stream will attempt to present images via the DAC. This value is\n/// used in combination with the DAC's `point_hz` in order to determine how many points should be\n/// used to draw each frame. E.g.\n///\n/// ```ignore\n/// let points_per_frame = point_hz / frame_hz;\n/// ```\n///\n/// This is simply used as a minimum value. E.g. if some very simple geometry is submitted, this\n/// allows the DAC to spend more time creating the path for the image. However, if complex geometry\n/// is submitted that would require more than the ideal `points_per_frame`, the DAC may not be able\n/// to achieve the desired `frame_hz` when drawing the path while also taking the\n/// `distance_per_point` and `radians_per_point` into consideration.\n///\n/// The value will be updated on the laser thread prior to requesting the next frame.\n///\n/// Returns `true` on success or `false` if the communication channel was closed.\npub unsafe extern \"C\" fn frame_stream_set_frame_hz(\n stream: *const FrameStream,\n frame_hz: u32,\n) -> bool {\n let stream: &FrameStream = &*stream;\n (*stream.inner).0.set_frame_hz(frame_hz).is_ok()\n}\n\n/// Update the rate at which the DAC should process points per second.\n///\n/// This value should be no greater than the detected DAC's `max_point_hz`.\n///\n/// By default this value is `stream::DEFAULT_POINT_HZ`.\n///\n/// Returns `true` on success or `false` if the communication channel was closed.\npub unsafe extern \"C\" fn raw_stream_set_point_hz(stream: *const RawStream, point_hz: u32) -> bool {\n let stream: &RawStream = &*stream;\n (*stream.inner).0.set_point_hz(point_hz).is_ok()\n}\n\n/// The maximum latency specified as a number of points.\n///\n/// Each time the laser indicates its \"fullness\", the raw stream will request enough points\n/// from the render function to fill the DAC buffer up to `latency_points`.\n///\n/// This value should be no greaterthan the DAC's `buffer_capacity`.\n///\n/// Returns `true` on success or `false` if the communication channel was closed.\npub unsafe extern \"C\" fn raw_stream_set_latency_points(\n stream: *const RawStream,\n points: u32,\n) -> bool {\n let stream: &RawStream = &*stream;\n (*stream.inner).0.set_latency_points(points).is_ok()\n}\n\n/// Add a sequence of consecutive points separated by blank space.\n///\n/// If some points already exist in the frame, this method will create a blank segment between the\n/// previous point and the first point before appending this sequence.\n#[no_mangle]\npub unsafe extern \"C\" fn frame_add_points(\n frame: *mut Frame,\n points: *const crate::Point,\n len: usize,\n) {\n let frame = &mut *frame;\n let points = std::slice::from_raw_parts(points, len);\n (*(*frame.inner).0).add_points(points.iter().cloned());\n}\n\n/// Add a sequence of consecutive lines.\n///\n/// If some points already exist in the frame, this method will create a blank segment between the\n/// previous point and the first point before appending this sequence.\n#[no_mangle]\npub unsafe extern \"C\" fn frame_add_lines(\n frame: *mut Frame,\n points: *const crate::Point,\n len: usize,\n) {\n let frame = &mut *frame;\n let points = std::slice::from_raw_parts(points, len);\n (*(*frame.inner).0).add_lines(points.iter().cloned());\n}\n\n/// Retrieve the current `frame_hz` at the time of rendering this `Frame`.\n#[no_mangle]\npub unsafe extern \"C\" fn frame_hz(frame: *const Frame) -> u32 {\n (*(*(*frame).inner).0).frame_hz()\n}\n\n/// Retrieve the current `point_hz` at the time of rendering this `Frame`.\n#[no_mangle]\npub unsafe extern \"C\" fn frame_point_hz(frame: *const Frame) -> u32 {\n (*(*(*frame).inner).0).point_hz()\n}\n\n/// Retrieve the current `latency_points` at the time of rendering this `Frame`.\n#[no_mangle]\npub unsafe extern \"C\" fn frame_latency_points(frame: *const Frame) -> u32 {\n (*(*(*frame).inner).0).latency_points()\n}\n\n/// Retrieve the current ideal `points_per_frame` at the time of rendering this `Frame`.\n#[no_mangle]\npub unsafe extern \"C\" fn points_per_frame(frame: *const Frame) -> u32 {\n (*(*(*frame).inner).0).latency_points()\n}\n\n/// Must be called in order to correctly clean up the frame stream.\n#[no_mangle]\npub unsafe extern \"C\" fn frame_stream_drop(stream: FrameStream) {\n if stream.inner != std::ptr::null_mut() {\n Box::from_raw(stream.inner);\n }\n}\n\n/// Must be called in order to correctly clean up the raw stream.\n#[no_mangle]\npub unsafe extern \"C\" fn raw_stream_drop(stream: RawStream) {\n if stream.inner != std::ptr::null_mut() {\n Box::from_raw(stream.inner);\n }\n}\n\n/// Must be called in order to correctly clean up the `DetectDacsAsync` resources.\n#[no_mangle]\npub unsafe extern \"C\" fn detect_dacs_async_drop(detect: DetectDacsAsync) {\n if detect.inner != std::ptr::null_mut() {\n Box::from_raw(detect.inner);\n }\n}\n\n/// Must be called in order to correctly clean up the API resources.\n#[no_mangle]\npub unsafe extern \"C\" fn api_drop(api: Api) {\n if api.inner != std::ptr::null_mut() {\n Box::from_raw(api.inner);\n }\n}\n\n/// Used for retrieving the last error that occurred from the API.\n#[no_mangle]\npub unsafe extern \"C\" fn api_last_error(api: *const Api) -> *const raw::c_char {\n let api: &ApiInner = &(*(*api).inner);\n match api.last_error {\n None => std::ptr::null(),\n Some(ref cstring) => cstring.as_ptr(),\n }\n}\n\n/// Used for retrieving the last error that occurred from the API.\n#[no_mangle]\npub unsafe extern \"C\" fn detect_dacs_async_last_error(\n detect: *const DetectDacsAsync,\n) -> *const raw::c_char {\n let detect_dacs_async: &DetectDacsAsyncInner = &(*(*detect).inner);\n let mut s = std::ptr::null();\n if let Ok(last_error) = detect_dacs_async.last_error.lock() {\n if let Some(ref cstring) = *last_error {\n s = cstring.as_ptr();\n }\n }\n s\n}\n\n/// Begin asynchronous DAC detection.\n///\n/// The given timeout corresponds to the duration of time since the last DAC broadcast was received\n/// before a DAC will be considered to be unavailable again.\nfn detect_dacs_async_inner(\n api: &crate::Api,\n dac_timeout: Option,\n) -> io::Result {\n let dacs = Arc::new(Mutex::new(HashMap::new()));\n let last_error = Arc::new(Mutex::new(None));\n let dacs2 = dacs.clone();\n let last_error2 = last_error.clone();\n let _inner = api.detect_dacs_async(\n dac_timeout,\n move |res: io::Result| match res {\n Ok(dac) => {\n let now = Instant::now();\n let mut dacs = dacs2.lock().unwrap();\n dacs.insert(dac.id(), (now, dac));\n if let Some(timeout) = dac_timeout {\n dacs.retain(|_, (ref last_bc, _)| now.duration_since(*last_bc) < timeout);\n }\n }\n Err(err) => match err.kind() {\n io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut => {\n dacs2.lock().unwrap().clear();\n }\n _ => {\n *last_error2.lock().unwrap() = Some(err_to_cstring(&err));\n }\n },\n },\n )?;\n Ok(DetectDacsAsyncInner {\n _inner,\n dacs,\n last_error,\n })\n}\n\nfn err_to_cstring(err: &dyn fmt::Display) -> CString {\n string_to_cstring(format!(\"{}\", err))\n}\n\nfn string_to_cstring(string: String) -> CString {\n CString::new(string.into_bytes()).expect(\"`string` contained null bytes\")\n}\n\nfn default_stream_config() -> StreamConfig {\n let detected_dac = std::ptr::null();\n let point_hz = crate::stream::DEFAULT_POINT_HZ;\n let latency_points = crate::stream::raw::default_latency_points(point_hz);\n StreamConfig {\n detected_dac,\n point_hz,\n latency_points,\n }\n}\n\nfn socket_addr_to_ffi(addr: std::net::SocketAddr) -> SocketAddr {\n let port = addr.port();\n let mut bytes = [0u8; 16];\n let ip = match addr.ip() {\n std::net::IpAddr::V4(ref ip) => {\n for (byte, octet) in bytes.iter_mut().zip(&ip.octets()) {\n *byte = *octet;\n }\n let version = IpAddrVersion::V4;\n IpAddr { version, bytes }\n }\n std::net::IpAddr::V6(ref ip) => {\n for (byte, octet) in bytes.iter_mut().zip(&ip.octets()) {\n *byte = *octet;\n }\n let version = IpAddrVersion::V6;\n IpAddr { version, bytes }\n }\n };\n SocketAddr { ip, port }\n}\n\nfn socket_addr_from_ffi(addr: SocketAddr) -> std::net::SocketAddr {\n let ip = match addr.ip.version {\n IpAddrVersion::V4 => {\n let b = &addr.ip.bytes;\n std::net::IpAddr::from([b[0], b[1], b[2], b[3]])\n }\n IpAddrVersion::V6 => std::net::IpAddr::from(addr.ip.bytes),\n };\n std::net::SocketAddr::new(ip, addr.port)\n}\n\nfn detected_dac_to_ffi(dac: crate::DetectedDac) -> DetectedDac {\n match dac {\n crate::DetectedDac::EtherDream {\n broadcast,\n source_addr,\n } => {\n let source_addr = socket_addr_to_ffi(source_addr);\n let ether_dream = DacEtherDream {\n broadcast,\n source_addr,\n };\n let kind = DetectedDacKind { ether_dream };\n DetectedDac { kind }\n }\n }\n}\n\nfn detected_dac_from_ffi(ffi_dac: DetectedDac) -> crate::DetectedDac {\n unsafe {\n let broadcast = ffi_dac.kind.ether_dream.broadcast.clone();\n let source_addr = socket_addr_from_ffi(ffi_dac.kind.ether_dream.source_addr);\n crate::DetectedDac::EtherDream {\n broadcast,\n source_addr,\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":156,"cells":{"blob_id":{"kind":"string","value":"38620374925e4827eca77667c9eb13b68879f167"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"colingluwa/Creditcoin-Consensus-Rust"},"path":{"kind":"string","value":"/src/primitives/hash.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2508,"string":"2,508"},"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":"macro_rules! impl_hash {\n ($name:ident, $size:expr) => {\n #[derive(Clone, Copy)]\n #[repr(transparent)]\n pub struct $name {\n inner: [u8; $size],\n }\n\n impl $name {\n pub const SIZE: usize = $size;\n\n pub const MIN: Self = Self {\n inner: [u8::min_value(); $size],\n };\n\n pub const MAX: Self = Self {\n inner: [u8::max_value(); $size],\n };\n\n pub const fn new() -> Self {\n Self { inner: [0; $size] }\n }\n\n pub fn random() -> Self {\n let mut this: Self = Self::new();\n ::rand::Rng::fill(&mut ::rand::thread_rng(), &mut this[..]);\n this\n }\n\n pub fn reversed(&self) -> Self {\n let mut this: Self = *self;\n this.reverse();\n this\n }\n\n pub fn to_hex(&self) -> String {\n $crate::utils::to_hex(self)\n }\n }\n\n impl ::std::ops::Deref for $name {\n type Target = [u8];\n\n fn deref(&self) -> &Self::Target {\n &self.inner\n }\n }\n\n impl ::std::ops::DerefMut for $name {\n fn deref_mut(&mut self) -> &mut Self::Target {\n &mut self.inner\n }\n }\n\n impl AsRef<[u8]> for $name {\n fn as_ref(&self) -> &[u8] {\n &self.inner\n }\n }\n\n impl From<[u8; $size]> for $name {\n fn from(inner: [u8; $size]) -> Self {\n $name { inner }\n }\n }\n\n impl From<$name> for [u8; $size] {\n fn from(this: $name) -> Self {\n this.inner\n }\n }\n\n impl ::std::fmt::Debug for $name {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n write!(f, \"{}\", self.to_hex())\n }\n }\n\n impl ::std::fmt::Display for $name {\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n write!(f, \"{}\", self.to_hex())\n }\n }\n\n impl Default for $name {\n fn default() -> Self {\n Self::new()\n }\n }\n\n impl PartialEq for $name {\n fn eq(&self, other: &Self) -> bool {\n (&**self).eq(&**other)\n }\n }\n\n impl Eq for $name {}\n\n impl PartialOrd for $name {\n fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> {\n (&**self).partial_cmp(&**other)\n }\n }\n\n impl Ord for $name {\n fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {\n (&**self).cmp(&**other)\n }\n }\n\n impl ::std::hash::Hash for $name {\n fn hash(&self, hasher: &mut H) {\n self.inner.hash(hasher)\n }\n }\n };\n}\n\nimpl_hash!(H256, 32);\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":157,"cells":{"blob_id":{"kind":"string","value":"1964af6946fc28cd363b40613e9e817d4617e63e"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"astral-sh/ruff"},"path":{"kind":"string","value":"/crates/ruff_diagnostics/src/fix.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6179,"string":"6,179"},"score":{"kind":"number","value":3.0625,"string":"3.0625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["BSD-3-Clause","0BSD","LicenseRef-scancode-free-unknown","GPL-1.0-or-later","MIT","Apache-2.0"],"string":"[\n \"BSD-3-Clause\",\n \"0BSD\",\n \"LicenseRef-scancode-free-unknown\",\n \"GPL-1.0-or-later\",\n \"MIT\",\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"#[cfg(feature = \"serde\")]\nuse serde::{Deserialize, Serialize};\n\nuse ruff_text_size::TextSize;\n\nuse crate::edit::Edit;\n\n/// Indicates confidence in the correctness of a suggested fix.\n#[derive(Default, Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(feature = \"serde\", derive(Serialize, Deserialize))]\npub enum Applicability {\n /// The fix is definitely what the user intended, or maintains the exact meaning of the code.\n /// This fix should be automatically applied.\n Automatic,\n\n /// The fix may be what the user intended, but it is uncertain.\n /// The fix should result in valid code if it is applied.\n /// The fix can be applied with user opt-in.\n Suggested,\n\n /// The fix has a good chance of being incorrect or the code be incomplete.\n /// The fix may result in invalid code if it is applied.\n /// The fix should only be manually applied by the user.\n Manual,\n\n /// The applicability of the fix is unknown.\n #[default]\n Unspecified,\n}\n\n/// Indicates the level of isolation required to apply a fix.\n#[derive(Default, Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]\n#[cfg_attr(feature = \"serde\", derive(Serialize, Deserialize))]\npub enum IsolationLevel {\n /// The fix should be applied as long as no other fixes in the same group have been applied.\n Group(u32),\n /// The fix should be applied as long as it does not overlap with any other fixes.\n #[default]\n NonOverlapping,\n}\n\n/// A collection of [`Edit`] elements to be applied to a source file.\n#[derive(Debug, PartialEq, Eq, Clone)]\n#[cfg_attr(feature = \"serde\", derive(Serialize, Deserialize))]\npub struct Fix {\n /// The [`Edit`] elements to be applied, sorted by [`Edit::start`] in ascending order.\n edits: Vec,\n /// The [`Applicability`] of the fix.\n applicability: Applicability,\n /// The [`IsolationLevel`] of the fix.\n isolation_level: IsolationLevel,\n}\n\nimpl Fix {\n /// Create a new [`Fix`] with an unspecified applicability from an [`Edit`] element.\n #[deprecated(\n note = \"Use `Fix::automatic`, `Fix::suggested`, or `Fix::manual` instead to specify an applicability.\"\n )]\n pub fn unspecified(edit: Edit) -> Self {\n Self {\n edits: vec![edit],\n applicability: Applicability::Unspecified,\n isolation_level: IsolationLevel::default(),\n }\n }\n\n /// Create a new [`Fix`] with an unspecified applicability from multiple [`Edit`] elements.\n #[deprecated(\n note = \"Use `Fix::automatic_edits`, `Fix::suggested_edits`, or `Fix::manual_edits` instead to specify an applicability.\"\n )]\n pub fn unspecified_edits(edit: Edit, rest: impl IntoIterator) -> Self {\n Self {\n edits: std::iter::once(edit).chain(rest).collect(),\n applicability: Applicability::Unspecified,\n isolation_level: IsolationLevel::default(),\n }\n }\n\n /// Create a new [`Fix`] with [automatic applicability](Applicability::Automatic) from an [`Edit`] element.\n pub fn automatic(edit: Edit) -> Self {\n Self {\n edits: vec![edit],\n applicability: Applicability::Automatic,\n isolation_level: IsolationLevel::default(),\n }\n }\n\n /// Create a new [`Fix`] with [automatic applicability](Applicability::Automatic) from multiple [`Edit`] elements.\n pub fn automatic_edits(edit: Edit, rest: impl IntoIterator) -> Self {\n let mut edits: Vec = std::iter::once(edit).chain(rest).collect();\n edits.sort_by_key(Edit::start);\n Self {\n edits,\n applicability: Applicability::Automatic,\n isolation_level: IsolationLevel::default(),\n }\n }\n\n /// Create a new [`Fix`] with [suggested applicability](Applicability::Suggested) from an [`Edit`] element.\n pub fn suggested(edit: Edit) -> Self {\n Self {\n edits: vec![edit],\n applicability: Applicability::Suggested,\n isolation_level: IsolationLevel::default(),\n }\n }\n\n /// Create a new [`Fix`] with [suggested applicability](Applicability::Suggested) from multiple [`Edit`] elements.\n pub fn suggested_edits(edit: Edit, rest: impl IntoIterator) -> Self {\n let mut edits: Vec = std::iter::once(edit).chain(rest).collect();\n edits.sort_by_key(Edit::start);\n Self {\n edits,\n applicability: Applicability::Suggested,\n isolation_level: IsolationLevel::default(),\n }\n }\n\n /// Create a new [`Fix`] with [manual applicability](Applicability::Manual) from an [`Edit`] element.\n pub fn manual(edit: Edit) -> Self {\n Self {\n edits: vec![edit],\n applicability: Applicability::Manual,\n isolation_level: IsolationLevel::default(),\n }\n }\n\n /// Create a new [`Fix`] with [manual applicability](Applicability::Manual) from multiple [`Edit`] elements.\n pub fn manual_edits(edit: Edit, rest: impl IntoIterator) -> Self {\n let mut edits: Vec = std::iter::once(edit).chain(rest).collect();\n edits.sort_by_key(Edit::start);\n Self {\n edits,\n applicability: Applicability::Manual,\n isolation_level: IsolationLevel::default(),\n }\n }\n\n /// Return the [`TextSize`] of the first [`Edit`] in the [`Fix`].\n pub fn min_start(&self) -> Option {\n self.edits.first().map(Edit::start)\n }\n\n /// Return a slice of the [`Edit`] elements in the [`Fix`], sorted by [`Edit::start`] in ascending order.\n pub fn edits(&self) -> &[Edit] {\n &self.edits\n }\n\n /// Return the [`Applicability`] of the [`Fix`].\n pub fn applicability(&self) -> Applicability {\n self.applicability\n }\n\n /// Return the [`IsolationLevel`] of the [`Fix`].\n pub fn isolation(&self) -> IsolationLevel {\n self.isolation_level\n }\n\n /// Create a new [`Fix`] with the given [`IsolationLevel`].\n #[must_use]\n pub fn isolate(mut self, isolation: IsolationLevel) -> Self {\n self.isolation_level = isolation;\n self\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":158,"cells":{"blob_id":{"kind":"string","value":"a1c5348ad2f062b5ba5bb6eace6e6851eaaa20eb"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"nbigaouette/advent_of_code_2018"},"path":{"kind":"string","value":"/day03/src/preparsed_ndarray.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4454,"string":"4,454"},"score":{"kind":"number","value":2.9375,"string":"2.9375"},"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 std::cmp;\nuse std::collections::HashSet;\n\nuse crate::{parse_input, AoC, Day03SolutionPart1, Day03SolutionPart2, Input};\n\nuse ndarray::Array2;\n\ntype Grid = Array2>;\n\n#[derive(Debug)]\npub struct Day03PreparsedNdarray {\n input: Vec,\n grid_size_width: usize,\n grid_size_height: usize,\n}\n\nfn build_grid(input: &[Input], grid_size_width: usize, grid_size_height: usize) -> Grid {\n let mut grid = Array2::>::from_elem((grid_size_width, grid_size_height), Vec::new());\n\n for claim in input {\n for i in claim.left..(claim.left + claim.wide) {\n for j in claim.top..(claim.top + claim.tall) {\n grid[[i, j]].push(claim.id);\n }\n }\n }\n\n grid\n}\n\nimpl<'a> AoC<'a> for Day03PreparsedNdarray {\n type SolutionPart1 = Day03SolutionPart1;\n type SolutionPart2 = Day03SolutionPart2;\n\n fn description(&self) -> &'static str {\n \"Pre-parsed string and ndarray\"\n }\n\n fn new(input: &'a str) -> Day03PreparsedNdarray {\n let input: Vec<_> = parse_input(input).collect();\n let grid_size_width = input.iter().fold(0, |acc, claim| {\n let width = claim.left + claim.wide;\n cmp::max(width, acc)\n });\n let grid_size_height = input.iter().fold(0, |acc, claim| {\n let height = claim.top + claim.tall;\n cmp::max(height, acc)\n });\n Day03PreparsedNdarray {\n input,\n grid_size_width,\n grid_size_height,\n }\n }\n\n fn solution_part1(&self) -> Self::SolutionPart1 {\n let grid = build_grid(&self.input, self.grid_size_width, self.grid_size_height);\n\n grid.iter()\n .filter_map(|p| if p.len() >= 2 { Some(1) } else { None })\n .count()\n }\n\n fn solution_part2(&self) -> Self::SolutionPart2 {\n let grid = build_grid(&self.input, self.grid_size_width, self.grid_size_height);\n\n let mut claims: HashSet = self.input.iter().map(|claim| claim.id).collect();\n\n for claim_ids in grid.iter() {\n if claim_ids.len() >= 2 {\n for claim_id in claim_ids {\n claims.remove(claim_id);\n }\n }\n }\n\n assert_eq!(claims.len(), 1);\n\n *claims.iter().next().unwrap()\n }\n}\n\n#[cfg(test)]\nmod tests {\n mod part1 {\n mod solution {\n use super::super::super::Day03PreparsedNdarray;\n use crate::{tests::init_logger, AoC, PUZZLE_INPUT};\n\n #[test]\n fn solution() {\n init_logger();\n\n let expected = 100595;\n let to_check = Day03PreparsedNdarray::new(PUZZLE_INPUT).solution_part1();\n\n assert_eq!(expected, to_check);\n }\n }\n\n mod given {\n use super::super::super::Day03PreparsedNdarray;\n use crate::{tests::init_logger, AoC};\n\n #[test]\n fn ex01() {\n init_logger();\n\n let expected = 4;\n let input = \"#1 @ 1,3: 4x4\n #2 @ 3,1: 4x4\n #3 @ 5,5: 2x2\";\n let to_check = Day03PreparsedNdarray::new(input).solution_part1();\n\n assert_eq!(expected, to_check);\n }\n }\n\n /*\n mod extra {\n use ::*;\n }\n */\n }\n\n mod part2 {\n mod solution {\n use super::super::super::Day03PreparsedNdarray;\n use crate::{tests::init_logger, AoC, PUZZLE_INPUT};\n\n #[test]\n fn solution() {\n init_logger();\n\n let expected = 415;\n let to_check = Day03PreparsedNdarray::new(PUZZLE_INPUT).solution_part2();\n\n assert_eq!(expected, to_check);\n }\n }\n\n mod given {\n use super::super::super::Day03PreparsedNdarray;\n use crate::{tests::init_logger, AoC};\n\n #[test]\n fn ex01() {\n init_logger();\n\n let expected = 3;\n let input = \"#1 @ 1,3: 4x4\n #2 @ 3,1: 4x4\n #3 @ 5,5: 2x2\";\n let to_check = Day03PreparsedNdarray::new(input).solution_part2();\n\n assert_eq!(expected, to_check);\n }\n }\n\n /*\n mod extra {\n use ::*;\n }\n */\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":159,"cells":{"blob_id":{"kind":"string","value":"2c09696fe56066e2f1721746d430a8ba43689692"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"kinseywk/dicey"},"path":{"kind":"string","value":"/src/lib.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3685,"string":"3,685"},"score":{"kind":"number","value":3.6875,"string":"3.6875"},"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":"#![allow(non_snake_case, non_upper_case_globals)]\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub struct DieRoll {\n\t//Number of dice in the roll\n\tpub quantity: usize,\n\t//Number of die faces (6 = standard cubic die)\n\tpub faces: usize,\n\t//Net bonus and malus applied to the roll (e.g., 1d4+1 adds 1 to each roll)\n\tpub adjustment: isize,\n}\n\npub fn parse(diceRoll: &str) -> Option> {\n\tlet mut result: Vec = Vec::new();\n\n\t//1.) Split input string on each ','\n\tlet diceRoll: Vec<&str> = diceRoll.split(',').collect();\n\n\tfor dieRoll in diceRoll {\n\t\tlet mut adjustmentChar: Option = None;\n\t\tlet mut adjustment: isize = 0;\n\t\tlet mut dieString: &str = dieRoll;\n\n\t\t//2.) Split-off the '+' or '-' clause, if one exists\n\t\t//2a.) Test if '+' and '-' are in the string\n\t\tif let Some(_) = dieRoll.find('+') {\n\t\t\tadjustmentChar = Some('+');\n\t\t} else if let Some(_) = dieRoll.find('-') {\n\t\t\tadjustmentChar = Some('-');\n\t\t}\n\n\t\t//2b.) If either exists, break-off the front part and parse the latter part as an integer\n\t\tif let None = adjustmentChar {\n\t\t} else {\n\t\t\tif let Some((diePart, adjustmentPart)) = dieString.split_once(adjustmentChar.unwrap()) {\n\t\t\t\tdieString = diePart;\n\n\t\t\t\tif let Ok(adjustmentParsed) = adjustmentPart.parse::() {\n\t\t\t\t\tadjustment = adjustmentParsed;\n\n\t\t\t\t\t//2c.) Finally, if the prior test matched a '-', make the parsed number negative\n\t\t\t\t\tif adjustmentChar.unwrap() == '-' {\n\t\t\t\t\t\tadjustment = -adjustment;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn None;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//3.) Split each dice string on 'd'\n\t\tif let Some((quantityPart, facesPart)) = dieString.split_once('d') {\n\t\t\t//4.) Parse each of _those_ strings as positive integers and create a DieRoll from each pair\n\t\t\tif let (Ok(quantity), Ok(faces)) = (quantityPart.parse::(), facesPart.parse::()) {\n\t\t\t\tif quantity == 0 || faces == 0 {\n\t\t\t\t\treturn None;\n\t\t\t\t} else {\n\t\t\t\t\tresult.push(DieRoll{quantity, faces, adjustment});\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn None;\n\t\t\t}\n\t\t} else {\n\t\t\treturn None;\n\t\t}\n\t}\n\n\tSome(result)\n}\n\n#[cfg(test)]\nmod tests {\n\tuse super::*;\n\n\t#[test]\n\tfn parse_single() {\n\t\t{\n\t\t\tconst test: &str = \"5d6\";\n\n\t\t\tif let Some(result) = parse(test) {\n\t\t\t\tassert_eq!(result[0], DieRoll{quantity: 5, faces: 6, adjustment: 0});\n\t\t\t} else {\n\t\t\t\tpanic!(\"Failed to parse string \\\"{}\\\"\", test);\n\t\t\t}\n\t\t}\n\n\t\t{\n\t\t\tconst test: &str = \"3d4+1\";\n\n\t\t\tif let Some(result) = parse(test) {\n\t\t\t\tassert_eq!(result[0], DieRoll{quantity: 3, faces: 4, adjustment: 1});\n\t\t\t} else {\n\t\t\t\tpanic!(\"Failed to parse string \\\"{}\\\"\", test);\n\t\t\t}\n\t\t}\n\n\t\t{\n\t\t\tconst test: &str = \"1d2-1\";\n\t\n\t\t\tif let Some(result) = parse(test) {\n\t\t\t\tassert_eq!(result[0], DieRoll{quantity: 1, faces: 2, adjustment: -1});\n\t\t\t} else {\n\t\t\t\tpanic!(\"Failed to parse string \\\"{}\\\"\", test);\n\t\t\t}\n\t\t}\n\t}\n\n\t#[test]\n\tfn parse_list() {\n\t\tconst test: &str = \"1d1,100d100,1000000d1000000,1d100+100,100d1-1\";\n\n\t\tif let Some(result) = parse(test) {\n\t\t\tassert_eq!(result.len(), 5, \"Failed to parse all list entries\");\n\t\t\tassert_eq!(result[0], DieRoll{quantity: 1, faces: 1, adjustment: 0});\n\t\t\tassert_eq!(result[1], DieRoll{quantity: 100, faces: 100, adjustment: 0});\n\t\t\tassert_eq!(result[2], DieRoll{quantity: 1000000, faces: 1000000, adjustment: 0});\n\t\t\tassert_eq!(result[3], DieRoll{quantity: 1, faces: 100, adjustment: 100});\n\t\t\tassert_eq!(result[4], DieRoll{quantity: 100, faces: 1, adjustment: -1});\n\t\t} else {\n\t\t\tpanic!(\"Failed to parse string \\\"{}\\\"\", test);\n\t\t}\n\t}\n\n\t#[test]\n\tfn parse_fail() {\n\t\tconst tests: &'static [&'static str] = &[\"r2d2\", \"-3d3\", \"3d-3\", \"3d0\", \"0d3\", \"3d\", \"d3\", \"3d3,\", \",\", \"\"];\n\n\t\tfor test in tests {\n\t\t\tassert_eq!(parse(test), None, \"Incorrectly parsed invalid string \\\"{}\\\"\", test);\n\t\t}\n\t}\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":160,"cells":{"blob_id":{"kind":"string","value":"1cb91910631be47d9fbc78821be91beeb4cc5743"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Concordium/wasm-tools"},"path":{"kind":"string","value":"/crates/wasm-encoder/src/code.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":26694,"string":"26,694"},"score":{"kind":"number","value":3.375,"string":"3.375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["LLVM-exception","Apache-2.0","LicenseRef-scancode-unknown-license-reference"],"string":"[\n \"LLVM-exception\",\n \"Apache-2.0\",\n \"LicenseRef-scancode-unknown-license-reference\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use super::*;\n\n/// An encoder for the code section.\n///\n/// # Example\n///\n/// ```\n/// use wasm_encoder::{\n/// CodeSection, Function, FunctionSection, Instruction, Module,\n/// TypeSection, ValType\n/// };\n///\n/// let mut types = TypeSection::new();\n/// types.function(vec![], vec![ValType::I32]);\n///\n/// let mut functions = FunctionSection::new();\n/// let type_index = 0;\n/// functions.function(type_index);\n///\n/// let locals = vec![];\n/// let mut func = Function::new(locals);\n/// func.instruction(Instruction::I32Const(42));\n/// let mut code = CodeSection::new();\n/// code.function(&func);\n///\n/// let mut module = Module::new();\n/// module\n/// .section(&types)\n/// .section(&functions)\n/// .section(&code);\n///\n/// let wasm_bytes = module.finish();\n/// ```\npub struct CodeSection {\n bytes: Vec,\n num_added: u32,\n}\n\nimpl CodeSection {\n /// Create a new code section encoder.\n pub fn new() -> CodeSection {\n CodeSection {\n bytes: vec![],\n num_added: 0,\n }\n }\n\n /// Write a function body into this code section.\n pub fn function(&mut self, func: &Function) -> &mut Self {\n func.encode(&mut self.bytes);\n self.num_added += 1;\n self\n }\n}\n\nimpl Section for CodeSection {\n fn id(&self) -> u8 {\n SectionId::Code.into()\n }\n\n fn encode(&self, sink: &mut S)\n where\n S: Extend,\n {\n let num_added = encoders::u32(self.num_added);\n let n = num_added.len();\n sink.extend(\n encoders::u32(u32::try_from(n + self.bytes.len()).unwrap())\n .chain(num_added)\n .chain(self.bytes.iter().copied()),\n );\n }\n}\n\n/// An encoder for a function body within the code section.\n///\n/// # Example\n///\n/// ```\n/// use wasm_encoder::{CodeSection, Function, Instruction};\n///\n/// // Define the function body for:\n/// //\n/// // (func (param i32 i32) (result i32)\n/// // local.get 0\n/// // local.get 1\n/// // i32.add)\n/// let locals = vec![];\n/// let mut func = Function::new(locals);\n/// func.instruction(Instruction::LocalGet(0));\n/// func.instruction(Instruction::LocalGet(1));\n/// func.instruction(Instruction::I32Add);\n///\n/// // Add our function to the code section.\n/// let mut code = CodeSection::new();\n/// code.function(&func);\n/// ```\npub struct Function {\n bytes: Vec,\n}\n\nimpl Function {\n /// Create a new function body with the given locals.\n pub fn new(locals: L) -> Self\n where\n L: IntoIterator,\n L::IntoIter: ExactSizeIterator,\n {\n let locals = locals.into_iter();\n let mut bytes = vec![];\n bytes.extend(encoders::u32(u32::try_from(locals.len()).unwrap()));\n for (count, ty) in locals {\n bytes.extend(encoders::u32(count));\n bytes.push(ty.into());\n }\n Function { bytes }\n }\n\n /// Write an instruction into this function body.\n pub fn instruction(&mut self, instruction: Instruction) -> &mut Self {\n instruction.encode(&mut self.bytes);\n self\n }\n\n /// Add raw bytes to this function's body.\n pub fn raw(&mut self, bytes: B) -> &mut Self\n where\n B: IntoIterator,\n {\n self.bytes.extend(bytes);\n self\n }\n\n fn encode(&self, bytes: &mut Vec) {\n bytes.extend(\n encoders::u32(u32::try_from(self.bytes.len()).unwrap())\n .chain(self.bytes.iter().copied()),\n );\n }\n}\n\n/// The immediate for a memory instruction.\n#[derive(Clone, Copy, Debug)]\npub struct MemArg {\n /// A static offset to add to the instruction's dynamic address operand.\n pub offset: u32,\n /// The expected alignment of the instruction's dynamic address operand\n /// (expressed the exponent of a power of two).\n pub align: u32,\n /// The index of the memory this instruction is operating upon.\n pub memory_index: u32,\n}\n\nimpl MemArg {\n fn encode(&self, bytes: &mut Vec) {\n if self.memory_index == 0 {\n bytes.extend(encoders::u32(self.align));\n bytes.extend(encoders::u32(self.offset));\n } else {\n bytes.extend(encoders::u32(self.align | (1 << 6)));\n bytes.extend(encoders::u32(self.offset));\n bytes.extend(encoders::u32(self.memory_index));\n }\n }\n}\n\n/// The type for a `block`/`if`/`loop`.\n#[derive(Clone, Copy, Debug)]\npub enum BlockType {\n /// `[] -> []`\n Empty,\n /// `[] -> [t]`\n Result(ValType),\n /// The `n`th function type.\n FunctionType(u32),\n}\n\nimpl BlockType {\n fn encode(&self, bytes: &mut Vec) {\n match *self {\n BlockType::Empty => bytes.push(0x40),\n BlockType::Result(ty) => bytes.push(ty.into()),\n BlockType::FunctionType(f) => bytes.extend(encoders::s33(f.into())),\n }\n }\n}\n\n/// WebAssembly instructions.\n#[derive(Clone, Debug)]\n#[non_exhaustive]\n#[allow(missing_docs, non_camel_case_types)]\npub enum Instruction<'a> {\n // Control instructions.\n Unreachable,\n Nop,\n Block(BlockType),\n Loop(BlockType),\n If(BlockType),\n Else,\n End,\n Br(u32),\n BrIf(u32),\n BrTable(&'a [u32], u32),\n Return,\n Call(u32),\n CallIndirect { ty: u32, table: u32 },\n\n // Parametric instructions.\n Drop,\n Select,\n\n // Variable instructions.\n LocalGet(u32),\n LocalSet(u32),\n LocalTee(u32),\n GlobalGet(u32),\n GlobalSet(u32),\n\n // Memory instructions.\n I32Load(MemArg),\n I64Load(MemArg),\n F32Load(MemArg),\n F64Load(MemArg),\n I32Load8_S(MemArg),\n I32Load8_U(MemArg),\n I32Load16_S(MemArg),\n I32Load16_U(MemArg),\n I64Load8_S(MemArg),\n I64Load8_U(MemArg),\n I64Load16_S(MemArg),\n I64Load16_U(MemArg),\n I64Load32_S(MemArg),\n I64Load32_U(MemArg),\n I32Store(MemArg),\n I64Store(MemArg),\n F32Store(MemArg),\n F64Store(MemArg),\n I32Store8(MemArg),\n I32Store16(MemArg),\n I64Store8(MemArg),\n I64Store16(MemArg),\n I64Store32(MemArg),\n MemorySize(u32),\n MemoryGrow(u32),\n MemoryInit { mem: u32, data: u32 },\n DataDrop(u32),\n MemoryCopy { src: u32, dst: u32 },\n MemoryFill(u32),\n\n // Numeric instructions.\n I32Const(i32),\n I64Const(i64),\n F32Const(f32),\n F64Const(f64),\n I32Eqz,\n I32Eq,\n I32Neq,\n I32LtS,\n I32LtU,\n I32GtS,\n I32GtU,\n I32LeS,\n I32LeU,\n I32GeS,\n I32GeU,\n I64Eqz,\n I64Eq,\n I64Neq,\n I64LtS,\n I64LtU,\n I64GtS,\n I64GtU,\n I64LeS,\n I64LeU,\n I64GeS,\n I64GeU,\n F32Eq,\n F32Neq,\n F32Lt,\n F32Gt,\n F32Le,\n F32Ge,\n F64Eq,\n F64Neq,\n F64Lt,\n F64Gt,\n F64Le,\n F64Ge,\n I32Clz,\n I32Ctz,\n I32Popcnt,\n I32Add,\n I32Sub,\n I32Mul,\n I32DivS,\n I32DivU,\n I32RemS,\n I32RemU,\n I32And,\n I32Or,\n I32Xor,\n I32Shl,\n I32ShrS,\n I32ShrU,\n I32Rotl,\n I32Rotr,\n I64Clz,\n I64Ctz,\n I64Popcnt,\n I64Add,\n I64Sub,\n I64Mul,\n I64DivS,\n I64DivU,\n I64RemS,\n I64RemU,\n I64And,\n I64Or,\n I64Xor,\n I64Shl,\n I64ShrS,\n I64ShrU,\n I64Rotl,\n I64Rotr,\n F32Abs,\n F32Neg,\n F32Ceil,\n F32Floor,\n F32Trunc,\n F32Nearest,\n F32Sqrt,\n F32Add,\n F32Sub,\n F32Mul,\n F32Div,\n F32Min,\n F32Max,\n F32Copysign,\n F64Abs,\n F64Neg,\n F64Ceil,\n F64Floor,\n F64Trunc,\n F64Nearest,\n F64Sqrt,\n F64Add,\n F64Sub,\n F64Mul,\n F64Div,\n F64Min,\n F64Max,\n F64Copysign,\n I32WrapI64,\n I32TruncF32S,\n I32TruncF32U,\n I32TruncF64S,\n I32TruncF64U,\n I64ExtendI32S,\n I64ExtendI32U,\n I64TruncF32S,\n I64TruncF32U,\n I64TruncF64S,\n I64TruncF64U,\n F32ConvertI32S,\n F32ConvertI32U,\n F32ConvertI64S,\n F32ConvertI64U,\n F32DemoteF64,\n F64ConvertI32S,\n F64ConvertI32U,\n F64ConvertI64S,\n F64ConvertI64U,\n F64PromoteF32,\n I32ReinterpretF32,\n I64ReinterpretF64,\n F32ReinterpretI32,\n F64ReinterpretI64,\n I32Extend8S,\n I32Extend16S,\n I64Extend8S,\n I64Extend16S,\n I64Extend32S,\n I32TruncSatF32S,\n I32TruncSatF32U,\n I32TruncSatF64S,\n I32TruncSatF64U,\n I64TruncSatF32S,\n I64TruncSatF32U,\n I64TruncSatF64S,\n I64TruncSatF64U,\n\n // SIMD instructions.\n V128Const(i128),\n\n // Reference types instructions.\n TypedSelect(ValType),\n RefNull(ValType),\n RefIsNull,\n RefFunc(u32),\n\n // Bulk memory instructions.\n TableInit { segment: u32, table: u32 },\n ElemDrop { segment: u32 },\n TableFill { table: u32 },\n TableSet { table: u32 },\n TableGet { table: u32 },\n TableGrow { table: u32 },\n TableSize { table: u32 },\n TableCopy { src: u32, dst: u32 },\n}\n\nimpl Instruction<'_> {\n pub(crate) fn encode(&self, bytes: &mut Vec) {\n match *self {\n // Control instructions.\n Instruction::Unreachable => bytes.push(0x00),\n Instruction::Nop => bytes.push(0x01),\n Instruction::Block(bt) => {\n bytes.push(0x02);\n bt.encode(bytes);\n }\n Instruction::Loop(bt) => {\n bytes.push(0x03);\n bt.encode(bytes);\n }\n Instruction::If(bt) => {\n bytes.push(0x04);\n bt.encode(bytes);\n }\n Instruction::Else => bytes.push(0x05),\n Instruction::End => bytes.push(0x0B),\n Instruction::Br(l) => {\n bytes.push(0x0C);\n bytes.extend(encoders::u32(l));\n }\n Instruction::BrIf(l) => {\n bytes.push(0x0D);\n bytes.extend(encoders::u32(l));\n }\n Instruction::BrTable(ls, l) => {\n bytes.push(0x0E);\n bytes.extend(encoders::u32(u32::try_from(ls.len()).unwrap()));\n for l in ls {\n bytes.extend(encoders::u32(*l));\n }\n bytes.extend(encoders::u32(l));\n }\n Instruction::Return => bytes.push(0x0F),\n Instruction::Call(f) => {\n bytes.push(0x10);\n bytes.extend(encoders::u32(f));\n }\n Instruction::CallIndirect { ty, table } => {\n bytes.push(0x11);\n bytes.extend(encoders::u32(ty));\n bytes.extend(encoders::u32(table));\n }\n\n // Parametric instructions.\n Instruction::Drop => bytes.push(0x1A),\n Instruction::Select => bytes.push(0x1B),\n Instruction::TypedSelect(ty) => {\n bytes.push(0x1c);\n bytes.extend(encoders::u32(1));\n bytes.push(ty.into());\n }\n\n // Variable instructions.\n Instruction::LocalGet(l) => {\n bytes.push(0x20);\n bytes.extend(encoders::u32(l));\n }\n Instruction::LocalSet(l) => {\n bytes.push(0x21);\n bytes.extend(encoders::u32(l));\n }\n Instruction::LocalTee(l) => {\n bytes.push(0x22);\n bytes.extend(encoders::u32(l));\n }\n Instruction::GlobalGet(g) => {\n bytes.push(0x23);\n bytes.extend(encoders::u32(g));\n }\n Instruction::GlobalSet(g) => {\n bytes.push(0x24);\n bytes.extend(encoders::u32(g));\n }\n Instruction::TableGet { table } => {\n bytes.push(0x25);\n bytes.extend(encoders::u32(table));\n }\n Instruction::TableSet { table } => {\n bytes.push(0x26);\n bytes.extend(encoders::u32(table));\n }\n\n // Memory instructions.\n Instruction::I32Load(m) => {\n bytes.push(0x28);\n m.encode(bytes);\n }\n Instruction::I64Load(m) => {\n bytes.push(0x29);\n m.encode(bytes);\n }\n Instruction::F32Load(m) => {\n bytes.push(0x2A);\n m.encode(bytes);\n }\n Instruction::F64Load(m) => {\n bytes.push(0x2B);\n m.encode(bytes);\n }\n Instruction::I32Load8_S(m) => {\n bytes.push(0x2C);\n m.encode(bytes);\n }\n Instruction::I32Load8_U(m) => {\n bytes.push(0x2D);\n m.encode(bytes);\n }\n Instruction::I32Load16_S(m) => {\n bytes.push(0x2E);\n m.encode(bytes);\n }\n Instruction::I32Load16_U(m) => {\n bytes.push(0x2F);\n m.encode(bytes);\n }\n Instruction::I64Load8_S(m) => {\n bytes.push(0x30);\n m.encode(bytes);\n }\n Instruction::I64Load8_U(m) => {\n bytes.push(0x31);\n m.encode(bytes);\n }\n Instruction::I64Load16_S(m) => {\n bytes.push(0x32);\n m.encode(bytes);\n }\n Instruction::I64Load16_U(m) => {\n bytes.push(0x33);\n m.encode(bytes);\n }\n Instruction::I64Load32_S(m) => {\n bytes.push(0x34);\n m.encode(bytes);\n }\n Instruction::I64Load32_U(m) => {\n bytes.push(0x35);\n m.encode(bytes);\n }\n Instruction::I32Store(m) => {\n bytes.push(0x36);\n m.encode(bytes);\n }\n Instruction::I64Store(m) => {\n bytes.push(0x37);\n m.encode(bytes);\n }\n Instruction::F32Store(m) => {\n bytes.push(0x38);\n m.encode(bytes);\n }\n Instruction::F64Store(m) => {\n bytes.push(0x39);\n m.encode(bytes);\n }\n Instruction::I32Store8(m) => {\n bytes.push(0x3A);\n m.encode(bytes);\n }\n Instruction::I32Store16(m) => {\n bytes.push(0x3B);\n m.encode(bytes);\n }\n Instruction::I64Store8(m) => {\n bytes.push(0x3C);\n m.encode(bytes);\n }\n Instruction::I64Store16(m) => {\n bytes.push(0x3D);\n m.encode(bytes);\n }\n Instruction::I64Store32(m) => {\n bytes.push(0x3E);\n m.encode(bytes);\n }\n Instruction::MemorySize(i) => {\n bytes.push(0x3F);\n bytes.extend(encoders::u32(i));\n }\n Instruction::MemoryGrow(i) => {\n bytes.push(0x40);\n bytes.extend(encoders::u32(i));\n }\n Instruction::MemoryInit { mem, data } => {\n bytes.push(0xfc);\n bytes.extend(encoders::u32(8));\n bytes.extend(encoders::u32(data));\n bytes.extend(encoders::u32(mem));\n }\n Instruction::DataDrop(data) => {\n bytes.push(0xfc);\n bytes.extend(encoders::u32(9));\n bytes.extend(encoders::u32(data));\n }\n Instruction::MemoryCopy { src, dst } => {\n bytes.push(0xfc);\n bytes.extend(encoders::u32(10));\n bytes.extend(encoders::u32(dst));\n bytes.extend(encoders::u32(src));\n }\n Instruction::MemoryFill(mem) => {\n bytes.push(0xfc);\n bytes.extend(encoders::u32(11));\n bytes.extend(encoders::u32(mem));\n }\n\n // Numeric instructions.\n Instruction::I32Const(x) => {\n bytes.push(0x41);\n bytes.extend(encoders::s32(x));\n }\n Instruction::I64Const(x) => {\n bytes.push(0x42);\n bytes.extend(encoders::s64(x));\n }\n Instruction::F32Const(x) => {\n bytes.push(0x43);\n let x = x.to_bits();\n bytes.extend(x.to_le_bytes().iter().copied());\n }\n Instruction::F64Const(x) => {\n bytes.push(0x44);\n let x = x.to_bits();\n bytes.extend(x.to_le_bytes().iter().copied());\n }\n Instruction::I32Eqz => bytes.push(0x45),\n Instruction::I32Eq => bytes.push(0x46),\n Instruction::I32Neq => bytes.push(0x47),\n Instruction::I32LtS => bytes.push(0x48),\n Instruction::I32LtU => bytes.push(0x49),\n Instruction::I32GtS => bytes.push(0x4A),\n Instruction::I32GtU => bytes.push(0x4B),\n Instruction::I32LeS => bytes.push(0x4C),\n Instruction::I32LeU => bytes.push(0x4D),\n Instruction::I32GeS => bytes.push(0x4E),\n Instruction::I32GeU => bytes.push(0x4F),\n Instruction::I64Eqz => bytes.push(0x50),\n Instruction::I64Eq => bytes.push(0x51),\n Instruction::I64Neq => bytes.push(0x52),\n Instruction::I64LtS => bytes.push(0x53),\n Instruction::I64LtU => bytes.push(0x54),\n Instruction::I64GtS => bytes.push(0x55),\n Instruction::I64GtU => bytes.push(0x56),\n Instruction::I64LeS => bytes.push(0x57),\n Instruction::I64LeU => bytes.push(0x58),\n Instruction::I64GeS => bytes.push(0x59),\n Instruction::I64GeU => bytes.push(0x5A),\n Instruction::F32Eq => bytes.push(0x5B),\n Instruction::F32Neq => bytes.push(0x5C),\n Instruction::F32Lt => bytes.push(0x5D),\n Instruction::F32Gt => bytes.push(0x5E),\n Instruction::F32Le => bytes.push(0x5F),\n Instruction::F32Ge => bytes.push(0x60),\n Instruction::F64Eq => bytes.push(0x61),\n Instruction::F64Neq => bytes.push(0x62),\n Instruction::F64Lt => bytes.push(0x63),\n Instruction::F64Gt => bytes.push(0x64),\n Instruction::F64Le => bytes.push(0x65),\n Instruction::F64Ge => bytes.push(0x66),\n Instruction::I32Clz => bytes.push(0x67),\n Instruction::I32Ctz => bytes.push(0x68),\n Instruction::I32Popcnt => bytes.push(0x69),\n Instruction::I32Add => bytes.push(0x6A),\n Instruction::I32Sub => bytes.push(0x6B),\n Instruction::I32Mul => bytes.push(0x6C),\n Instruction::I32DivS => bytes.push(0x6D),\n Instruction::I32DivU => bytes.push(0x6E),\n Instruction::I32RemS => bytes.push(0x6F),\n Instruction::I32RemU => bytes.push(0x70),\n Instruction::I32And => bytes.push(0x71),\n Instruction::I32Or => bytes.push(0x72),\n Instruction::I32Xor => bytes.push(0x73),\n Instruction::I32Shl => bytes.push(0x74),\n Instruction::I32ShrS => bytes.push(0x75),\n Instruction::I32ShrU => bytes.push(0x76),\n Instruction::I32Rotl => bytes.push(0x77),\n Instruction::I32Rotr => bytes.push(0x78),\n Instruction::I64Clz => bytes.push(0x79),\n Instruction::I64Ctz => bytes.push(0x7A),\n Instruction::I64Popcnt => bytes.push(0x7B),\n Instruction::I64Add => bytes.push(0x7C),\n Instruction::I64Sub => bytes.push(0x7D),\n Instruction::I64Mul => bytes.push(0x7E),\n Instruction::I64DivS => bytes.push(0x7F),\n Instruction::I64DivU => bytes.push(0x80),\n Instruction::I64RemS => bytes.push(0x81),\n Instruction::I64RemU => bytes.push(0x82),\n Instruction::I64And => bytes.push(0x83),\n Instruction::I64Or => bytes.push(0x84),\n Instruction::I64Xor => bytes.push(0x85),\n Instruction::I64Shl => bytes.push(0x86),\n Instruction::I64ShrS => bytes.push(0x87),\n Instruction::I64ShrU => bytes.push(0x88),\n Instruction::I64Rotl => bytes.push(0x89),\n Instruction::I64Rotr => bytes.push(0x8A),\n Instruction::F32Abs => bytes.push(0x8B),\n Instruction::F32Neg => bytes.push(0x8C),\n Instruction::F32Ceil => bytes.push(0x8D),\n Instruction::F32Floor => bytes.push(0x8E),\n Instruction::F32Trunc => bytes.push(0x8F),\n Instruction::F32Nearest => bytes.push(0x90),\n Instruction::F32Sqrt => bytes.push(0x91),\n Instruction::F32Add => bytes.push(0x92),\n Instruction::F32Sub => bytes.push(0x93),\n Instruction::F32Mul => bytes.push(0x94),\n Instruction::F32Div => bytes.push(0x95),\n Instruction::F32Min => bytes.push(0x96),\n Instruction::F32Max => bytes.push(0x97),\n Instruction::F32Copysign => bytes.push(0x98),\n Instruction::F64Abs => bytes.push(0x99),\n Instruction::F64Neg => bytes.push(0x9A),\n Instruction::F64Ceil => bytes.push(0x9B),\n Instruction::F64Floor => bytes.push(0x9C),\n Instruction::F64Trunc => bytes.push(0x9D),\n Instruction::F64Nearest => bytes.push(0x9E),\n Instruction::F64Sqrt => bytes.push(0x9F),\n Instruction::F64Add => bytes.push(0xA0),\n Instruction::F64Sub => bytes.push(0xA1),\n Instruction::F64Mul => bytes.push(0xA2),\n Instruction::F64Div => bytes.push(0xA3),\n Instruction::F64Min => bytes.push(0xA4),\n Instruction::F64Max => bytes.push(0xA5),\n Instruction::F64Copysign => bytes.push(0xA6),\n Instruction::I32WrapI64 => bytes.push(0xA7),\n Instruction::I32TruncF32S => bytes.push(0xA8),\n Instruction::I32TruncF32U => bytes.push(0xA9),\n Instruction::I32TruncF64S => bytes.push(0xAA),\n Instruction::I32TruncF64U => bytes.push(0xAB),\n Instruction::I64ExtendI32S => bytes.push(0xAC),\n Instruction::I64ExtendI32U => bytes.push(0xAD),\n Instruction::I64TruncF32S => bytes.push(0xAE),\n Instruction::I64TruncF32U => bytes.push(0xAF),\n Instruction::I64TruncF64S => bytes.push(0xB0),\n Instruction::I64TruncF64U => bytes.push(0xB1),\n Instruction::F32ConvertI32S => bytes.push(0xB2),\n Instruction::F32ConvertI32U => bytes.push(0xB3),\n Instruction::F32ConvertI64S => bytes.push(0xB4),\n Instruction::F32ConvertI64U => bytes.push(0xB5),\n Instruction::F32DemoteF64 => bytes.push(0xB6),\n Instruction::F64ConvertI32S => bytes.push(0xB7),\n Instruction::F64ConvertI32U => bytes.push(0xB8),\n Instruction::F64ConvertI64S => bytes.push(0xB9),\n Instruction::F64ConvertI64U => bytes.push(0xBA),\n Instruction::F64PromoteF32 => bytes.push(0xBB),\n Instruction::I32ReinterpretF32 => bytes.push(0xBC),\n Instruction::I64ReinterpretF64 => bytes.push(0xBD),\n Instruction::F32ReinterpretI32 => bytes.push(0xBE),\n Instruction::F64ReinterpretI64 => bytes.push(0xBF),\n Instruction::I32Extend8S => bytes.push(0xC0),\n Instruction::I32Extend16S => bytes.push(0xC1),\n Instruction::I64Extend8S => bytes.push(0xC2),\n Instruction::I64Extend16S => bytes.push(0xC3),\n Instruction::I64Extend32S => bytes.push(0xC4),\n\n Instruction::I32TruncSatF32S => {\n bytes.push(0xFC);\n bytes.extend(encoders::u32(0));\n }\n Instruction::I32TruncSatF32U => {\n bytes.push(0xFC);\n bytes.extend(encoders::u32(1));\n }\n Instruction::I32TruncSatF64S => {\n bytes.push(0xFC);\n bytes.extend(encoders::u32(2));\n }\n Instruction::I32TruncSatF64U => {\n bytes.push(0xFC);\n bytes.extend(encoders::u32(3));\n }\n Instruction::I64TruncSatF32S => {\n bytes.push(0xFC);\n bytes.extend(encoders::u32(4));\n }\n Instruction::I64TruncSatF32U => {\n bytes.push(0xFC);\n bytes.extend(encoders::u32(5));\n }\n Instruction::I64TruncSatF64S => {\n bytes.push(0xFC);\n bytes.extend(encoders::u32(6));\n }\n Instruction::I64TruncSatF64U => {\n bytes.push(0xFC);\n bytes.extend(encoders::u32(7));\n }\n\n // Reference types instructions.\n Instruction::RefNull(ty) => {\n bytes.push(0xd0);\n bytes.push(ty.into());\n }\n Instruction::RefIsNull => bytes.push(0xd1),\n Instruction::RefFunc(f) => {\n bytes.push(0xd2);\n bytes.extend(encoders::u32(f));\n }\n\n // Bulk memory instructions.\n Instruction::TableInit { segment, table } => {\n bytes.push(0xfc);\n bytes.extend(encoders::u32(0x0c));\n bytes.extend(encoders::u32(segment));\n bytes.extend(encoders::u32(table));\n }\n Instruction::ElemDrop { segment } => {\n bytes.push(0xfc);\n bytes.extend(encoders::u32(0x0d));\n bytes.extend(encoders::u32(segment));\n }\n Instruction::TableCopy { src, dst } => {\n bytes.push(0xfc);\n bytes.extend(encoders::u32(0x0e));\n bytes.extend(encoders::u32(dst));\n bytes.extend(encoders::u32(src));\n }\n Instruction::TableGrow { table } => {\n bytes.push(0xfc);\n bytes.extend(encoders::u32(0x0f));\n bytes.extend(encoders::u32(table));\n }\n Instruction::TableSize { table } => {\n bytes.push(0xfc);\n bytes.extend(encoders::u32(0x10));\n bytes.extend(encoders::u32(table));\n }\n Instruction::TableFill { table } => {\n bytes.push(0xfc);\n bytes.extend(encoders::u32(0x11));\n bytes.extend(encoders::u32(table));\n }\n\n // SIMD instructions.\n Instruction::V128Const(x) => {\n bytes.push(0xFD);\n bytes.extend(encoders::u32(12));\n bytes.extend(x.to_le_bytes().iter().copied());\n }\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":161,"cells":{"blob_id":{"kind":"string","value":"e590f9cc3bc61658b15ea7fcfedc93c7cce091ad"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"StackCrash/kryptos"},"path":{"kind":"string","value":"/src/common/mod.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":748,"string":"748"},"score":{"kind":"number","value":3.65625,"string":"3.65625"},"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 const ALPHABET: &str = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\npub fn binary_to_char(bin: &str) -> Result {\n let binary = bin.as_bytes().iter().map(|b| b - 48).collect::>();\n for bit in &binary {\n if *bit > 1 {\n return Err(String::from(\"Must be a valid binary number\"));\n }\n }\n\n Ok((binary.iter().fold(0, |x, &b| x * 2 + b as u8) + 65) as char)\n}\n\n#[cfg(test)]\nmod tests {\n use super::binary_to_char;\n\n #[test]\n fn valid_binary() {\n assert!(binary_to_char(\"010\").is_ok());\n }\n\n #[test]\n fn invalid_binary() {\n assert!(binary_to_char(\"2010\").is_err());\n }\n\n #[test]\n fn number_to_char() {\n assert_eq!('C', binary_to_char(\"010\").unwrap());\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":162,"cells":{"blob_id":{"kind":"string","value":"e95dd4fc71955bf79eb1ebf030173d27eb981356"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"yuan-yuan-jia/Algorithms"},"path":{"kind":"string","value":"/src/problems/backtracking/nqueens.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4430,"string":"4,430"},"score":{"kind":"number","value":3.765625,"string":"3.765625"},"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":"//! The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.\n//!\n//! Given an integer n, return all distinct solutions to the n-queens puzzle.\n//!\n//! Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.\n//!\n//! # See also\n//!\n//! - [Leetcode](https://leetcode.com/problems/n-queens/)\n\nuse std::collections::HashSet;\n\npub fn solve_n_queens(n: i32) -> Vec> {\n Board::new(n as usize).solve()\n}\n\nstruct Board {\n matrix: Vec>,\n n: usize,\n solutions: HashSet>,\n}\n\nimpl Board {\n pub fn new(n: usize) -> Self {\n Self {\n matrix: vec![vec!['.'; n]; n],\n n,\n solutions: HashSet::new(),\n }\n }\n pub fn solve(mut self) -> Vec> {\n self._solve(0, 0);\n self.solutions.into_iter().collect()\n }\n fn _solve(&mut self, i: usize, count: usize) {\n if count == self.n {\n self.add_solution();\n } else if i == self.n {\n } else {\n for col in 0..self.n {\n if self.safe(i, col) {\n self.matrix[i][col] = 'Q';\n self._solve(i + 1, count + 1);\n self.matrix[i][col] = '.';\n }\n }\n }\n }\n fn add_solution(&mut self) {\n self.solutions.insert(\n self.matrix\n .iter()\n .map(|x| x.iter().copied().collect())\n .collect(),\n );\n }\n\n fn safe(&self, i: usize, j: usize) -> bool {\n for j_ in 0..self.n {\n if self.matrix[i][j_] == 'Q' {\n return false;\n }\n }\n for i_ in 0..self.n {\n if self.matrix[i_][j] == 'Q' {\n return false;\n }\n }\n let (mut i_, mut j_) = (i + 1, j + 1);\n while i_ > 0 && j_ > 0 {\n i_ -= 1;\n j_ -= 1;\n if self.matrix[i_][j_] == 'Q' {\n return false;\n }\n }\n let (mut i_, mut j_) = (i, j + 1);\n while i_ < self.n && j_ > 0 {\n j_ -= 1;\n if self.matrix[i_][j_] == 'Q' {\n return false;\n }\n i_ += 1;\n }\n let (mut i_, mut j_) = (i, j);\n while i_ < self.n && j_ < self.n {\n if self.matrix[i_][j_] == 'Q' {\n return false;\n }\n i_ += 1;\n j_ += 1;\n }\n let (mut i_, mut j_) = (i + 1, j);\n while i_ > 0 && j_ < self.n {\n i_ -= 1;\n if self.matrix[i_][j_] == 'Q' {\n return false;\n }\n j_ += 1;\n }\n true\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n #[test]\n fn test_n_queens() {\n let n1 = solve_n_queens(1);\n assert_eq!(n1, vec![vec![\"Q\".to_string()]]);\n\n let n2 = solve_n_queens(2);\n assert!(n2.is_empty());\n\n let n3 = solve_n_queens(3);\n assert!(n3.is_empty());\n\n let mut n4 = solve_n_queens(4);\n n4.sort();\n assert_eq!(\n n4,\n make_solution(&[\n &[\"..Q.\", \"Q...\", \"...Q\", \".Q..\"],\n &[\".Q..\", \"...Q\", \"Q...\", \"..Q.\"],\n ])\n );\n\n let mut n5 = solve_n_queens(5);\n let mut n5_expected = make_solution(&[\n &[\"..Q..\", \"....Q\", \".Q...\", \"...Q.\", \"Q....\"],\n &[\"...Q.\", \"Q....\", \"..Q..\", \"....Q\", \".Q...\"],\n &[\"....Q\", \".Q...\", \"...Q.\", \"Q....\", \"..Q..\"],\n &[\"Q....\", \"...Q.\", \".Q...\", \"....Q\", \"..Q..\"],\n &[\".Q...\", \"....Q\", \"..Q..\", \"Q....\", \"...Q.\"],\n &[\"....Q\", \"..Q..\", \"Q....\", \"...Q.\", \".Q...\"],\n &[\".Q...\", \"...Q.\", \"Q....\", \"..Q..\", \"....Q\"],\n &[\"..Q..\", \"Q....\", \"...Q.\", \".Q...\", \"....Q\"],\n &[\"...Q.\", \".Q...\", \"....Q\", \"..Q..\", \"Q....\"],\n &[\"Q....\", \"..Q..\", \"....Q\", \".Q...\", \"...Q.\"],\n ]);\n n5.sort();\n n5_expected.sort();\n assert_eq!(n5, n5_expected);\n\n let n8 = solve_n_queens(8);\n assert_eq!(n8.len(), 92);\n }\n\n fn make_solution(sol: &[&[&'static str]]) -> Vec> {\n sol.iter()\n .map(|&x| x.iter().map(|&s| s.to_owned()).collect())\n .collect()\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":163,"cells":{"blob_id":{"kind":"string","value":"efd3d047c44fa30c6f88b9de8f3cc4410a97acaf"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"arbanhossain/5dchess-tools"},"path":{"kind":"string","value":"/lib/parse.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2769,"string":"2,769"},"score":{"kind":"number","value":3.015625,"string":"3.015625"},"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 super::game;\nuse serde::Deserialize;\n\n#[derive(Debug, Deserialize)]\nstruct GameRaw {\n timelines: Vec,\n width: u8,\n height: u8,\n active_player: bool,\n}\n\n/// Represents an in-game timeline\n#[derive(Debug, Deserialize)]\nstruct TimelineRaw {\n index: f32,\n states: Vec>,\n width: u8,\n height: u8,\n begins_at: isize,\n emerges_from: Option,\n}\n\npub fn parse(raw: &str) -> Option {\n let game_raw: GameRaw = serde_json::from_str(raw).ok()?;\n\n let even_initial_timelines = game_raw\n .timelines\n .iter()\n .any(|tl| tl.index == -0.5 || tl.index == 0.5);\n\n let min_timeline = game_raw.timelines\n .iter()\n .map(|tl| tl.index)\n .min_by_key(|x| (*x) as isize)?;\n let max_timeline = game_raw.timelines\n .iter()\n .map(|tl| tl.index)\n .max_by_key(|x| (*x) as isize)?;\n\n let timeline_width = ((-min_timeline).min(max_timeline) + 1.0).round();\n let active_timelines = game_raw.timelines\n .iter()\n .filter(|tl| tl.index.abs() <= timeline_width);\n let present = active_timelines\n .map(|tl| tl.begins_at + (tl.states.len() as isize) - 1)\n .min()?;\n\n let mut res = game::Game::new(game_raw.width, game_raw.height);\n\n res.info.present = present;\n res.info.min_timeline = de_l(min_timeline, even_initial_timelines);\n res.info.max_timeline = de_l(max_timeline, even_initial_timelines);\n res.info.active_player = game_raw.active_player;\n res.info.even_initial_timelines = even_initial_timelines;\n\n for tl in game_raw.timelines.into_iter() {\n res.timelines.insert(\n de_l(tl.index, even_initial_timelines),\n de_timeline(tl, even_initial_timelines),\n );\n }\n\n Some(res)\n}\n\nfn de_board(raw: Vec, t: isize, l: i32, width: u8, height: u8) -> game::Board {\n let mut res = game::Board::new(t, l, width, height);\n res.pieces = raw\n .into_iter()\n .map(|x| game::Piece::from(x))\n .collect();\n res\n}\n\nfn de_l(raw: f32, even: bool) -> i32 {\n if even && raw < 0.0 {\n (raw.ceil() - 1.0) as i32\n } else {\n raw.floor() as i32\n }\n}\n\nfn de_timeline(raw: TimelineRaw, even: bool) -> game::Timeline {\n let mut res = game::Timeline::new(\n de_l(raw.index, even),\n raw.width,\n raw.height,\n raw.begins_at,\n raw.emerges_from.map(|x| de_l(x, even)),\n );\n\n let index = de_l(raw.index, even);\n let begins_at = raw.begins_at;\n let width = raw.width;\n let height = raw.height;\n\n res.states = raw\n .states\n .into_iter()\n .enumerate()\n .map(|(i, b)| de_board(b, begins_at + i as isize, index, width, height))\n .collect();\n\n res\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":164,"cells":{"blob_id":{"kind":"string","value":"df05578e32242c25d9e7d2077794fc3a2da03bce"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"0000marcell/LearnRust"},"path":{"kind":"string","value":"/RH/aoc1/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1188,"string":"1,188"},"score":{"kind":"number","value":3.90625,"string":"3.90625"},"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":"fn main() {\n let instruction: Vec = std::env::args().collect();\n let instruction: &String = &instruction[1];\n\n println!(\"{}\", santa(instruction));\n}\n\nfn santa(instruction: &String) -> i32 {\n // if '(' up else if ')' down\n let mut floor: i32 = 0;\n for paren in instruction.chars() {\n println!(\"{}\", paren);\n match paren {\n '(' => floor += 1,\n ')' => floor -= 1,\n _ => panic!(),\n }\n }\n floor\n}\n\n// #[cfg(test)]\nmod test {\n use super::santa;\n #[test]\n fn example() {\n assert!(santa(&\"(())\".to_string()) == 0);\n assert!(santa(&\"()()\".to_string()) == 0);\n assert!(santa(&\"(((\".to_string()) == 3);\n assert!(santa(&\"(()(()(\".to_string()) == 3);\n assert!(santa(&\"))(((((\".to_string()) == 3);\n assert!(santa(&\"())\".to_string()) == -1);\n assert!(santa(&\"))(\".to_string()) == -1);\n assert!(santa(&\")))\".to_string()) == -3);\n assert!(santa(&\")())())\".to_string()) == -3);\n }\n #[test]\n fn a() {\n assert!(santa(&\"\".to_string()) == 0);\n }\n #[test]\n #[should_panic]\n fn b() {\n santa(&\"{}\".to_string());\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":165,"cells":{"blob_id":{"kind":"string","value":"6a343d704b724f4e3b3d2632e8240d84080c4f8f"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Godofh3ell/el_monitorro-1"},"path":{"kind":"string","value":"/src/db.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2024,"string":"2,024"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"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 chrono::prelude::*;\nuse chrono::{DateTime, Utc};\nuse diesel::pg::PgConnection;\nuse diesel::r2d2::{ConnectionManager, Pool, PooledConnection};\nuse dotenv::dotenv;\nuse once_cell::sync::OnceCell;\nuse std::env;\nuse tokio::sync::Semaphore;\nuse tokio::sync::SemaphorePermit;\n\npub mod feed_items;\npub mod feeds;\npub mod telegram;\n\nstatic POOL: OnceCell>> = OnceCell::new();\nstatic SEMAPHORE: OnceCell = OnceCell::new();\nstatic POOL_NUMBER: OnceCell = OnceCell::new();\n\npub struct SemaphoredDbConnection<'a> {\n _semaphore_permit: SemaphorePermit<'a>,\n pub connection: PooledConnection>,\n}\n\npub async fn get_semaphored_connection<'a>() -> SemaphoredDbConnection<'a> {\n let _semaphore_permit = semaphore().acquire().await.unwrap();\n let connection = establish_connection();\n\n SemaphoredDbConnection {\n _semaphore_permit,\n connection,\n }\n}\n\npub fn current_time() -> DateTime {\n Utc::now().round_subsecs(0)\n}\n\npub fn establish_connection() -> PooledConnection> {\n pool().get().unwrap()\n}\n\npub fn semaphore() -> &'static Semaphore {\n SEMAPHORE.get_or_init(|| Semaphore::new(*pool_connection_number()))\n}\n\npub fn pool_connection_number() -> &'static usize {\n POOL_NUMBER.get_or_init(|| {\n dotenv().ok();\n\n let database_pool_size_str =\n env::var(\"DATABASE_POOL_SIZE\").unwrap_or_else(|_| \"10\".to_string());\n let database_pool_size: usize = database_pool_size_str.parse().unwrap();\n\n database_pool_size\n })\n}\n\nfn pool() -> &'static Pool> {\n POOL.get_or_init(|| {\n dotenv().ok();\n\n let database_url = env::var(\"DATABASE_URL\").expect(\"DATABASE_URL must be set\");\n\n let manager = ConnectionManager::::new(database_url);\n\n Pool::builder()\n .max_size(*pool_connection_number() as u32)\n .build(manager)\n .unwrap()\n })\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":166,"cells":{"blob_id":{"kind":"string","value":"916510d952a46ad8df39dc2a78aee51d1daedaac"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"potatosalad/leetcode"},"path":{"kind":"string","value":"/src/n1122_relative_sort_array.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1815,"string":"1,815"},"score":{"kind":"number","value":3.625,"string":"3.625"},"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 * [1122] Relative Sort Array\n *\n * Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.\n * Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order.\n * \n * Example 1:\n * Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]\n * Output: [2,2,2,1,4,3,3,9,6,7,19]\n * \n * Constraints:\n *\n * \tarr1.length, arr2.length <= 1000\n * \t0 <= arr1[i], arr2[i] <= 1000\n * \tEach arr2[i] is distinct.\n * \tEach arr2[i] is in arr1.\n *\n */\npub struct Solution {}\n\n// submission codes start here\n\nuse std::collections::HashMap;\nuse std::collections::HashSet;\n\nimpl Solution {\n pub fn relative_sort_array(arr1: Vec, arr2: Vec) -> Vec {\n let set: HashSet = arr2.iter().copied().collect();\n let mut histogram: HashMap = HashMap::new();\n let mut tail: Vec = Vec::new();\n for n in arr1 {\n if set.contains(&n) {\n *(histogram.entry(n).or_insert(0)) += 1;\n } else {\n tail.push(n);\n }\n }\n let mut head: Vec = Vec::new();\n for n in arr2 {\n let x: usize = histogram.get(&n).copied().unwrap();\n head.append(&mut vec![n; x]);\n }\n tail.sort_unstable();\n head.append(&mut tail);\n head\n }\n}\n\n// submission codes end\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_1122() {\n assert_eq!(\n vec![2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19],\n Solution::relative_sort_array(\n vec![2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19],\n vec![2, 1, 4, 3, 9, 6]\n )\n );\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":167,"cells":{"blob_id":{"kind":"string","value":"22e8a01c9a2474f92601c744aaa918083d913c1b"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"TerminalStudio/nativeshell"},"path":{"kind":"string","value":"/nativeshell/src/shell/platform/win32/window_base.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":18540,"string":"18,540"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"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":"use std::{\n cell::RefCell,\n rc::{Rc, Weak},\n};\n\nuse crate::{\n shell::{\n api_model::{\n WindowFrame, WindowGeometry, WindowGeometryFlags, WindowGeometryRequest, WindowStyle,\n },\n IPoint, IRect, ISize, Point, Rect, Size,\n },\n util::OkLog,\n};\n\nuse super::{\n all_bindings::*,\n display::Displays,\n error::PlatformResult,\n flutter_sys::{FlutterDesktopGetDpiForHWND, FlutterDesktopGetDpiForMonitor},\n util::{clamp, BoolResultExt, HRESULTExt, GET_X_LPARAM, GET_Y_LPARAM},\n};\n\npub struct WindowBaseState {\n hwnd: HWND,\n min_frame_size: RefCell,\n max_frame_size: RefCell,\n min_content_size: RefCell,\n max_content_size: RefCell,\n delegate: Weak,\n style: RefCell,\n}\n\nconst LARGE_SIZE: f64 = 64.0 * 1024.0;\n\nimpl WindowBaseState {\n pub fn new(hwnd: HWND, delegate: Weak) -> Self {\n Self {\n hwnd,\n delegate,\n min_frame_size: RefCell::new(Size::wh(0.0, 0.0)),\n max_frame_size: RefCell::new(Size::wh(LARGE_SIZE, LARGE_SIZE)),\n min_content_size: RefCell::new(Size::wh(0.0, 0.0)),\n max_content_size: RefCell::new(Size::wh(LARGE_SIZE, LARGE_SIZE)),\n style: Default::default(),\n }\n }\n\n pub fn hide(&self) -> PlatformResult<()> {\n unsafe { ShowWindow(self.hwnd, SW_HIDE).as_platform_result() }\n }\n\n pub fn show(&self, callback: F) -> PlatformResult<()>\n where\n F: FnOnce() + 'static,\n {\n unsafe {\n ShowWindow(self.hwnd, SW_SHOW); // false is not an error\n }\n callback();\n Ok(())\n }\n\n pub fn set_geometry(\n &self,\n geometry: WindowGeometryRequest,\n ) -> PlatformResult {\n let geometry = geometry.filtered_by_preference();\n\n let mut res = WindowGeometryFlags {\n ..Default::default()\n };\n\n if geometry.content_origin.is_some()\n || geometry.content_size.is_some()\n || geometry.frame_origin.is_some()\n || geometry.frame_size.is_some()\n {\n self.set_bounds_geometry(&geometry, &mut res)?;\n\n // There's no set_content_rect in winapi, so this is best effort implementation\n // that tries to deduce future content rect from current content rect and frame rect\n // in case it's wrong (i.e. display with different DPI or frame size change after reposition)\n // it will retry once again\n if res.content_origin || res.content_size {\n let content_rect = self.content_rect_for_frame_rect(&self.get_frame_rect()?)?;\n if (res.content_origin\n && content_rect.origin() != *geometry.content_origin.as_ref().unwrap())\n || (res.content_size\n && content_rect.size() != *geometry.content_size.as_ref().unwrap())\n {\n // retry\n self.set_bounds_geometry(&geometry, &mut res)?;\n }\n }\n }\n\n if let Some(size) = geometry.min_frame_size {\n self.min_frame_size.replace(size);\n res.min_frame_size = true;\n }\n\n if let Some(size) = geometry.max_frame_size {\n self.max_frame_size.replace(size);\n res.max_frame_size = true;\n }\n\n if let Some(size) = geometry.min_content_size {\n self.min_content_size.replace(size);\n res.min_content_size = true;\n }\n\n if let Some(size) = geometry.max_content_size {\n self.max_content_size.replace(size);\n res.max_content_size = true;\n }\n\n Ok(res)\n }\n\n fn set_bounds_geometry(\n &self,\n geometry: &WindowGeometry,\n flags: &mut WindowGeometryFlags,\n ) -> PlatformResult<()> {\n let current_frame_rect = self.get_frame_rect()?;\n let current_content_rect = self.content_rect_for_frame_rect(&current_frame_rect)?;\n\n let content_offset = current_content_rect.to_local(&current_frame_rect.origin());\n let content_size_delta = current_frame_rect.size() - current_content_rect.size();\n\n let mut origin: Option = None;\n let mut size: Option = None;\n\n if let Some(frame_origin) = &geometry.frame_origin {\n origin.replace(frame_origin.clone());\n flags.frame_origin = true;\n }\n\n if let Some(frame_size) = &geometry.frame_size {\n size.replace(frame_size.clone());\n flags.frame_size = true;\n }\n\n if let Some(content_origin) = &geometry.content_origin {\n origin.replace(content_origin.translated(&content_offset));\n flags.content_origin = true;\n }\n\n if let Some(content_size) = &geometry.content_size {\n size.replace(content_size + &content_size_delta);\n flags.content_size = true;\n }\n\n let physical = IRect::origin_size(\n &self.to_physical(origin.as_ref().unwrap_or(&Point::xy(0.0, 0.0))),\n &size\n .as_ref()\n .unwrap_or(&Size::wh(0.0, 0.0))\n .scaled(self.get_scaling_factor())\n .into(),\n );\n\n let mut flags = SWP_NOZORDER | SWP_NOACTIVATE;\n if origin.is_none() {\n flags |= SWP_NOMOVE;\n }\n if size.is_none() {\n flags |= SWP_NOSIZE;\n }\n unsafe {\n SetWindowPos(\n self.hwnd,\n HWND(0),\n physical.x,\n physical.y,\n physical.width,\n physical.height,\n flags,\n )\n .as_platform_result()\n }\n }\n\n pub fn get_geometry(&self) -> PlatformResult {\n let frame_rect = self.get_frame_rect()?;\n let content_rect = self.content_rect_for_frame_rect(&frame_rect)?;\n\n Ok(WindowGeometry {\n frame_origin: Some(frame_rect.origin()),\n frame_size: Some(frame_rect.size()),\n content_origin: Some(content_rect.origin()),\n content_size: Some(content_rect.size()),\n min_frame_size: Some(self.min_frame_size.borrow().clone()),\n max_frame_size: Some(self.max_frame_size.borrow().clone()),\n min_content_size: Some(self.min_content_size.borrow().clone()),\n max_content_size: Some(self.max_content_size.borrow().clone()),\n })\n }\n\n pub fn supported_geometry(&self) -> PlatformResult {\n Ok(WindowGeometryFlags {\n frame_origin: true,\n frame_size: true,\n content_origin: true,\n content_size: true,\n min_frame_size: true,\n max_frame_size: true,\n min_content_size: true,\n max_content_size: true,\n })\n }\n\n fn get_frame_rect(&self) -> PlatformResult {\n let mut rect: RECT = Default::default();\n unsafe {\n GetWindowRect(self.hwnd, &mut rect as *mut _).as_platform_result()?;\n }\n let size: Size = ISize::wh(rect.right - rect.left, rect.bottom - rect.top).into();\n Ok(Rect::origin_size(\n &self.to_logical(&IPoint::xy(rect.left, rect.top)),\n &size.scaled(1.0 / self.get_scaling_factor()),\n ))\n }\n\n fn content_rect_for_frame_rect(&self, frame_rect: &Rect) -> PlatformResult {\n let content_rect = IRect::origin_size(\n &self.to_physical(&frame_rect.top_left()),\n &frame_rect.size().scaled(self.get_scaling_factor()).into(),\n );\n let rect = RECT {\n left: content_rect.x,\n top: content_rect.y,\n right: content_rect.x2(),\n bottom: content_rect.y2(),\n };\n unsafe {\n SendMessageW(\n self.hwnd,\n WM_NCCALCSIZE as u32,\n WPARAM(0),\n LPARAM(&rect as *const _ as isize),\n );\n }\n let size: Size = ISize::wh(rect.right - rect.left, rect.bottom - rect.top).into();\n Ok(Rect::origin_size(\n &self.to_logical(&IPoint::xy(rect.left, rect.top)),\n &size.scaled(1.0 / self.get_scaling_factor()),\n ))\n }\n\n fn adjust_window_position(&self, position: &mut WINDOWPOS) -> PlatformResult<()> {\n let scale = self.get_scaling_factor();\n let frame_rect = self.get_frame_rect()?;\n let content_rect = self.content_rect_for_frame_rect(&frame_rect)?;\n\n let size_delta = frame_rect.size() - content_rect.size();\n\n let min_content = &*self.min_content_size.borrow() + &size_delta;\n let min_content: ISize = min_content.scaled(scale).into();\n\n let min_frame = self.min_frame_size.borrow();\n let min_frame: ISize = min_frame.scaled(scale).into();\n\n let min_size = ISize::wh(\n std::cmp::max(min_content.width, min_frame.width),\n std::cmp::max(min_content.height, min_frame.height),\n );\n\n let max_content = &*self.max_content_size.borrow() + &size_delta;\n let max_content: ISize = max_content.scaled(scale).into();\n\n let max_frame = self.max_frame_size.borrow();\n let max_frame: ISize = max_frame.scaled(scale).into();\n\n let max_size = ISize::wh(\n std::cmp::min(max_content.width, max_frame.width),\n std::cmp::min(max_content.height, max_frame.height),\n );\n\n position.cx = clamp(position.cx, min_size.width, max_size.width);\n position.cy = clamp(position.cy, min_size.height, max_size.height);\n\n Ok(())\n }\n\n pub fn close(&self) -> PlatformResult<()> {\n unsafe { DestroyWindow(self.hwnd).as_platform_result() }\n }\n\n pub fn local_to_global(&self, offset: &Point) -> IPoint {\n let scaled: IPoint = offset.scaled(self.get_scaling_factor()).into();\n self.local_to_global_physical(&scaled)\n }\n\n pub fn local_to_global_physical(&self, offset: &IPoint) -> IPoint {\n let mut point = POINT {\n x: offset.x,\n y: offset.y,\n };\n unsafe {\n ClientToScreen(self.hwnd, &mut point as *mut _);\n }\n IPoint::xy(point.x, point.y)\n }\n\n pub fn global_to_local(&self, offset: &IPoint) -> Point {\n let local: Point = self.global_to_local_physical(&offset).into();\n local.scaled(1.0 / self.get_scaling_factor())\n }\n\n pub fn global_to_local_physical(&self, offset: &IPoint) -> IPoint {\n let mut point = POINT {\n x: offset.x,\n y: offset.y,\n };\n unsafe {\n ScreenToClient(self.hwnd, &mut point as *mut _);\n }\n IPoint::xy(point.x, point.y)\n }\n\n fn to_physical(&self, offset: &Point) -> IPoint {\n Displays::get_displays()\n .convert_logical_to_physical(offset)\n .unwrap_or_else(|| offset.clone().into())\n }\n\n fn to_logical(&self, offset: &IPoint) -> Point {\n Displays::get_displays()\n .convert_physical_to_logical(offset)\n .unwrap_or_else(|| offset.clone().into())\n }\n\n pub fn is_rtl(&self) -> bool {\n let style = WINDOW_EX_STYLE(unsafe { GetWindowLongW(self.hwnd, GWL_EXSTYLE) } as u32);\n style & WS_EX_LAYOUTRTL == WS_EX_LAYOUTRTL\n }\n\n pub fn get_scaling_factor(&self) -> f64 {\n unsafe { FlutterDesktopGetDpiForHWND(self.hwnd) as f64 / 96.0 }\n }\n\n #[allow(unused)]\n fn get_scaling_factor_for_monitor(&self, monitor: isize) -> f64 {\n unsafe { FlutterDesktopGetDpiForMonitor(monitor) as f64 / 96.0 }\n }\n\n fn delegate(&self) -> Rc {\n // delegate owns us so unwrap is safe here\n self.delegate.upgrade().unwrap()\n }\n\n unsafe fn set_close_enabled(&self, enabled: bool) {\n let menu = GetSystemMenu(self.hwnd, false);\n if enabled {\n EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED);\n } else {\n EnableMenuItem(\n menu,\n SC_CLOSE as u32,\n MF_BYCOMMAND | MF_DISABLED | MF_GRAYED,\n );\n }\n }\n\n pub fn update_dwm_frame(&self) -> PlatformResult<()> {\n let margin = match self.style.borrow().frame {\n WindowFrame::Regular => 0, // already has shadow\n WindowFrame::NoTitle => 1, // neede for window shadow\n WindowFrame::NoFrame => 0, // neede for transparency\n };\n\n let margins = MARGINS {\n cxLeftWidth: 0,\n cxRightWidth: 0,\n cyTopHeight: margin,\n cyBottomHeight: 0,\n };\n unsafe {\n DwmExtendFrameIntoClientArea(self.hwnd, &margins as *const _).as_platform_result()\n }\n }\n\n pub fn set_title(&self, title: String) -> PlatformResult<()> {\n unsafe {\n SetWindowTextW(self.hwnd, title);\n }\n Ok(())\n }\n\n pub fn set_style(&self, style: WindowStyle) -> PlatformResult<()> {\n *self.style.borrow_mut() = style.clone();\n unsafe {\n let mut s = WINDOW_STYLE(GetWindowLongW(self.hwnd, GWL_STYLE) as u32);\n s &= WINDOW_STYLE(!(WS_OVERLAPPEDWINDOW | WS_DLGFRAME).0);\n\n if style.frame == WindowFrame::Regular {\n s |= WS_CAPTION;\n if style.can_resize {\n s |= WS_THICKFRAME;\n }\n }\n\n if style.frame == WindowFrame::NoTitle {\n s |= WS_CAPTION;\n if style.can_resize {\n s |= WS_THICKFRAME;\n } else {\n s |= WS_BORDER;\n }\n }\n\n if style.frame == WindowFrame::NoFrame {\n s |= WS_POPUP\n }\n\n s |= WS_SYSMENU;\n self.set_close_enabled(style.can_close);\n if style.can_maximize && style.can_resize {\n s |= WS_MAXIMIZEBOX;\n }\n if style.can_minimize {\n s |= WS_MINIMIZEBOX;\n }\n\n SetWindowLongW(self.hwnd, GWL_STYLE, s.0 as i32);\n SetWindowPos(\n self.hwnd,\n HWND(0),\n 0,\n 0,\n 0,\n 0,\n SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER,\n )\n .as_platform_result()?;\n\n self.update_dwm_frame()?;\n }\n Ok(())\n }\n\n pub fn perform_window_drag(&self) -> PlatformResult<()> {\n unsafe {\n println!(\"Perform window drag!\");\n ReleaseCapture();\n SendMessageW(\n self.hwnd,\n WM_NCLBUTTONDOWN as u32,\n WPARAM(HTCAPTION as usize),\n LPARAM(0),\n );\n }\n Ok(())\n }\n\n pub fn has_redirection_surface(&self) -> bool {\n let style = WINDOW_EX_STYLE(unsafe { GetWindowLongW(self.hwnd, GWL_EXSTYLE) } as u32);\n (style & WS_EX_NOREDIRECTIONBITMAP).0 == 0\n }\n\n pub fn remove_border(&self) -> bool {\n self.style.borrow().frame == WindowFrame::NoTitle\n }\n\n fn do_hit_test(&self, x: i32, y: i32) -> u32 {\n let mut win_rect = RECT::default();\n unsafe {\n GetWindowRect(self.hwnd, &mut win_rect as *mut _);\n }\n\n let border_width = (7.0 * self.get_scaling_factor()) as i32;\n\n if x < win_rect.left + border_width && y < win_rect.top + border_width {\n HTTOPLEFT\n } else if x > win_rect.right - border_width && y < win_rect.top + border_width {\n HTTOPRIGHT\n } else if y < win_rect.top + border_width {\n HTTOP\n } else if x < win_rect.left + border_width && y > win_rect.bottom - border_width {\n HTBOTTOMLEFT\n } else if x > win_rect.right - border_width && y > win_rect.bottom - border_width {\n HTBOTTOMRIGHT\n } else if y > win_rect.bottom - border_width {\n HTBOTTOM\n } else if x < win_rect.left + border_width {\n HTLEFT\n } else if x > win_rect.right - border_width {\n HTRIGHT\n } else {\n HTCLIENT\n }\n }\n\n pub fn handle_message(\n &self,\n _h_wnd: HWND,\n msg: u32,\n _w_param: WPARAM,\n l_param: LPARAM,\n ) -> Option {\n match msg {\n WM_CLOSE => {\n self.delegate().should_close();\n Some(LRESULT(0))\n }\n WM_DESTROY => {\n self.delegate().will_close();\n None\n }\n WM_DISPLAYCHANGE => {\n Displays::displays_changed();\n self.delegate().displays_changed();\n None\n }\n WM_WINDOWPOSCHANGING => {\n let position = unsafe { &mut *(l_param.0 as *mut WINDOWPOS) };\n self.adjust_window_position(position).ok_log();\n None\n }\n WM_DWMCOMPOSITIONCHANGED => {\n self.update_dwm_frame().ok_log();\n None\n }\n WM_NCCALCSIZE => {\n if self.remove_border() {\n Some(LRESULT(1))\n } else {\n None\n }\n }\n WM_NCHITTEST => {\n if self.remove_border() {\n let res = self.do_hit_test(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param));\n Some(LRESULT(res as i32))\n } else {\n None\n }\n }\n _ => None,\n }\n }\n\n pub fn handle_child_message(\n &self,\n _h_wnd: HWND,\n msg: u32,\n _w_param: WPARAM,\n l_param: LPARAM,\n ) -> Option {\n match msg {\n WM_NCHITTEST => {\n if self.remove_border() {\n let res = self.do_hit_test(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param));\n if res != HTCLIENT {\n Some(LRESULT(HTTRANSPARENT))\n } else {\n Some(LRESULT(res as i32))\n }\n } else {\n None\n }\n }\n _ => None,\n }\n }\n}\n\npub trait WindowDelegate {\n fn should_close(&self);\n fn will_close(&self);\n fn displays_changed(&self);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":168,"cells":{"blob_id":{"kind":"string","value":"8e91db882281095b6715f97f1a64202981b013ce"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"DrewKestell/ForayRust"},"path":{"kind":"string","value":"/src/game_timer.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3022,"string":"3,022"},"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":"use winapi::um::profileapi::QueryPerformanceCounter;\nuse winapi::shared::ntdef::LARGE_INTEGER;\nuse std::mem::zeroed;\n\npub struct GameTimer {\n seconds_per_count: f64,\n delta_time: f64,\n base_time: i64,\n paused_time: i64,\n stop_time: i64,\n previous_time: i64,\n current_time: i64,\n stopped: bool\n}\n\nimpl GameTimer {\n pub fn new() -> GameTimer {\n unsafe {\n let mut counts_per_second: LARGE_INTEGER = zeroed();\n QueryPerformanceCounter(&mut counts_per_second);\n let seconds_per_count = 1.0 / *counts_per_second.QuadPart() as f64;\n\n GameTimer {\n seconds_per_count: seconds_per_count,\n delta_time: -1.0,\n base_time: 0,\n paused_time: 0,\n stop_time: 0,\n previous_time: 0,\n current_time: 0,\n stopped: false\n }\n }\n }\n\n pub fn tick(&mut self) {\n if self.stopped {\n self.delta_time = 0.0;\n return;\n }\n\n unsafe {\n let mut current_time: LARGE_INTEGER = zeroed();\n QueryPerformanceCounter(&mut current_time);\n self.current_time = *current_time.QuadPart();\n }\n\n self.delta_time = (self.current_time - self.previous_time) as f64 * self.seconds_per_count;\n self.previous_time = self.current_time;\n \n if self.delta_time < 0.0 {\n self.delta_time = 0.0;\n }\n }\n\n pub fn reset(&mut self) {\n unsafe {\n let mut current_time: LARGE_INTEGER = zeroed();\n QueryPerformanceCounter(&mut current_time);\n\n self.base_time = *current_time.QuadPart();\n self.previous_time = *current_time.QuadPart();\n self.stop_time = *current_time.QuadPart();\n self.stopped = false;\n }\n }\n\n pub fn stop(&mut self) {\n if !self.stopped {\n unsafe {\n let mut current_time: LARGE_INTEGER = zeroed();\n QueryPerformanceCounter(&mut current_time);\n self.stop_time = *current_time.QuadPart();\n self.stopped = true;\n }\n }\n }\n\n pub fn start(&mut self) {\n if self.stopped {\n unsafe {\n let mut start_time: LARGE_INTEGER = zeroed();\n QueryPerformanceCounter(&mut start_time);\n\n self.paused_time += *start_time.QuadPart() - self.stop_time;\n self.previous_time = *start_time.QuadPart();\n self.stop_time = 0;\n self.stopped = false;\n }\n }\n }\n\n pub fn total_time(&self) -> f64 {\n if self.stopped {\n ((self.stop_time - self.paused_time) - self.base_time) as f64 * self.seconds_per_count\n }\n else {\n ((self.current_time - self.paused_time) - self.base_time) as f64 * self.seconds_per_count\n }\n }\n\n pub fn delta_time(&self) -> f64 {\n self.delta_time\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":169,"cells":{"blob_id":{"kind":"string","value":"c3337f1f1473accd16e0a194ec276ef69b78cc85"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"gloriousfutureio/hermitdb"},"path":{"kind":"string","value":"/src/memory_log.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2578,"string":"2,578"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"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::BTreeMap;\nuse std::fmt::Debug;\n\nuse crdts::{CmRDT, Actor};\nuse log::{TaggedOp, LogReplicable};\nuse error::Result;\n\n#[derive(Debug, Clone)]\npub struct Log {\n actor: A,\n logs: BTreeMap)>\n}\n\n#[derive(Debug, Clone)]\npub struct Op {\n actor: A,\n index: u64,\n op: C::Op\n}\n\nimpl TaggedOp for Op {\n type ID = (A, u64);\n\n fn id(&self) -> Self::ID {\n (self.actor.clone(), self.index)\n }\n\n fn op(&self) -> &C::Op {\n &self.op\n }\n}\n\nimpl LogReplicable for Log {\n type Op = Op;\n\n fn next(&self) -> Result> {\n let largest_lag = self.logs.iter()\n .max_by_key(|(_, (index, log))| (log.len() as u64) - *index);\n\n if let Some((actor, (index, log))) = largest_lag {\n if *index >= log.len() as u64 {\n Ok(None)\n } else {\n Ok(Some(Op {\n actor: actor.clone(),\n index: *index,\n op: log[*index as usize].clone()\n }))\n }\n } else {\n Ok(None)\n }\n }\n\n fn ack(&mut self, op: &Self::Op) -> Result<()> {\n // We can ack ops that are not present in the log\n \n let (actor, index) = op.id();\n \n let log = self.logs.entry(actor)\n .or_insert_with(|| (0, Vec::new()));\n \n log.0 = index + 1;\n Ok(())\n }\n\n fn commit(&mut self, op: C::Op) -> Result {\n let log = self.logs.entry(self.actor.clone())\n .or_insert_with(|| (0, Vec::new()));\n\n log.1.push(op.clone());\n\n Ok(Op {\n actor: self.actor.clone(),\n index: log.0,\n op: op\n })\n }\n\n fn pull(&mut self, other: &Self) -> Result<()> {\n for (actor, (_, log)) in other.logs.iter() {\n let entry = self.logs.entry(actor.clone())\n .or_insert_with(|| (0, vec![]));\n\n if log.len() > entry.1.len() {\n for i in (entry.1.len())..log.len() {\n entry.1.push(log[i as usize].clone());\n }\n }\n }\n Ok(())\n }\n\n fn push(&self, other: &mut Self) -> Result<()> {\n other.pull(self)\n }\n}\n\nimpl Log {\n pub fn new(actor: A) -> Self {\n Log {\n actor: actor,\n logs: BTreeMap::new()\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":170,"cells":{"blob_id":{"kind":"string","value":"3b6a8bd239de8e214574da7f3d0eb3faedfd1d68"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"AlberErre/rust-experiments"},"path":{"kind":"string","value":"/fizz-buzz/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":573,"string":"573"},"score":{"kind":"number","value":4.15625,"string":"4.15625"},"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":"fn main() {\n println!(\"Hello, Fizz Buzz!\");\n\n const NUMBER: i32 = 35;\n\n let fizz_buzz_result = fizz_buzz(NUMBER);\n\n println!(\"Fizz Buzz for number {} is: {:?}\", NUMBER, fizz_buzz_result);\n}\n\nfn fizz_buzz(number: i32) -> Vec {\n //NOTE: we start at 1 to avoid handling another case with 0\n let numbers = 1..=number;\n\n numbers\n .map(|n| match n {\n n if (n % 3 == 0 && n % 5 == 0) => String::from(\"FizzBuzz\"),\n n if n % 3 == 0 => String::from(\"Fizz\"),\n n if n % 5 == 0 => String::from(\"Buzz\"),\n _ => n.to_string(),\n })\n .collect()\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":171,"cells":{"blob_id":{"kind":"string","value":"00813770f2c8333ff4b3a5282971ad36f1644f50"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Dongitestil/PL_2_Rust"},"path":{"kind":"string","value":"/server/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1569,"string":"1,569"},"score":{"kind":"number","value":2.8125,"string":"2.8125"},"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::thread;\nuse std::net::{TcpListener, TcpStream, Shutdown};\nuse std::io::{Read, Write};\nuse std::str::from_utf8;\nmod protector;\nuse protector::*;\n\nfn handle_client(mut stream: TcpStream) {\n let mut hash = [0 as u8; 5]; \n let mut key = [0 as u8; 10];\n let mut mes = [0 as u8;50];\n while match stream.read(&mut hash) {\n Ok(_) => {\n stream.read(&mut key);\n stream.read(&mut mes);\n let text1 = from_utf8(&hash).unwrap();\n let text2 = from_utf8(&key).unwrap();\n let new_key = next_session_key(&text1,&text2);\n let result = new_key.clone().into_bytes();\n //отправка данных\n stream.write(&result).unwrap();\n stream.write(&mes).unwrap();\n true\n },\n Err(_) => {\n println!(\"Ошибка при подключении к {}\", stream.peer_addr().unwrap());\n stream.shutdown(Shutdown::Both).unwrap();\n false\n }\n } {}\n}\n\nfn main() {\n let listener = TcpListener::bind(\"0.0.0.0:3333\").unwrap();\n println!(\"Сервер запустился...\");\n for stream in listener.incoming() {\n match stream {\n Ok(stream) => {\n println!(\"Новое подключение: {}\", stream.peer_addr().unwrap());\n thread::spawn(move|| {\n handle_client(stream)\n });\n }\n Err(e) => {\n println!(\"Ошибка: {}\", e);\n }\n }\n }\n drop(listener);\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":172,"cells":{"blob_id":{"kind":"string","value":"ce1070567ee74acc90f0f31ff337228e172fe016"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"evelynmitchell/stateright.github.io"},"path":{"kind":"string","value":"/rs-src/getting-started/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3202,"string":"3,202"},"score":{"kind":"number","value":2.53125,"string":"2.53125"},"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":"/* ANCHOR: all */\nuse stateright::actor::{*, register::*};\nuse std::borrow::Cow; // COW == clone-on-write\nuse std::net::{SocketAddrV4, Ipv4Addr};\n\n// ANCHOR: actor\ntype RequestId = u64;\n\n#[derive(Clone)]\nstruct ServerActor;\n\nimpl Actor for ServerActor {\n type Msg = RegisterMsg;\n type State = char;\n\n fn on_start(&self, _id: Id, _o: &mut Out) -> Self::State {\n '?' // default value for the register\n }\n\n fn on_msg(&self, _id: Id, state: &mut Cow,\n src: Id, msg: Self::Msg, o: &mut Out) {\n match msg {\n RegisterMsg::Put(req_id, value) => {\n *state.to_mut() = value;\n o.send(src, RegisterMsg::PutOk(req_id));\n }\n RegisterMsg::Get(req_id) => {\n o.send(src, RegisterMsg::GetOk(req_id, **state));\n }\n _ => {}\n }\n }\n}\n// ANCHOR_END: actor\n\n#[cfg(test)]\nmod test {\n use super::*;\n use stateright::{*, semantics::*, semantics::register::*};\n use ActorModelAction::Deliver;\n use RegisterMsg::{Get, GetOk, Put, PutOk};\n\n // ANCHOR: test\n #[test]\n fn is_unfortunately_not_linearizable() {\n let checker = ActorModel::new(\n (),\n LinearizabilityTester::new(Register('?'))\n )\n .actor(RegisterActor::Server(ServerActor))\n .actor(RegisterActor::Client { put_count: 2, server_count: 1 })\n .property(Expectation::Always, \"linearizable\", |_, state| {\n state.history.serialized_history().is_some()\n })\n .property(Expectation::Sometimes, \"get succeeds\", |_, state| {\n state.network.iter().any(|e| matches!(e.msg, RegisterMsg::GetOk(_, _)))\n })\n .property(Expectation::Sometimes, \"put succeeds\", |_, state| {\n state.network.iter().any(|e| matches!(e.msg, RegisterMsg::PutOk(_)))\n })\n .record_msg_in(RegisterMsg::record_returns)\n .record_msg_out(RegisterMsg::record_invocations)\n .checker().spawn_dfs().join();\n //checker.assert_properties(); // TRY IT: Uncomment this line, and the test will fail.\n checker.assert_discovery(\"linearizable\", vec![\n Deliver { src: Id::from(1), dst: Id::from(0), msg: Put(1, 'A') },\n Deliver { src: Id::from(0), dst: Id::from(1), msg: PutOk(1) },\n Deliver { src: Id::from(1), dst: Id::from(0), msg: Put(2, 'Z') },\n Deliver { src: Id::from(0), dst: Id::from(1), msg: PutOk(2) },\n Deliver { src: Id::from(1), dst: Id::from(0), msg: Put(1, 'A') },\n Deliver { src: Id::from(1), dst: Id::from(0), msg: Get(3) },\n Deliver { src: Id::from(0), dst: Id::from(1), msg: GetOk(3, 'A') },\n ]);\n }\n // ANCHOR_END: test\n}\n\n// ANCHOR: main\nfn main() {\n env_logger::init_from_env(env_logger::Env::default().default_filter_or(\"info\"));\n spawn(\n serde_json::to_vec,\n |bytes| serde_json::from_slice(bytes),\n vec![\n (SocketAddrV4::new(Ipv4Addr::LOCALHOST, 3000), ServerActor)\n ]).unwrap();\n}\n// ANCHOR_END: main\n/* ANCHOR_END: all */\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":173,"cells":{"blob_id":{"kind":"string","value":"539a574f3851eefc209d9506b0cbe9999a5ed8f8"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"unpluggedcoder/memory-profiler"},"path":{"kind":"string","value":"/integration-tests/test-programs/return-opt-u128.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":401,"string":"401"},"score":{"kind":"number","value":2.640625,"string":"2.640625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["Apache-2.0","LicenseRef-scancode-unknown-license-reference","MIT"],"string":"[\n \"Apache-2.0\",\n \"LicenseRef-scancode-unknown-license-reference\",\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"const CONSTANT: u128 = 0xaaaaaaaaaaaaaaaa5555555555555555;\n\nextern {\n fn malloc( size: usize ) -> *const u8;\n fn abort() -> !;\n}\n\n#[inline(never)]\n#[no_mangle]\nfn func_1() -> Option< u128 > {\n unsafe { malloc( 123456 ); }\n Some( CONSTANT )\n}\n\n#[inline(never)]\n#[no_mangle]\nfn func_2() {\n if func_1() != Some( CONSTANT ) {\n unsafe { abort(); }\n }\n}\n\nfn main() {\n func_2();\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":174,"cells":{"blob_id":{"kind":"string","value":"d24d4db001063f5d1473e134935fe0021b6b5b70"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"kavirajk/pgroup"},"path":{"kind":"string","value":"/src/lib.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2373,"string":"2,373"},"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 bincode;\nuse crossbeam_channel::Receiver;\nuse serde::{Deserialize, Serialize};\nuse std::collections::HashMap;\nuse std::net::{SocketAddr, ToSocketAddrs, UdpSocket};\n\n#[derive(Debug)]\nstruct Group {\n me: Node,\n peers: HashMap,\n\n // ack for specific ping's seq_no.\n ack_handlers: HashMap>,\n}\n\nimpl Group {\n fn members(&self) -> Vec {\n unimplemented!()\n }\n\n fn new(me: Node, seed_peers: &[Node]) -> Self {\n unimplemented!()\n }\n\n fn probe_peers(&self) {\n unimplemented!()\n }\n\n fn probe(&self, node: &Node) {\n unimplemented!()\n }\n\n fn packet_listener(&self) -> Result<(), String> {\n let mut buf: Vec = vec![0; 1024];\n\n self.me.sock.recv(&mut buf).unwrap();\n\n let pkt = decode_packet(&buf).unwrap();\n\n match pkt {\n Packet::Ping { from, seq_no } => if self.ack_handlers.contains_key(&seq_no) {},\n Packet::Ack { from, seq_no } => {}\n Packet::PingReq => {}\n Packet::IndirectAck => {}\n _ => {}\n }\n\n Ok(())\n }\n\n fn send(sock: &UdpSocket, msg: Vec, to: T) -> std::io::Result {\n sock.send_to(&msg, to)\n }\n\n fn encode_and_send() {}\n}\n\n#[derive(Debug)]\nstruct Node {\n name: String,\n seq_no: u64,\n incar_no: u64,\n addr: SocketAddr,\n sock: UdpSocket,\n state: NodeState,\n}\n\nimpl Node {\n fn next_seq_no(&self) {\n unimplemented!()\n }\n\n fn next_incar_no(&self) {\n unimplemented!()\n }\n}\n\n#[derive(Debug)]\nenum NodeState {\n Alive,\n Dead,\n Suspect,\n}\n\n#[derive(Serialize, Deserialize, Debug, PartialEq)]\nenum Packet {\n Ping { from: String, seq_no: u32 },\n Ack { from: String, seq_no: u32 },\n PingReq,\n IndirectAck,\n Alive,\n Joined,\n Left,\n Failed,\n}\n\nfn encode_packet(pkt: &Packet) -> Result, String> {\n let buf = bincode::serialize(pkt).unwrap();\n Ok(buf)\n}\n\nfn decode_packet(buf: &[u8]) -> Result {\n let pkt: Packet = bincode::deserialize(buf).unwrap();\n Ok(pkt)\n}\n\n#[test]\nfn test_encode_decode() {\n let before = Packet::Ping {\n from: \"me\".to_owned(),\n seq_no: 1234,\n };\n\n let buf = encode_packet(&before).unwrap();\n\n let after = decode_packet(&buf).unwrap();\n\n assert_eq!(before, after);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":175,"cells":{"blob_id":{"kind":"string","value":"f9a2594077419e7a188555f362be2af0e36c6b1a"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"quinnnned/rust-mancala"},"path":{"kind":"string","value":"/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":9671,"string":"9,671"},"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 std::fmt;\n\n#[derive(Copy, Clone, PartialEq, Debug)]\nstruct Player {\n pits: [i8; 6],\n score: i8,\n}\n\nimpl Player {\n fn get_moves(&self) -> Vec {\n (0..6)\n .into_iter()\n .filter(|&i| self.pits[i] != 0)\n .collect::>()\n }\n}\n\n#[derive(Copy, Clone, PartialEq, Debug)]\nenum GameMode {\n WhiteTurn,\n BlackTurn,\n GameOver,\n}\n\n#[derive(Copy, Clone, PartialEq, Debug)]\nstruct GameState {\n mode: GameMode,\n white: Player,\n black: Player,\n}\n\nstruct GameSkeuomorph {\n b: [i8; 8],\n w: [i8; 8],\n}\n\nimpl fmt::Display for GameState {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(\n f,\n \" |{: >2}|{: >2}|{: >2}|{: >2}|{: >2}|{: >2}| \n{: >2} |--{}--| {}\n |{: >2}|{: >2}|{: >2}|{: >2}|{: >2}|{: >2}| \n\",\n // Top Row: Black Pits (reverse order)\n self.black.pits[5],\n self.black.pits[4],\n self.black.pits[3],\n self.black.pits[2],\n self.black.pits[1],\n self.black.pits[0],\n // Middle Row: Score and Status\n self.black.score,\n match self.mode {\n GameMode::WhiteTurn => \"WHITE TO MOVE\",\n GameMode::BlackTurn => \"BLACK TO MOVE\",\n GameMode::GameOver => \"--GAME OVER--\",\n },\n self.white.score,\n // Bottom Row: White Pits\n self.white.pits[0],\n self.white.pits[1],\n self.white.pits[2],\n self.white.pits[3],\n self.white.pits[4],\n self.white.pits[5],\n )\n }\n}\n\nimpl GameState {\n fn get_valid_moves(&self) -> Vec {\n match self.mode {\n GameMode::WhiteTurn => self.white.get_moves(),\n GameMode::BlackTurn => self.black.get_moves(),\n GameMode::GameOver => vec![],\n }\n }\n\n fn from(s: GameSkeuomorph) -> GameState {\n GameState {\n mode: if s.b[7] == 0 {\n if s.w[0] == 0 {\n GameMode::GameOver\n } else {\n GameMode::WhiteTurn\n }\n } else {\n GameMode::BlackTurn\n },\n white: Player {\n pits: [s.w[1], s.w[2], s.w[3], s.w[4], s.w[5], s.w[6]],\n score: s.w[7],\n },\n black: Player {\n pits: [s.b[6], s.b[5], s.b[4], s.b[3], s.b[2], s.b[1]],\n score: s.b[0],\n },\n }\n }\n\n fn new() -> GameState {\n GameState::from(GameSkeuomorph {\n b: [0, 4, 4, 4, 4, 4, 4, 0],\n w: [1, 4, 4, 4, 4, 4, 4, 0],\n })\n }\n\n fn get_next_state(&self, pit_index: usize) -> GameState {\n // Ignore moves after Game Over\n if self.mode == GameMode::GameOver {\n return GameState { ..*self };\n }\n\n // Set up active/inactive semantics\n let (mut active_player, mut inactive_player) = match self.mode {\n GameMode::WhiteTurn => (self.white, self.black),\n _ => (self.black, self.white),\n };\n\n let mut last_stone_was_score = false;\n let mut stones_to_move = active_player.pits[pit_index];\n let mut pit_pointer = pit_index;\n const MAX_PIT_INDEX: usize = 5;\n active_player.pits[pit_pointer] = 0;\n pit_pointer += 1;\n\n while stones_to_move > 0 {\n // Active Pits\n while stones_to_move > 0 && pit_pointer <= MAX_PIT_INDEX {\n stones_to_move -= 1;\n // Detect Steal\n let is_last_stone = stones_to_move == 0;\n let last_pit_is_empty = active_player.pits[pit_pointer] == 0;\n if is_last_stone && last_pit_is_empty {\n let opposite_pit = 5 - pit_pointer;\n let stolen_stones = inactive_player.pits[opposite_pit];\n inactive_player.pits[opposite_pit] = 0;\n active_player.score += stolen_stones + 1;\n } else {\n active_player.pits[pit_pointer] += 1;\n pit_pointer += 1;\n }\n }\n\n // Active Scoring Pit\n if stones_to_move > 0 {\n stones_to_move -= 1;\n let is_last_stone = stones_to_move == 0;\n if is_last_stone {\n last_stone_was_score = true;\n }\n active_player.score += 1;\n pit_pointer = 0;\n }\n\n // Inactive Pits\n while stones_to_move > 0 && pit_pointer <= MAX_PIT_INDEX {\n stones_to_move -= 1;\n inactive_player.pits[pit_pointer] += 1;\n pit_pointer += 1;\n }\n pit_pointer = 0;\n }\n\n // Undo active/inactive semantics\n let (white, black) = match self.mode {\n GameMode::WhiteTurn => (active_player, inactive_player),\n _ => (inactive_player, active_player),\n };\n\n let is_game_over = true\n && active_player.pits[0] == 0\n && active_player.pits[1] == 0\n && active_player.pits[2] == 0\n && active_player.pits[3] == 0\n && active_player.pits[4] == 0\n && active_player.pits[5] == 0;\n\n let mode = if is_game_over {\n GameMode::GameOver\n } else {\n if last_stone_was_score {\n self.mode\n } else {\n if self.mode == GameMode::WhiteTurn {\n GameMode::BlackTurn\n } else {\n GameMode::WhiteTurn\n }\n }\n };\n\n return GameState { mode, white, black };\n }\n}\n\n#[test]\nfn game_over_is_permanent() {\n let game_over = GameState::from(GameSkeuomorph {\n b: [0, 4, 4, 4, 4, 4, 4, 0],\n w: [0, 4, 4, 4, 4, 4, 4, 0],\n });\n\n assert_eq!(game_over.get_next_state(0), game_over);\n}\n\n#[test]\nfn white_basic_move() {\n assert_eq!(\n GameState::new().get_next_state(0),\n GameState::from(GameSkeuomorph {\n b: [0, 4, 4, 4, 4, 4, 4, 1],\n w: [0, 0, 5, 5, 5, 5, 4, 0],\n })\n );\n}\n\n#[test]\nfn black_basic_move() {\n assert_eq!(\n GameState::new().get_next_state(0).get_next_state(0),\n GameState::from(GameSkeuomorph {\n b: [0, 4, 5, 5, 5, 5, 0, 0],\n w: [1, 0, 5, 5, 5, 5, 4, 0],\n })\n );\n}\n\n#[test]\nfn white_overflow_move() {\n assert_eq!(\n GameState::new().get_next_state(5),\n GameState::from(GameSkeuomorph {\n b: [0, 4, 4, 4, 5, 5, 5, 1],\n w: [0, 4, 4, 4, 4, 4, 0, 1],\n })\n );\n}\n\n#[test]\nfn black_overflow_move() {\n assert_eq!(\n GameState::from(GameSkeuomorph {\n b: [0, 4, 4, 4, 5, 5, 5, 1],\n w: [0, 4, 4, 4, 4, 4, 0, 1],\n }).get_next_state(5),\n GameState::from(GameSkeuomorph {\n b: [1, 0, 4, 4, 5, 5, 5, 0],\n w: [1, 5, 5, 5, 4, 4, 0, 1],\n })\n );\n}\n\n#[test]\nfn white_free_turn() {\n assert_eq!(\n GameState::new().get_next_state(2),\n GameState::from(GameSkeuomorph {\n b: [0, 4, 4, 4, 4, 4, 4, 0],\n w: [1, 4, 4, 0, 5, 5, 5, 1],\n })\n );\n}\n\n#[test]\nfn black_free_turn() {\n assert_eq!(\n GameState::new().get_next_state(0).get_next_state(2),\n GameState::from(GameSkeuomorph {\n b: [1, 5, 5, 5, 0, 4, 4, 1],\n w: [0, 0, 5, 5, 5, 5, 4, 0],\n })\n );\n}\n\n#[test]\nfn white_long_wrap() {\n assert_eq!(\n GameState::from(GameSkeuomorph {\n b: [0, 0, 0, 0, 0, 0, 0, 0],\n w: [1, 0, 0, 0, 0, 0, 48, 0],\n }).get_next_state(5),\n GameState::from(GameSkeuomorph {\n b: [0, 4, 4, 4, 4, 4, 4, 1],\n w: [0, 4, 4, 3, 3, 3, 3, 4],\n })\n );\n}\n\n#[test]\nfn black_long_wrap() {\n assert_eq!(\n GameState::from(GameSkeuomorph {\n b: [0, 48, 0, 0, 0, 0, 0, 1],\n w: [0, 0, 0, 0, 0, 0, 0, 0],\n }).get_next_state(5),\n GameState::from(GameSkeuomorph {\n b: [4, 3, 3, 3, 3, 4, 4, 0],\n w: [1, 4, 4, 4, 4, 4, 4, 0],\n })\n );\n}\n\n#[test]\nfn white_steal() {\n assert_eq!(\n GameState::from(GameSkeuomorph {\n b: [0, 4, 4, 4, 4, 4, 4, 0],\n w: [1, 8, 4, 4, 4, 4, 0, 0],\n }).get_next_state(1),\n GameState::from(GameSkeuomorph {\n b: [0, 4, 4, 4, 4, 4, 0, 1],\n w: [0, 8, 0, 5, 5, 5, 0, 5],\n })\n );\n}\n\n#[test]\nfn black_steal() {\n assert_eq!(\n GameState::from(GameSkeuomorph {\n b: [0, 0, 4, 4, 4, 4, 8, 1],\n w: [0, 4, 4, 4, 4, 4, 4, 0],\n }).get_next_state(1),\n GameState::from(GameSkeuomorph {\n b: [5, 0, 5, 5, 5, 0, 8, 0],\n w: [1, 0, 4, 4, 4, 4, 4, 0],\n })\n );\n}\n\n#[test]\nfn game_over_if_white_empty() {\n assert_eq!(\n GameState::from(GameSkeuomorph {\n b: [0, 8, 8, 8, 8, 8, 6, 0],\n w: [1, 0, 0, 0, 0, 0, 2, 0],\n }).get_next_state(5),\n GameState::from(GameSkeuomorph {\n b: [0, 8, 8, 8, 8, 8, 7, 0],\n w: [0, 0, 0, 0, 0, 0, 0, 1],\n })\n );\n}\n\n#[test]\nfn game_over_if_black_empty() {\n assert_eq!(\n GameState::from(GameSkeuomorph {\n b: [0, 2, 0, 0, 0, 0, 0, 1],\n w: [0, 6, 8, 8, 8, 8, 8, 0],\n }).get_next_state(5),\n GameState::from(GameSkeuomorph {\n b: [1, 0, 0, 0, 0, 0, 0, 0],\n w: [0, 7, 8, 8, 8, 8, 8, 0],\n })\n );\n}\n\nfn main() {}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":176,"cells":{"blob_id":{"kind":"string","value":"ca8df953a610e9ef5696a063e7b52596cd83288f"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"blackjack/algorithms_pt1"},"path":{"kind":"string","value":"/rust/week01_quickmerge/src/percolation.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3263,"string":"3,263"},"score":{"kind":"number","value":3.3125,"string":"3.3125"},"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::fmt::{Display, Formatter, Error};\nuse quickmerge::QuickMerge;\n\n#[allow(dead_code)]\npub struct Percolation {\n x: usize,\n y: usize,\n pub last: usize,\n data: QuickMerge,\n}\n\n\nimpl Percolation {\n pub fn new(x: usize, y: usize) -> Percolation {\n let mut p = Percolation {\n x: x,\n y: y,\n last: x * y + 1,\n data: QuickMerge::new(x * y + 2),\n };\n\n for i in p.data.id.iter_mut() {\n *i = x * y + 2;\n }\n p.data.id[0] = 0;\n p.data.id[p.last] = p.last;\n p\n }\n\n pub fn index(&self, row: usize, column: usize) -> usize {\n if row == 0 {\n return 0;\n }\n if row > self.y {\n return self.last;\n }\n\n self.y * (row - 1) + column\n }\n\n\n pub fn open(&mut self, row: usize, column: usize) {\n let index = self.index(row, column);\n\n if !self.is_open(row, column) {\n self.data.id[index] = index;\n }\n\n\n let neighbors =\n [(row + 1, column), (row - 1, column), (row, column + 1), (row, column - 1)];\n\n let x = self.x;\n\n for &(nrow, ncol) in neighbors.iter()\n .filter(|c| c.1 > 0 && c.1 <= x) {\n\n if self.is_open(nrow, ncol) {\n let neighbor = self.index(nrow, ncol);\n self.data.union(index, neighbor);\n }\n\n }\n\n }\n\n pub fn is_open(&self, row: usize, column: usize) -> bool {\n let index = self.index(row, column);\n self.data.id[index] <= self.last\n }\n\n pub fn is_full(&mut self, row: usize, column: usize) -> bool {\n let index = self.index(row, column);\n self.data.connected(index, 0)\n }\n\n pub fn number_of_open_sites(&self) -> usize {\n let max = self.last;\n let id = &self.data.id[1..max];\n id.iter().filter(|&&i| i < max).count()\n }\n\n pub fn percolates(&mut self) -> bool {\n let row = self.y + 1;\n self.is_full(row, 1)\n }\n}\n\nimpl Display for Percolation {\n fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {\n\n write!(f, \"{}\\n\", self.data.id[0])?;\n\n let print = |row, column| {\n if self.is_open(row, column) {\n let index = self.index(row, column);\n self.data.id[index].to_string()\n } else {\n \"X\".to_string()\n }\n };\n for row in 1..self.x + 1 {\n for column in 1..self.y + 1 {\n write!(f, \"{}\", print(row, column))?;\n }\n write!(f, \"\\n\")?;\n }\n write!(f, \"{}\\n\", print(self.y + 1, self.x))\n }\n}\n\n\n#[test]\nfn test_open() {\n let mut p = Percolation::new(3, 3);\n p.open(1, 3);\n p.open(2, 2);\n p.open(2, 3);\n p.open(3, 3);\n assert!(p.is_open(4, 3));\n assert!(p.is_open(4, 1));\n}\n\n#[test]\nfn test_count() {\n let mut p = Percolation::new(3, 3);\n p.open(1, 3);\n p.open(2, 2);\n p.open(2, 3);\n p.open(3, 3);\n assert_eq!(4, p.number_of_open_sites());\n}\n\n#[test]\nfn test_percolates() {\n let mut p = Percolation::new(3, 3);\n p.open(1, 1);\n p.open(2, 1);\n p.open(2, 2);\n p.open(2, 3);\n assert!(!p.percolates());\n p.open(3, 3);\n assert!(p.percolates());\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":177,"cells":{"blob_id":{"kind":"string","value":"fe45abe02d8c82057cab67c3d57a52c0db4ac9a4"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"KaiseiYokoyama/iiif_awesome_sample_viewer"},"path":{"kind":"string","value":"/src/iif_manifest.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1711,"string":"1,711"},"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":"#[derive(Deserialize, Debug, Serialize)]\npub struct Manifest {\n #[serde(rename = \"@context\")]\n context: String,\n #[serde(rename = \"@id\")]\n id: String,\n #[serde(rename = \"@type\")]\n type_: String,\n license: String,\n attribution: String,\n description: String,\n label: String,\n sequences: Vec,\n}\n\nimpl Manifest {\n pub fn get_images(&self) -> Vec {\n let mut images = Vec::new();\n\n for sequence in &self.sequences {\n for canvas in &sequence.canvases {\n for image in &canvas.images {\n images.push(image.resource.id.clone());\n }\n }\n }\n\n return images;\n }\n}\n\n#[derive(Deserialize, Debug, Serialize)]\nstruct Sequence {\n #[serde(rename = \"@id\")]\n id: String,\n #[serde(rename = \"@type\")]\n type_: String,\n canvases: Vec,\n}\n\n#[derive(Deserialize, Debug, Serialize)]\nstruct Canvas {\n #[serde(rename = \"@id\")]\n id: String,\n #[serde(rename = \"@type\")]\n type_: String,\n width: u32,\n height: u32,\n label: String,\n images: Vec,\n}\n\n#[derive(Deserialize, Debug, Serialize)]\nstruct Image {\n #[serde(rename = \"@id\")]\n id: String,\n #[serde(rename = \"@type\")]\n type_: String,\n resource: Resource,\n}\n\n#[derive(Deserialize, Debug, Serialize)]\nstruct Resource {\n #[serde(rename = \"@id\")]\n id: String,\n #[serde(rename = \"@type\")]\n type_: String,\n format: String,\n width: u32,\n height: u32,\n service: Service,\n}\n\n#[derive(Deserialize, Debug, Serialize)]\nstruct Service {\n #[serde(rename = \"@context\")]\n context: String,\n #[serde(rename = \"@id\")]\n id: String,\n profile: String,\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":178,"cells":{"blob_id":{"kind":"string","value":"157578cc19a1950de93f8033afdf0c4e222d9af6"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"KallDrexx/r8"},"path":{"kind":"string","value":"/r8-core/src/execution.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":51703,"string":"51,703"},"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":"use custom_error::custom_error;\nuse crate::{Hardware, Instruction, Register};\nuse crate::hardware::{STACK_SIZE, MEMORY_SIZE, FRAMEBUFFER_HEIGHT, FRAMEBUFFER_WIDTH};\n\ncustom_error!{pub ExecutionError\n InvalidRegisterForInstruction {instruction:Instruction} = \"Invalid register was used for instruction: {instruction}\",\n UnhandleableInstruction {instruction:Instruction} = \"The instruction '{instruction}' is not known\",\n StackOverflow = \"Call exceeded maximum stack size\",\n InvalidCallOrJumpAddress {address:u16} = \"Call performed to invalid address {address}\",\n EmptyStack = \"Return was called with an empty stack\",\n InvalidFontDigit {digit: u8} = \"Font digit of {digit} is invalid, only 0-f is allowed\",\n}\n\npub fn execute_instruction(instruction: Instruction, hardware: &mut Hardware) -> Result<(), ExecutionError> {\n match instruction {\n Instruction::AddFromRegister {register1: Register::General(reg1_num), register2: Register::General(reg2_num)} => {\n let reg1_value = hardware.gen_registers[reg1_num as usize];\n let reg2_value = hardware.gen_registers[reg2_num as usize];\n let will_wrap = reg1_value > 0 && std::u8::MAX - reg1_value < reg2_value;;\n\n hardware.gen_registers[reg1_num as usize] = reg1_value.wrapping_add(reg2_value);\n hardware.gen_registers[0xf] = if will_wrap { 1 } else { 0};\n hardware.program_counter += 2;\n }\n\n Instruction::AddFromRegister {register1: Register::I, register2: Register::General(reg2_num)} => {\n hardware.i_register = hardware.i_register.wrapping_add(hardware.gen_registers[reg2_num as usize] as u16);\n hardware.program_counter += 2;\n }\n\n Instruction::AddFromValue {register: Register::General(reg_num), value} => {\n hardware.gen_registers[reg_num as usize] = hardware.gen_registers[reg_num as usize].wrapping_add(value);\n hardware.program_counter += 2;\n }\n\n Instruction::And {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => {\n hardware.gen_registers[reg_num1 as usize] = hardware.gen_registers[reg_num1 as usize] & hardware.gen_registers[reg_num2 as usize];\n hardware.program_counter += 2;\n }\n\n Instruction::Call {address} => {\n if hardware.stack_pointer >= STACK_SIZE {\n return Err(ExecutionError::StackOverflow);\n }\n\n hardware.stack[hardware.stack_pointer] = hardware.program_counter;\n hardware.stack_pointer = hardware.stack_pointer + 1;\n hardware.program_counter = address;\n }\n\n Instruction::ClearDisplay => {\n for x in 0..hardware.framebuffer.len() {\n for y in 0..hardware.framebuffer[x].len() {\n hardware.framebuffer[x][y] = 0;\n }\n }\n\n hardware.program_counter += 2;\n }\n\n Instruction::DrawSprite {x_register: Register::General(x_reg_num), y_register: Register::General(y_reg_num), height} => {\n let first_row = hardware.gen_registers[y_reg_num as usize] as usize;\n let first_pixel = hardware.gen_registers[x_reg_num as usize] as usize;\n let shift_amount = first_pixel % 8;\n\n let left_column_set = first_pixel / 8;\n\n // According to the Cowgod spec, if the right column set would be out of bounds it\n // wraps to the other side on the same row\n let right_column_set = (left_column_set + 1) % (FRAMEBUFFER_WIDTH / 8);\n\n let mut collisions_found = false;\n for x in 0..height as usize {\n let sprite_byte = hardware.memory[hardware.i_register as usize + x];\n let left_byte = sprite_byte >> shift_amount;\n\n // According to Cowgod spec, if we've gone past the screen in height then wrap to the top\n let row = (first_row + x) % FRAMEBUFFER_HEIGHT;\n\n // Detect if the xor will reset any already on pixels\n if hardware.framebuffer[row][left_column_set] & left_byte > 0 {\n collisions_found = true;\n }\n\n // Update framebuffer\n hardware.framebuffer[row][left_column_set] ^= left_byte;\n\n // If we are affecting pixels across column set boundaries, repeat for the next byte\n if shift_amount > 0 {\n let right_byte = sprite_byte << 8 - shift_amount;\n\n if hardware.framebuffer[row][right_column_set] & right_byte > 0 {\n collisions_found = true;\n }\n\n hardware.framebuffer[row][right_column_set] ^= right_byte;\n }\n }\n\n hardware.program_counter += 2;\n hardware.gen_registers[0xf] = if collisions_found { 1 } else { 0 };\n }\n\n Instruction::JumpToAddress {address, add_register_0} => {\n let final_address = match add_register_0 {\n true => address + hardware.gen_registers[0] as u16,\n false => address\n };\n\n if final_address < 512 || final_address > MEMORY_SIZE as u16 {\n return Err(ExecutionError::InvalidCallOrJumpAddress {address: final_address});\n }\n\n hardware.program_counter = final_address;\n }\n\n Instruction::LoadAddressIntoIRegister {address} => {\n hardware.i_register = address;\n hardware.program_counter += 2;\n }\n\n Instruction::LoadBcdValue {source: Register::General(reg_num)} => {\n let start_address = hardware.i_register as usize;\n let source_value = hardware.gen_registers[reg_num as usize];\n\n hardware.memory[start_address] = (source_value / 100) % 10;\n hardware.memory[start_address + 1] = (source_value / 10) % 10;\n hardware.memory[start_address + 2] = source_value % 10;\n hardware.program_counter += 2;\n }\n\n Instruction::LoadFromKeyPress {destination: Register::General(reg_num)} => {\n // According to specs I have found this instruction does not recognize a key if it's\n // currently down. So it will wait (stay on the same program counter for our purposes)\n // until the user releases the key, at which point for one execution\n // `hardware.key_released_since_last_instruction` should have the key that was just released.\n\n if let Some(key_num) = hardware.key_released_since_last_instruction {\n hardware.gen_registers[reg_num as usize] = key_num;\n hardware.program_counter += 2;\n }\n }\n\n Instruction::LoadFromMemory {last_register: Register::General(reg_num)} => {\n for index in 0..=reg_num {\n hardware.gen_registers[index as usize] = hardware.memory[hardware.i_register as usize + index as usize];\n }\n\n hardware.i_register = hardware.i_register + reg_num as u16 + 1;\n hardware.program_counter += 2;\n }\n\n Instruction::LoadFromRegister {destination, source} => {\n let source_value = match source {\n Register::General(num) => hardware.gen_registers[num as usize],\n Register::SoundTimer => hardware.sound_timer,\n Register::DelayTimer => hardware.delay_timer,\n _ => return Err(ExecutionError::InvalidRegisterForInstruction {instruction: Instruction::LoadFromRegister {destination, source}}),\n };\n\n match destination {\n Register::General(num) => hardware.gen_registers[num as usize] = source_value,\n Register::SoundTimer => hardware.sound_timer = source_value,\n Register::DelayTimer => hardware.delay_timer = source_value,\n _ => return Err(ExecutionError::InvalidRegisterForInstruction {instruction: Instruction::LoadFromRegister {destination, source}}),\n }\n\n hardware.program_counter += 2;\n }\n\n Instruction::LoadFromValue {destination: Register::General(reg_num), value} => {\n hardware.gen_registers[reg_num as usize] = value;\n hardware.program_counter += 2;\n }\n\n Instruction::LoadIntoMemory {last_register: Register::General(reg_num)} => {\n for index in 0..=reg_num {\n hardware.memory[hardware.i_register as usize + index as usize] = hardware.gen_registers[index as usize];\n }\n\n hardware.i_register = hardware.i_register + reg_num as u16 + 1;\n hardware.program_counter += 2;\n }\n\n Instruction::LoadSpriteLocation {sprite_digit: Register::General(reg_num)} => {\n let digit = hardware.gen_registers[reg_num as usize];\n if digit > 0xf {\n return Err(ExecutionError::InvalidFontDigit {digit});\n }\n\n hardware.i_register = hardware.font_addresses[&digit];\n hardware.program_counter += 2;\n }\n\n Instruction::Or {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => {\n hardware.gen_registers[reg_num1 as usize] = hardware.gen_registers[reg_num1 as usize] | hardware.gen_registers[reg_num2 as usize];\n hardware.program_counter += 2;\n }\n\n Instruction::Return => {\n if hardware.stack_pointer == 0 {\n return Err(ExecutionError::EmptyStack);\n }\n\n hardware.program_counter = hardware.stack[hardware.stack_pointer - 1] + 2;\n hardware.stack_pointer = hardware.stack_pointer - 1;\n }\n\n Instruction::SetRandom {register: Register::General(reg_num), and_value} => {\n hardware.gen_registers[reg_num as usize] = rand::random::() & and_value;\n hardware.program_counter += 2;\n }\n\n Instruction::ShiftLeft {register: Register::General(reg_num)} => {\n hardware.gen_registers[reg_num as usize] = hardware.gen_registers[reg_num as usize] << 1;\n hardware.program_counter += 2;\n }\n\n Instruction::ShiftRight {register: Register::General(reg_num)} => {\n hardware.gen_registers[reg_num as usize] = hardware.gen_registers[reg_num as usize] >> 1;\n hardware.program_counter += 2;\n }\n\n Instruction::SkipIfEqual {register: Register::General(reg_num), value} => {\n let increment = match hardware.gen_registers[reg_num as usize] == value {\n true => 4,\n false => 2,\n };\n\n hardware.program_counter += increment;\n }\n\n Instruction::SkipIfKeyPressed {register: Register::General(reg_num)} => {\n let increment = match hardware.current_key_down {\n Some(x) if x == hardware.gen_registers[reg_num as usize] => 4,\n _ => 2,\n };\n\n hardware.program_counter += increment;\n }\n\n Instruction::SkipIfKeyNotPressed {register: Register::General(reg_num)} => {\n let increment = match hardware.current_key_down {\n Some(x) if x == hardware.gen_registers[reg_num as usize] => 2,\n _ => 4,\n };\n\n hardware.program_counter += increment;\n }\n\n Instruction::SkipIfNotEqual {register: Register::General(reg_num), value} => {\n let increment = match hardware.gen_registers[reg_num as usize] == value {\n true => 2,\n false => 4,\n };\n\n hardware.program_counter += increment;\n }\n\n Instruction::SkipIfRegistersEqual {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => {\n let increment = match hardware.gen_registers[reg_num1 as usize] == hardware.gen_registers[reg_num2 as usize] {\n true => 4,\n false => 2,\n };\n\n hardware.program_counter += increment;\n }\n\n Instruction::SkipIfRegistersNotEqual {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => {\n let increment = match hardware.gen_registers[reg_num1 as usize] == hardware.gen_registers[reg_num2 as usize] {\n true => 2,\n false => 4,\n };\n\n hardware.program_counter += increment;\n }\n\n Instruction::Subtract {minuend: Register::General(minuend_reg), subtrahend: Register::General(subtrahend_reg), stored_in: Register::General(stored_in_reg)} => {\n let will_underflow = hardware.gen_registers[minuend_reg as usize] < hardware.gen_registers[subtrahend_reg as usize];\n let difference = hardware.gen_registers[minuend_reg as usize].wrapping_sub(hardware.gen_registers[subtrahend_reg as usize]);\n hardware.gen_registers[stored_in_reg as usize] = difference;\n hardware.gen_registers[0xf] = if will_underflow { 0 } else { 1 };\n hardware.program_counter += 2;\n }\n\n Instruction::Xor {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => {\n hardware.gen_registers[reg_num1 as usize] = hardware.gen_registers[reg_num1 as usize] ^ hardware.gen_registers[reg_num2 as usize];\n hardware.program_counter += 2;\n }\n\n _ => return Err(ExecutionError::UnhandleableInstruction{instruction})\n }\n\n Ok(())\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use ::{Hardware, Register};\n\n #[test]\n fn can_add_value_to_general_register() {\n const REGISTER_NUMBER: u8 = 3;\n let mut hardware = Hardware::new();\n hardware.gen_registers[REGISTER_NUMBER as usize] = 100;\n hardware.program_counter = 1000;\n\n let instruction = Instruction::AddFromValue {\n register: Register::General(REGISTER_NUMBER),\n value: 12,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.gen_registers[REGISTER_NUMBER as usize], 112, \"Invalid register value\");\n assert_eq!(hardware.program_counter, 1002, \"Invalid resulting program counter\");\n }\n\n #[test]\n fn can_add_value_to_general_register_that_overflows() {\n const REGISTER_NUMBER: u8 = 3;\n let mut hardware = Hardware::new();\n hardware.gen_registers[REGISTER_NUMBER as usize] = 100;\n hardware.program_counter = 1000;\n\n let instruction = Instruction::AddFromValue {\n register: Register::General(REGISTER_NUMBER),\n value: 165,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.gen_registers[REGISTER_NUMBER as usize], 9, \"Invalid register value\");\n assert_eq!(hardware.program_counter, 1002, \"Invalid resulting program counter\");\n assert_eq!(hardware.gen_registers[0xf], 0, \"Add by value should not have caused carry mark\");\n }\n\n #[test]\n fn can_add_value_from_general_register_without_carry() {\n const REGISTER1_NUMBER: u8 = 4;\n const REGISTER2_NUMBER: u8 = 6;\n let mut hardware = Hardware::new();\n hardware.gen_registers[REGISTER1_NUMBER as usize] = 100;\n hardware.gen_registers[REGISTER2_NUMBER as usize] = 55;\n hardware.program_counter = 1000;\n\n let instruction = Instruction::AddFromRegister {\n register1: Register::General(REGISTER1_NUMBER),\n register2: Register::General(REGISTER2_NUMBER),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.gen_registers[REGISTER1_NUMBER as usize], 155, \"Invalid register value\");\n assert_eq!(hardware.gen_registers[0xf], 0, \"Invalid VF register value\");\n assert_eq!(hardware.program_counter, 1002, \"Invalid resulting program counter\");\n }\n\n #[test]\n fn can_add_value_from_general_register_with_carry() {\n const REGISTER1_NUMBER: u8 = 4;\n const REGISTER2_NUMBER: u8 = 6;\n let mut hardware = Hardware::new();\n hardware.gen_registers[REGISTER1_NUMBER as usize] = 200;\n hardware.gen_registers[REGISTER2_NUMBER as usize] = 65;\n hardware.program_counter = 1000;\n\n let instruction = Instruction::AddFromRegister {\n register1: Register::General(REGISTER1_NUMBER),\n register2: Register::General(REGISTER2_NUMBER),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.gen_registers[REGISTER1_NUMBER as usize], 9, \"Invalid register value\");\n assert_eq!(hardware.gen_registers[0xf], 1, \"Invalid VF register value\");\n assert_eq!(hardware.program_counter, 1002, \"Invalid resulting program counter\");\n }\n\n #[test]\n fn can_add_value_from_general_register_to_i_register() {\n let mut hardware = Hardware::new();\n hardware.i_register = 100;\n hardware.gen_registers[3] = 12;\n hardware.program_counter = 1000;\n\n let instruction = Instruction::AddFromRegister {\n register1: Register::I,\n register2: Register::General(3),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.i_register, 112, \"Invalid register value\");\n assert_eq!(hardware.program_counter, 1002, \"Invalid resulting program counter\");\n }\n\n #[test]\n fn can_execute_call_instruction() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.stack[0] = 567;\n hardware.stack[1] = 599;\n hardware.stack_pointer = 2;\n\n let instruction = Instruction::Call {address: 1654};\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.stack_pointer, 3, \"Incorrect stack pointer\");\n assert_eq!(hardware.stack[0], 567, \"Incorrect address at stack 0\");\n assert_eq!(hardware.stack[1], 599, \"Incorrect address at stack 1\");\n assert_eq!(hardware.stack[2], 1000, \"Incorrect address at stack 2\");\n assert_eq!(hardware.program_counter, 1654, \"Incorrect program counter value\");\n }\n\n #[test]\n fn stack_overflow_error_when_call_performed_at_max_stack() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.stack_pointer = 16;\n\n let instruction = Instruction::Call {address: 1654};\n match execute_instruction(instruction, &mut hardware).unwrap_err() {\n ExecutionError::StackOverflow => (),\n x => panic!(\"Expected StackOverflow, instead got {:?}\", x),\n }\n }\n\n #[test]\n fn can_call_jump_to_address_without_add() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1002;\n hardware.gen_registers[0] = 10;\n hardware.stack_pointer = 1;\n hardware.stack[0] = 533;\n\n let instruction = Instruction::JumpToAddress {address: 2330, add_register_0: false};\n execute_instruction(instruction, &mut hardware).unwrap();\n\n assert_eq!(hardware.program_counter, 2330, \"Incorrect program counter value\");\n assert_eq!(hardware.stack_pointer, 1, \"Incorrect stack pointer value\"); // Make sure stack wasn't messed with\n assert_eq!(hardware.stack[0], 533, \"Incorrect stack[0] value\");\n }\n\n #[test]\n fn can_call_jump_address_with_add() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1002;\n hardware.gen_registers[0] = 10;\n hardware.stack_pointer = 1;\n hardware.stack[0] = 533;\n\n let instruction = Instruction::JumpToAddress {address: 2330, add_register_0: true};\n execute_instruction(instruction, &mut hardware).unwrap();\n\n assert_eq!(hardware.program_counter, 2340, \"Incorrect program counter value\");\n assert_eq!(hardware.stack_pointer, 1, \"Incorrect stack pointer value\"); // Make sure stack wasn't messed with\n assert_eq!(hardware.stack[0], 533, \"Incorrect stack[0] value\");\n }\n\n #[test]\n fn cannot_jump_to_address_below_512() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1002;\n hardware.gen_registers[0] = 10;\n hardware.stack_pointer = 1;\n hardware.stack[0] = 533;\n\n let instruction = Instruction::JumpToAddress {address: 511, add_register_0: false};\n match execute_instruction(instruction, &mut hardware).unwrap_err() {\n ExecutionError::InvalidCallOrJumpAddress {address: 511} => (),\n x => panic!(\"Expected InvalidCallOrJumpAddress {{address: 2331}}, instead got {:?}\", x),\n }\n }\n\n #[test]\n fn cannot_jump_to_address_above_memory_size() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1002;\n hardware.gen_registers[0] = 10;\n hardware.stack_pointer = 1;\n hardware.stack[0] = 533;\n\n let address = MEMORY_SIZE as u16 + 1;\n let instruction = Instruction::JumpToAddress {address, add_register_0: false};\n match execute_instruction(instruction, &mut hardware).unwrap_err() {\n ExecutionError::InvalidCallOrJumpAddress {address: _} => (),\n x => panic!(\"Expected InvalidCallOrJumpAddress {{address: {}}}, instead got {:?}\", address, x),\n }\n }\n\n #[test]\n fn jump_to_machine_code_is_unhandled() {\n // According to specs, SYS instructions are ignored by modern interpreters.\n\n let mut hardware = Hardware::new();\n let instruction = Instruction::JumpToMachineCode {address: 123};\n match execute_instruction(instruction, &mut hardware).unwrap_err() {\n ExecutionError::UnhandleableInstruction {instruction: _} => (),\n x => panic!(\"Expected UnhandleableInstruction, instead got {:?}\", x),\n }\n }\n\n #[test]\n fn can_load_from_value_into_general_register() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[4] = 10;\n\n let instruction = Instruction::LoadFromValue {\n destination: Register::General(4),\n value: 123,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.gen_registers[4], 123, \"Incorrect value in register\");\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n }\n\n #[test]\n fn can_load_from_register_into_general_register() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[4] = 10;\n hardware.gen_registers[5] = 122;\n\n let instruction = Instruction::LoadFromRegister {\n destination: Register::General(4),\n source: Register::General(5),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.gen_registers[4], 122, \"Incorrect value in register\");\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n }\n\n #[test]\n fn load_from_key_press_does_not_progress_if_no_key_released() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[4] = 10;\n hardware.current_key_down = Some(0x4);\n hardware.key_released_since_last_instruction = None;\n\n let instruction = Instruction::LoadFromKeyPress {destination: Register::General(4)};\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1000, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[4], 10, \"Register 4 value should not have changed\");\n }\n\n #[test]\n fn load_from_key_press_proceeds_if_key_was_released() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[4] = 10;\n hardware.current_key_down = None;\n hardware.key_released_since_last_instruction = Some(0x5);\n\n let instruction = Instruction::LoadFromKeyPress {destination: Register::General(4)};\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[4], 5, \"Incorrect value in register\");\n }\n\n #[test]\n fn can_load_bcd_value_into_memory() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[5] = 235;\n hardware.i_register = 1500;\n\n let instruction = Instruction::LoadBcdValue {source: Register::General(5)};\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.memory[1500], 2, \"Incorrect bcd value #1\");\n assert_eq!(hardware.memory[1501], 3, \"Incorrect bcd value #2\");\n assert_eq!(hardware.memory[1502], 5, \"Incorrect bcd value #3\");\n }\n\n #[test]\n fn can_load_register_values_into_memory() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[0] = 100;\n hardware.gen_registers[1] = 101;\n hardware.gen_registers[2] = 102;\n hardware.gen_registers[3] = 103;\n hardware.gen_registers[4] = 104;\n hardware.gen_registers[5] = 105;\n hardware.i_register = 933;\n\n let instruction = Instruction::LoadIntoMemory {last_register: Register::General(4)};\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.memory[933], 100, \"Incorrect value in memory location 0\");\n assert_eq!(hardware.memory[934], 101, \"Incorrect value in memory location 1\");\n assert_eq!(hardware.memory[935], 102, \"Incorrect value in memory location 2\");\n assert_eq!(hardware.memory[936], 103, \"Incorrect value in memory location 3\");\n assert_eq!(hardware.memory[937], 104, \"Incorrect value in memory location 4\");\n assert_eq!(hardware.memory[938], 0, \"Incorrect value in memory location 5\");\n assert_eq!(hardware.i_register, 938, \"Incorrect resulting I register\");\n }\n\n #[test]\n fn can_load_memory_into_multiple_register_values() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.i_register = 933;\n hardware.memory[933] = 100;\n hardware.memory[934] = 101;\n hardware.memory[935] = 102;\n hardware.memory[936] = 103;\n hardware.memory[937] = 104;\n hardware.memory[938] = 105;\n\n let instruction = Instruction::LoadFromMemory {last_register: Register::General(4)};\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[0], 100, \"Incorrect value in register V0\");\n assert_eq!(hardware.gen_registers[1], 101, \"Incorrect value in register V1\");\n assert_eq!(hardware.gen_registers[2], 102, \"Incorrect value in register V2\");\n assert_eq!(hardware.gen_registers[3], 103, \"Incorrect value in register V3\");\n assert_eq!(hardware.gen_registers[4], 104, \"Incorrect value in register V4\");\n assert_eq!(hardware.gen_registers[5], 0, \"Incorrect value in register V5\");\n assert_eq!(hardware.i_register, 938, \"Incorrect resulting I register\");\n }\n\n #[test]\n fn can_execute_return_instruction() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.stack_pointer = 2;\n hardware.stack[0] = 1500;\n hardware.stack[1] = 938;\n hardware.stack[2] = 1700; // residual from previous call\n\n let instruction = Instruction::Return;\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 938 + 2, \"Incorrect program pointer\");\n assert_eq!(hardware.stack_pointer, 1, \"Incorrect stack pointer\");\n }\n\n #[test]\n fn cannot_execute_return_with_empty_stack() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.stack_pointer = 0;\n hardware.stack[0] = 1500;\n hardware.stack[1] = 938;\n\n let instruction = Instruction::Return;\n match execute_instruction(instruction, &mut hardware).unwrap_err() {\n ExecutionError::EmptyStack => (),\n x => panic!(\"Expected EmptyStack instead got {:?}\", x),\n }\n }\n\n #[test]\n fn skip_occurs_when_skip_if_equal_passes() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[5] = 23;\n\n let instruction = Instruction::SkipIfEqual {\n register: Register::General(5),\n value: 23,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1004, \"Incorrect program counter\");\n }\n\n #[test]\n fn does_not_skip_when_skip_if_equal_fails() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[5] = 23;\n\n let instruction = Instruction::SkipIfEqual {\n register: Register::General(5),\n value: 24,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n }\n\n #[test]\n fn skip_occurs_when_skip_if_not_equal_passes() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[5] = 23;\n\n let instruction = Instruction::SkipIfNotEqual {\n register: Register::General(5),\n value: 25,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1004, \"Incorrect program counter\");\n }\n\n #[test]\n fn does_not_skip_occurs_when_skip_if_not_equal_fails() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[5] = 23;\n\n let instruction = Instruction::SkipIfNotEqual {\n register: Register::General(5),\n value: 23,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n }\n\n #[test]\n fn skip_occurs_when_skip_if_register_equals_passes() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[4] = 23;\n hardware.gen_registers[5] = 23;\n\n let instruction = Instruction::SkipIfRegistersEqual {\n register1: Register::General(5),\n register2: Register::General(4),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1004, \"Incorrect program counter\");\n }\n\n #[test]\n fn does_not_skip_occurs_when_skip_if_register_equals_fails() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[4] = 25;\n hardware.gen_registers[5] = 23;\n\n let instruction = Instruction::SkipIfRegistersEqual {\n register1: Register::General(5),\n register2: Register::General(4),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n }\n\n #[test]\n fn skip_occurs_when_skip_if_register_not_equals_passes() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[4] = 25;\n hardware.gen_registers[5] = 23;\n\n let instruction = Instruction::SkipIfRegistersNotEqual {\n register1: Register::General(5),\n register2: Register::General(4),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1004, \"Incorrect program counter\");\n }\n\n #[test]\n fn does_not_skip_occurs_when_skip_if_register_not_equals_fails() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[4] = 23;\n hardware.gen_registers[5] = 23;\n\n let instruction = Instruction::SkipIfRegistersNotEqual {\n register1: Register::General(5),\n register2: Register::General(4),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n }\n\n #[test]\n fn skip_occurs_when_skip_if_key_pressed_passes() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[5] = 10;\n hardware.current_key_down = Some(10);\n\n let instruction = Instruction::SkipIfKeyPressed {\n register: Register::General(5),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1004, \"Incorrect program counter\");\n }\n\n #[test]\n fn does_not_skip_occurs_when_skip_if_key_pressed_fails() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[5] = 10;\n hardware.current_key_down = Some(11);\n\n let instruction = Instruction::SkipIfKeyPressed {\n register: Register::General(5),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n }\n\n #[test]\n fn skip_occurs_when_skip_if_key_not_pressed_passes() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[5] = 10;\n hardware.current_key_down = Some(11);\n\n let instruction = Instruction::SkipIfKeyNotPressed {\n register: Register::General(5),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1004, \"Incorrect program counter\");\n }\n\n #[test]\n fn does_not_skip_occurs_when_skip_if_key_not_pressed_fails() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[5] = 10;\n hardware.current_key_down = Some(10);\n\n let instruction = Instruction::SkipIfKeyNotPressed {\n register: Register::General(5),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n }\n\n #[test]\n fn can_or_register_values_together() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[2] = 123;\n hardware.gen_registers[3] = 203;\n\n let instruction = Instruction::Or {\n register1: Register::General(3),\n register2: Register::General(2),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[2], 123, \"Incorrect V2 value\");\n assert_eq!(hardware.gen_registers[3], 203 | 123, \"Incorrect v3 value\");\n }\n\n #[test]\n fn can_and_register_values_together() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[2] = 123;\n hardware.gen_registers[3] = 203;\n\n let instruction = Instruction::And {\n register1: Register::General(3),\n register2: Register::General(2),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[2], 123, \"Incorrect V2 value\");\n assert_eq!(hardware.gen_registers[3], 203 & 123, \"Incorrect v3 value\");\n }\n\n #[test]\n fn can_xor_register_values_together() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[2] = 123;\n hardware.gen_registers[3] = 203;\n\n let instruction = Instruction::Xor {\n register1: Register::General(3),\n register2: Register::General(2),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[2], 123, \"Incorrect V2 value\");\n assert_eq!(hardware.gen_registers[3], 203 ^ 123, \"Incorrect v3 value\");\n }\n\n #[test]\n fn can_shift_register_value_right() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[3] = 203;\n\n let instruction = Instruction::ShiftRight {\n register: Register::General(3),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[3], 203 >> 1, \"Incorrect v3 value\");\n }\n\n #[test]\n fn can_shift_register_value_left() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[3] = 203;\n\n let instruction = Instruction::ShiftLeft {\n register: Register::General(3),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[3], 203 << 1, \"Incorrect v3 value\");\n }\n\n #[test]\n fn can_get_random_number() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[3] = 100;\n\n let instruction = Instruction::SetRandom {\n register: Register::General(3),\n and_value: 23,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n\n let value1 = hardware.gen_registers[3];\n\n let instruction = Instruction::SetRandom {\n register: Register::General(3),\n and_value: 23,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n let value2 = hardware.gen_registers[3];\n\n assert_ne!(value1, value2, \"Values 1 and 2 were the same (possibly not random??)\");\n }\n\n #[test]\n fn can_subtract_register_without_underflow() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[4] = 100;\n hardware.gen_registers[5] = 25;\n\n let instruction = Instruction::Subtract {\n minuend: Register::General(4),\n subtrahend: Register::General(5),\n stored_in: Register::General(4),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[4], 75, \"Incorrect V4 register\");\n assert_eq!(hardware.gen_registers[5], 25, \"Incorrect V5 register\");\n assert_eq!(hardware.gen_registers[0xf], 1, \"Incorrect VF register\");\n }\n\n #[test]\n fn can_subtract_register_with_underflow() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[4] = 100;\n hardware.gen_registers[5] = 25;\n\n let instruction = Instruction::Subtract {\n minuend: Register::General(5),\n subtrahend: Register::General(4),\n stored_in: Register::General(5),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[4], 100, \"Incorrect V4 register\");\n assert_eq!(hardware.gen_registers[5], 181, \"Incorrect V5 register\");\n assert_eq!(hardware.gen_registers[0xf], 0, \"Incorrect VF register\");\n }\n\n #[test]\n fn can_clear_display() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n for x in 0..hardware.framebuffer.len() {\n for y in 0..hardware.framebuffer[x].len() {\n hardware.framebuffer[x][y] = 0xFF;\n }\n }\n\n let instruction = Instruction::ClearDisplay;\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n\n for x in 0..hardware.framebuffer.len() {\n for y in 0..hardware.framebuffer[x].len() {\n if hardware.framebuffer[x][y] != 0 {\n panic!(\"Expected frame buffer by {}x{} to be 0\", x, y);\n }\n }\n }\n }\n\n #[test]\n fn can_load_digit_sprite_location() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[4] = 0xa;\n\n let instruction = Instruction::LoadSpriteLocation {sprite_digit: Register::General(4)};\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.i_register, hardware.font_addresses[&0xa], \"Incorrect sprite address\");\n }\n\n #[test]\n fn can_load_address_into_i_register() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n\n let instruction = Instruction::LoadAddressIntoIRegister {address: 0x123};\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.i_register, 0x123, \"Incorrect I register value\");\n }\n\n #[test]\n fn visible_8_x_3_sprite_to_screen_on_x_multiple_of_8_can_be_drawn() {\n const SPRITE_START_ADDRESS: usize = 1046;\n const X_POS: u8 = 16;\n const Y_POS: u8 = 2;\n\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.i_register = SPRITE_START_ADDRESS as u16;\n hardware.gen_registers[4] = X_POS;\n hardware.gen_registers[3] = Y_POS;\n hardware.memory[SPRITE_START_ADDRESS] = 0b10101010;\n hardware.memory[SPRITE_START_ADDRESS + 1] = 0b01010101;\n hardware.memory[SPRITE_START_ADDRESS + 2] = 0b11001101;\n hardware.memory[SPRITE_START_ADDRESS + 3] = 0b11111111;\n\n let instruction = Instruction::DrawSprite {\n x_register: Register::General(4),\n y_register: Register::General(3),\n height: 3,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[0xf], 0, \"Incorrect VF value\");\n assert_eq!(hardware.framebuffer[2][2], 0b10101010, \"Incorrect framebuffer value at row 2 column byte 2\");\n assert_eq!(hardware.framebuffer[3][2], 0b01010101, \"Incorrect framebuffer value at row 3 column byte 2\");\n assert_eq!(hardware.framebuffer[4][2], 0b11001101, \"Incorrect framebuffer value at row 4 column byte 2\");\n assert_eq!(hardware.framebuffer[5][2], 0, \"Incorrect framebuffer value at row 5 column byte 2\");\n }\n\n #[test]\n fn visible_8_x_3_sprite_to_screen_on_x_non_multiple_of_8_can_be_drawn() {\n const SPRITE_START_ADDRESS: usize = 1046;\n const X_POS: u8 = 18;\n const Y_POS: u8 = 2;\n\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.i_register = SPRITE_START_ADDRESS as u16;\n hardware.gen_registers[4] = X_POS;\n hardware.gen_registers[3] = Y_POS;\n hardware.memory[SPRITE_START_ADDRESS] = 0b10101010;\n hardware.memory[SPRITE_START_ADDRESS + 1] = 0b01010101;\n hardware.memory[SPRITE_START_ADDRESS + 2] = 0b11001101;\n hardware.memory[SPRITE_START_ADDRESS + 3] = 0b11111111;\n\n let instruction = Instruction::DrawSprite {\n x_register: Register::General(4),\n y_register: Register::General(3),\n height: 3,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[0xf], 0, \"Incorrect VF value\");\n assert_eq!(hardware.framebuffer[2][2], 0b00101010, \"Incorrect framebuffer value at row 2 column byte 2\");\n assert_eq!(hardware.framebuffer[2][3], 0b10000000, \"Incorrect framebuffer value at row 2 column byte 3\");\n assert_eq!(hardware.framebuffer[3][2], 0b00010101, \"Incorrect framebuffer value at row 3 column byte 2\");\n assert_eq!(hardware.framebuffer[3][3], 0b01000000, \"Incorrect framebuffer value at row 3 column byte 3\");\n assert_eq!(hardware.framebuffer[4][2], 0b00110011, \"Incorrect framebuffer value at row 4 column byte 2\");\n assert_eq!(hardware.framebuffer[4][3], 0b01000000, \"Incorrect framebuffer value at row 4 column byte 3\");\n assert_eq!(hardware.framebuffer[5][2], 0, \"Incorrect framebuffer value at row 5 column byte 2\");\n assert_eq!(hardware.framebuffer[5][3], 0, \"Incorrect framebuffer value at row 5 column byte 3\");\n }\n\n #[test]\n fn sprites_xor_existing_framebuffer_values() {\n const SPRITE_START_ADDRESS: usize = 1046;\n const X_POS: u8 = 18;\n const Y_POS: u8 = 2;\n\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.i_register = SPRITE_START_ADDRESS as u16;\n hardware.gen_registers[4] = X_POS;\n hardware.gen_registers[3] = Y_POS;\n hardware.memory[SPRITE_START_ADDRESS] = 0b10101010;\n hardware.memory[SPRITE_START_ADDRESS + 1] = 0b01010101;\n hardware.memory[SPRITE_START_ADDRESS + 2] = 0b11001101;\n hardware.framebuffer[2][2] = 0xFF;\n hardware.framebuffer[2][3] = 0xFF;\n\n let instruction = Instruction::DrawSprite {\n x_register: Register::General(4),\n y_register: Register::General(3),\n height: 3,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[0xf], 1, \"Incorrect VF value\");\n assert_eq!(hardware.framebuffer[2][2], 0b00101010 ^ 0xFF, \"Incorrect framebuffer value at row 2 column byte 2\");\n assert_eq!(hardware.framebuffer[2][3], 0b10000000 ^ 0xFF, \"Incorrect framebuffer value at row 2 column byte 3\");\n assert_eq!(hardware.framebuffer[3][2], 0b00010101, \"Incorrect framebuffer value at row 3 column byte 2\");\n assert_eq!(hardware.framebuffer[3][3], 0b01000000, \"Incorrect framebuffer value at row 3 column byte 3\");\n assert_eq!(hardware.framebuffer[4][2], 0b00110011, \"Incorrect framebuffer value at row 4 column byte 2\");\n assert_eq!(hardware.framebuffer[4][3], 0b01000000, \"Incorrect framebuffer value at row 4 column byte 3\");\n assert_eq!(hardware.framebuffer[5][2], 0, \"Incorrect framebuffer value at row 5 column byte 2\");\n assert_eq!(hardware.framebuffer[5][3], 0, \"Incorrect framebuffer value at row 5 column byte 3\");\n }\n\n #[test]\n fn partially_visible_sprite_wraps_across_both_axis() {\n const SPRITE_START_ADDRESS: usize = 1046;\n const X_POS: u8 = 58;\n const Y_POS: u8 = 30;\n\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.i_register = SPRITE_START_ADDRESS as u16;\n hardware.gen_registers[4] = X_POS;\n hardware.gen_registers[3] = Y_POS;\n hardware.memory[SPRITE_START_ADDRESS] = 0b10101010;\n hardware.memory[SPRITE_START_ADDRESS + 1] = 0b01010101;\n hardware.memory[SPRITE_START_ADDRESS + 2] = 0b11001101;\n hardware.memory[SPRITE_START_ADDRESS + 3] = 0b11111111;\n\n let instruction = Instruction::DrawSprite {\n x_register: Register::General(4),\n y_register: Register::General(3),\n height: 3,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[0xf], 0, \"Incorrect VF value\");\n assert_eq!(hardware.framebuffer[30][7], 0b00101010, \"Incorrect framebuffer value at row 30 column byte 7\");\n assert_eq!(hardware.framebuffer[30][0], 0b10000000, \"Incorrect framebuffer value at row 30 column byte 0\");\n assert_eq!(hardware.framebuffer[31][7], 0b00010101, \"Incorrect framebuffer value at row 31 column byte 7\");\n assert_eq!(hardware.framebuffer[31][0], 0b01000000, \"Incorrect framebuffer value at row 31 column byte 0\");\n assert_eq!(hardware.framebuffer[0][7], 0b00110011, \"Incorrect framebuffer value at row 0 column byte 7\");\n assert_eq!(hardware.framebuffer[0][0], 0b01000000, \"Incorrect framebuffer value at row 0 column byte 0\");\n assert_eq!(hardware.framebuffer[1][7], 0, \"Incorrect framebuffer value at row 1 column byte 7\");\n assert_eq!(hardware.framebuffer[1][0], 0, \"Incorrect framebuffer value at row 1 column byte 0\");\n }\n\n #[test]\n fn can_set_gen_register_to_delay_timer_value() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[3] = 25;\n hardware.delay_timer = 50;\n\n let instruction = Instruction::LoadFromRegister {\n source: Register::DelayTimer,\n destination: Register::General(3),\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[3], 50, \"Incorrect VX value\");\n assert_eq!(hardware.delay_timer, 50, \"Incorrect delay timer value\");\n }\n\n #[test]\n fn can_set_delay_timer_to_value_in_general_register() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[3] = 25;\n hardware.delay_timer = 50;\n\n let instruction = Instruction::LoadFromRegister {\n source: Register::General(3),\n destination: Register::DelayTimer,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[3], 25, \"Incorrect VX value\");\n assert_eq!(hardware.delay_timer, 25, \"Incorrect delay timer value\");\n }\n\n #[test]\n fn can_set_sound_timer_to_value_in_general_register() {\n let mut hardware = Hardware::new();\n hardware.program_counter = 1000;\n hardware.gen_registers[3] = 25;\n hardware.sound_timer = 50;\n\n let instruction = Instruction::LoadFromRegister {\n source: Register::General(3),\n destination: Register::SoundTimer,\n };\n\n execute_instruction(instruction, &mut hardware).unwrap();\n assert_eq!(hardware.program_counter, 1002, \"Incorrect program counter\");\n assert_eq!(hardware.gen_registers[3], 25, \"Incorrect VX value\");\n assert_eq!(hardware.sound_timer, 25, \"Incorrect delay timer value\");\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":179,"cells":{"blob_id":{"kind":"string","value":"b02f18df40f0853593c61d4e526fd341a4b168d3"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"kalaninja/data-structures"},"path":{"kind":"string","value":"/week2_priority_queues_and_disjoint_sets/2_job_queue/rust/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3274,"string":"3,274"},"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":"use std::io::stdin;\nuse std::fmt::{self, Display, Formatter};\n\ntype ThreadId = u32;\ntype ThreadTime = u64;\n\n#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]\nstruct Thread {\n time_idle: ThreadTime,\n thread_id: ThreadId,\n}\n\nimpl Thread {\n fn new(thread_id: ThreadId, time_idle: ThreadTime) -> Self {\n Thread { thread_id, time_idle }\n }\n}\n\nimpl Display for Thread {\n fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {\n write!(f, \"{} {}\", self.thread_id, self.time_idle)\n }\n}\n\n#[derive(Debug)]\nstruct ThreadQueue {\n data: Vec\n}\n\nimpl ThreadQueue {\n fn new(n: usize) -> Self {\n ThreadQueue {\n data: (0..n as ThreadId)\n .fold(Vec::with_capacity(n),\n |mut acc, i| {\n acc.push(Thread::new(i, 0));\n acc\n })\n }\n }\n\n fn peak(&self) -> &Thread {\n &self.data[0]\n }\n\n fn exec_task(&mut self, time: u32) {\n self.data[0].time_idle += time as u64;\n self.sift_down(0);\n }\n\n fn sift_down(&mut self, i: usize) {\n let mut cur_i = i;\n\n loop {\n let left = 2 * cur_i + 1;\n if left >= self.data.len() { break; }\n\n let right = 2 * cur_i + 2;\n let min = if right < self.data.len() && self.data[right] < self.data[left] {\n right\n } else {\n left\n };\n\n if self.data[min] < self.data[cur_i] {\n self.data.swap(cur_i, min);\n cur_i = min;\n } else {\n break;\n }\n }\n }\n}\n\nfn main() {\n let n = read_line()\n .split_whitespace()\n .nth(0).unwrap()\n .parse().unwrap();\n let t = read_line().trim()\n .split_whitespace()\n .map(|x| x.parse().unwrap())\n .collect();\n\n solve(n, t).iter().for_each(|x| println!(\"{}\", x));\n}\n\nfn solve(n: usize, tasks: Vec) -> Vec {\n let mut threads = ThreadQueue::new(n);\n let mut result = Vec::with_capacity(tasks.len());\n\n for time in tasks {\n result.push(*threads.peak());\n threads.exec_task(time);\n }\n\n result\n}\n\n#[test]\nfn test_case_1() {\n let e = vec![\n Thread::new(0, 0),\n Thread::new(1, 0),\n Thread::new(0, 1),\n Thread::new(1, 2),\n Thread::new(0, 4),\n ];\n\n assert_eq!(solve(2, vec![1, 2, 3, 4, 5]), e);\n}\n\n#[test]\nfn test_case_2() {\n let e = vec![\n Thread::new(0, 0),\n Thread::new(1, 0),\n Thread::new(2, 0),\n Thread::new(3, 0),\n Thread::new(0, 1),\n Thread::new(1, 1),\n Thread::new(2, 1),\n Thread::new(3, 1),\n Thread::new(0, 2),\n Thread::new(1, 2),\n Thread::new(2, 2),\n Thread::new(3, 2),\n Thread::new(0, 3),\n Thread::new(1, 3),\n Thread::new(2, 3),\n Thread::new(3, 3),\n Thread::new(0, 4),\n Thread::new(1, 4),\n Thread::new(2, 4),\n Thread::new(3, 4),\n ];\n\n assert_eq!(solve(4, vec![1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), e);\n}\n\nfn read_line() -> String {\n let mut input = String::new();\n stdin().read_line(&mut input).unwrap();\n input\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":180,"cells":{"blob_id":{"kind":"string","value":"ef1331be181b9020769930de3c4dcfc1ff3f1abd"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"MwlLj/rust-p2p"},"path":{"kind":"string","value":"/exchange_service/src/enums/nat.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":555,"string":"555"},"score":{"kind":"number","value":3.46875,"string":"3.46875"},"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::cmp::PartialEq;\n\n#[derive(PartialEq, Debug, Clone)]\npub enum Nat {\n Nat1 = 1,\n Nat2 = 2,\n Nat3 = 3,\n Nat4 = 4,\n NotNat4 = 5\n}\n\nimpl std::convert::From for Nat {\n fn from(item: u8) -> Self {\n match item {\n 1 => Nat::Nat1,\n 2 => Nat::Nat2,\n 3 => Nat::Nat3,\n 4 => Nat::Nat4,\n 5 => Nat::NotNat4,\n _ => Nat::Nat1\n }\n }\n}\n\n// impl PartialEq for Nat {\n// fn eq(&self, other: &Nat) -> bool {\n// *self as u8 == *other as u8\n// }\n// }\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":181,"cells":{"blob_id":{"kind":"string","value":"c18e0eec7aa060fe97fdb6dc292259a5da9e8088"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"leon2k2k2k/xi_pl"},"path":{"kind":"string","value":"/xi-backends/py_backend/py_prim.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4355,"string":"4,355"},"score":{"kind":"number","value":2.515625,"string":"2.515625"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["LicenseRef-scancode-warranty-disclaimer"],"string":"[\n \"LicenseRef-scancode-warranty-disclaimer\"\n]"},"license_type":{"kind":"string","value":"no_license"},"text":{"kind":"string","value":"use std::collections::BTreeMap;\n\nuse xi_core::judgment::{Judgment, Primitive};\nuse xi_uuid::VarUuid;\n\nuse crate::py_backend::py_output::{\n make_var_name, promise_resolve, to_py_ident, to_py_num, to_py_str, Expr,\n};\n\nuse super::py_output::{to_py_app, to_py_ident1};\n\n#[derive(Clone, PartialEq, Eq, Debug)]\npub enum PyPrim {\n StringType,\n NumberType,\n StringElem(String),\n NumberElem(String),\n Ffi(String, String),\n Remote(String, String),\n Var(VarUuid),\n}\n\nimpl Primitive for PyPrim {\n fn maybe_prim_type(&self) -> Option> {\n use PyPrim::*;\n\n match self {\n StringType => Some(Judgment::u(None)),\n NumberType => Some(Judgment::u(None)),\n StringElem(_) => Some(Judgment::prim_wo_prim_type(StringType, None)),\n NumberElem(_) => Some(Judgment::prim_wo_prim_type(NumberType, None)),\n Ffi(_, _) => None,\n Var(_) => None,\n Remote(_, _) => None,\n }\n }\n}\n\nimpl PyPrim {\n pub fn to_py_prim(\n &self,\n ffi: &mut BTreeMap<(String, String), VarUuid>,\n remote: &mut BTreeMap<(String, String), VarUuid>,\n ) -> Expr {\n match self {\n PyPrim::StringType => {\n promise_resolve(to_py_app(to_py_ident(\"prim\"), vec![to_py_str(\"Str\")]))\n }\n PyPrim::NumberType => {\n promise_resolve(to_py_app(to_py_ident(\"prim\"), vec![to_py_str(\"Int\")]))\n }\n PyPrim::StringElem(str) => promise_resolve(to_py_str(str.clone())),\n PyPrim::NumberElem(num) => promise_resolve(to_py_num(num.clone())),\n PyPrim::Ffi(filename, ffi_name) => {\n let var = match ffi.get(&(filename.clone(), ffi_name.clone())) {\n Some(var) => *var,\n None => {\n let var = VarUuid::new();\n ffi.insert((filename.clone(), ffi_name.clone()), var);\n var\n }\n };\n\n to_py_ident(format!(\"ffi{}\", var.index()))\n }\n PyPrim::Remote(remote_address, remote_name) => {\n let var = match remote.get(&(remote_address.clone(), remote_name.clone())) {\n Some(var) => *var,\n None => {\n let var = VarUuid::new();\n remote.insert((remote_address.clone(), remote_address.clone()), var);\n var\n }\n };\n\n to_py_ident(format!(\"remote{}\", var.index()))\n }\n\n PyPrim::Var(index) => to_py_ident1(make_var_name(index)),\n }\n }\n}\n\n#[derive(Clone, Debug)]\npub struct PyModule {\n pub str_to_index: BTreeMap,\n pub module_items: BTreeMap,\n}\n\n#[derive(Clone, Debug)]\n\npub struct PyModuleAndImports {\n pub module: PyModule,\n pub imports: BTreeMap,\n}\n\n#[derive(Clone, Debug)]\npub enum PyModuleItem {\n Define(PyDefineItem),\n // Import(JsImportItem),\n}\n\nimpl PyModuleItem {\n pub fn type_(&self) -> Judgment {\n match self {\n PyModuleItem::Define(define_item) => define_item.type_.clone(),\n // JsModuleItem::Import(import_item) => import_item.type_.clone(),\n }\n }\n\n pub fn transport_info(&self) -> TransportInfo {\n match self {\n PyModuleItem::Define(define_item) => define_item.transport_info.clone(),\n }\n }\n}\n\n#[derive(Clone, Debug)]\npub struct PyDefineItem {\n pub name: String,\n pub transport_info: TransportInfo,\n pub type_: Judgment,\n pub impl_: Judgment,\n}\n\n#[derive(Clone, Debug)]\npub struct TransportInfo {\n pub origin: Option,\n pub transport: Option,\n}\n\nimpl TransportInfo {\n pub fn none() -> TransportInfo {\n TransportInfo {\n origin: None,\n transport: None,\n }\n }\n\n pub fn only_origin(origin: String) -> TransportInfo {\n TransportInfo {\n origin: Some(origin),\n transport: None,\n }\n }\n\n pub fn origin_and_transport(origin: String, tranport: String) -> TransportInfo {\n TransportInfo {\n origin: Some(origin),\n transport: Some(tranport),\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":182,"cells":{"blob_id":{"kind":"string","value":"8be91f8a6314d1ee36682bf93fca8b5573a1dafd"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"SuperiorJT/mr-cd-projekt-red"},"path":{"kind":"string","value":"/src/audio/receiver.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3352,"string":"3,352"},"score":{"kind":"number","value":2.578125,"string":"2.578125"},"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::{\n collections::HashMap,\n sync::Arc,\n sync::RwLock,\n time::{Instant, SystemTime, UNIX_EPOCH},\n};\n\nuse config::{Config, File};\nuse serde::Deserialize;\n\nuse serenity::model::id::UserId;\nuse serenity::voice::AudioReceiver;\n\nuse super::buffer::DiscordAudioBuffer;\nuse super::DiscordAudioPacket;\n\n#[derive(Deserialize)]\nstruct UserMixConfig {\n volume: f32,\n mute: bool,\n}\n\nimpl Default for UserMixConfig {\n fn default() -> Self {\n Self {\n volume: 1.0,\n mute: false,\n }\n }\n}\n\npub struct Receiver {\n buffer: Arc>,\n mix_config: HashMap,\n instant: Instant,\n}\n\nimpl Receiver {\n pub fn new(buffer: Arc>) -> Self {\n let mut config = Config::new();\n if let Err(err) = config.merge(File::with_name(\"config/mixer.json\")) {\n error!(\"{} - Using empty config\", err);\n }\n let mix_config = match config.try_into::>() {\n Ok(c) => c,\n Err(_) => HashMap::new(),\n };\n Self {\n buffer,\n mix_config,\n instant: Instant::now(),\n }\n }\n}\n\nimpl AudioReceiver for Receiver {\n fn speaking_update(&mut self, ssrc: u32, user_id: u64, speaking: bool) {\n let mut buffer = match self.buffer.write() {\n Ok(buffer) => buffer,\n Err(why) => {\n error!(\"Could not get audio buffer lock: {:?}\", why);\n\n return;\n }\n };\n let volume = self.mix_config.entry(user_id).or_default().volume;\n buffer.update_track_mix(ssrc, (volume * f32::from(u8::max_value())) as u8);\n\n info!(\"Speaking Update: {}, {}, {}\", user_id, ssrc, speaking);\n }\n\n fn voice_packet(\n &mut self,\n ssrc: u32,\n sequence: u16,\n _timestamp: u32,\n stereo: bool,\n data: &[i16],\n _compressed_size: usize,\n ) {\n // info!(\n // \"Audio packet sequence {:05} has {:04} bytes, SSRC {}, is_stereo: {}\",\n // sequence,\n // data.len() * 2,\n // ssrc,\n // stereo\n // );\n // let since_the_epoch = SystemTime::now()\n // .duration_since(UNIX_EPOCH)\n // .expect(\"Time went backwards\");\n // let since_start = self.instant.elapsed().as_secs()\n // * u64::from(1000 + self.instant.elapsed().subsec_millis());\n // let timestamp = since_the_epoch.as_secs() * 1000 + since_the_epoch.subsec_millis() as u64;\n // info!(\n // \"Time: {}, Sequence: {}, ssrc: {}\",\n // since_start, sequence, ssrc\n // );\n // let mut buffer = match self.buffer.write() {\n // Ok(buffer) => buffer,\n // Err(why) => {\n // error!(\"Could not get audio buffer lock: {:?}\", why);\n\n // return;\n // }\n // };\n // buffer.insert_item(DiscordAudioPacket::new(\n // ssrc,\n // sequence,\n // timestamp,\n // stereo,\n // data.to_owned(),\n // ));\n // info!(\n // \"Data Size: {}, Buffer Length: {}, Buffer Cap: {}\",\n // data.len(),\n // buffer.size(),\n // buffer.capacity()\n // );\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":183,"cells":{"blob_id":{"kind":"string","value":"e1257f2999b0a1a7a626edd92e68b001cded0b65"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"tonmanna/RustLearningFollowBookBeginer"},"path":{"kind":"string","value":"/chapter2/src/tuples_sample3.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":159,"string":"159"},"score":{"kind":"number","value":2.796875,"string":"2.796875"},"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)]\nstruct Matrix(f32, f32, f32, f32);\n\npub fn tuples_sample_struct() {\n let matrix = Matrix(1.1,1.2,2.1,2.2);\n println!(\"{:?}\", matrix);\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":184,"cells":{"blob_id":{"kind":"string","value":"515021a225e189e61d7eab324be1137cab06e59b"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"shunty-gh/AdventOfCode2017"},"path":{"kind":"string","value":"/day12/aoc2017-day12.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2689,"string":"2,689"},"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":"use std::io::prelude::*;\nuse std::fmt;\nuse std::io::BufReader;\nuse std::fs::File;\nuse std::path::Path;\nuse std::env;\n\n/// Advent of Code 2017\n/// Day 12\n\n// compile with, for example:\n// $> rustc -g --out-dir ./bin aoc2017-day12.rs\n// or (providing the 'path' is set correctly in Cargo.toml):\n// $> cargo build\n\nfn main() {\n let args: Vec = env::args().collect();\n let inputname: &str;\n if args.len() > 1 {\n inputname = &args[1];\n } else {\n inputname = \"./aoc2017-day12.txt\";\n }\n\n let input = lines_from_file(inputname);\n\n let programs: Vec = input.iter()\n .map(|line| {\n let splits: Vec<&str> = line.split(\" <-> \").collect();\n\n Program {\n id: splits[0].to_string().parse::().unwrap(),\n connections: splits[1].to_string()\n .split(\", \")\n .map(|s| s.parse::().unwrap())\n .collect(),\n }\n })\n .collect();\n //println!(\"Programs: {:?}\", programs);\n\n let mut visited: Vec = vec![];\n let mut group_count = 0;\n let mut group_zero_count = 0;\n\n for program in &programs {\n let key = &program.id;\n if visited.contains(key) {\n continue;\n }\n\n group_count += 1;\n let mut to_visit: Vec = vec![*key];\n while to_visit.len() > 0 {\n let current = to_visit.pop().unwrap();\n if !visited.contains(&current) {\n visited.push(current);\n\n for conn in &programs[current].connections {\n if !visited.contains(conn) {\n to_visit.push(*conn);\n }\n }\n }\n }\n if *key == 0 {\n group_zero_count = visited.len();\n }\n }\n\n assert!(programs.len() == visited.len(), \"Number visited should equal total number of programs\");\n println!(\"Using {} as input\", &inputname);\n println!(\"Num programs: {}\", programs.len());\n println!(\"Programs connected to P0 (part 1): {}\", group_zero_count);\n println!(\"Number of groups (part 2): {}\", group_count);\n}\n\nfn lines_from_file

(filename: P) -> Vec\nwhere\n P: AsRef,\n{\n let file = File::open(filename).expect(\"no such file\");\n let buf = BufReader::new(file);\n buf.lines()\n .map(|l| l.expect(\"Could not parse line\"))\n .collect()\n}\n\nstruct Program {\n id: usize,\n connections: Vec,\n}\n\nimpl fmt::Debug for Program {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"Prog id: {}; Connections: {:?}\", self.id, self.connections)\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":185,"cells":{"blob_id":{"kind":"string","value":"f5dff23875161835aebdb3f0e6a7dc725d3facee"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"KwinnerChen/rust_repo"},"path":{"kind":"string","value":"/workspace_learning/complex/src/lib.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1850,"string":"1,850"},"score":{"kind":"number","value":3.921875,"string":"3.921875"},"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":"#![allow(dead_code)]\n\nuse std::{fmt::{Display, Formatter, Result}, ops::Add, write};\n\n\n/// 表示复数结构\n#[derive(Debug, Default, PartialEq, Clone, Copy)]\nstruct Complex {\n re: T,\n im: T,\n}\n\nimpl> Complex {\n /// 创建一个复数结构\n /// # Example\n /// ```\n /// use complex::Complex;\n /// let com = Complex::new(0, 0);\n /// assert_eq!(Complex{re:0, im:0}, com);\n ///```\n /// # Panic!\n /// 只能由实现了Add trait的类型创建\n fn new(re: T, im: T) -> Self {\n Self {\n re,\n im,\n }\n }\n}\n\nimpl> Add for Complex {\n type Output = Self;\n fn add(self, other:Self) -> Self::Output {\n Self {\n re: self.re + other.re,\n im: self.im + other.im,\n }\n }\n}\n\nimpl Display for Complex {\n fn fmt(&self, f: &mut Formatter) -> Result {\n write!(f, \"{}+{}i\", self.re, self.im)\n }\n}\n\n\nfn show_me(item: impl Display) {\n println!(\"{}\", item);\n}\n\n#[cfg(test)]\nmod tests {\n #[derive(Debug, Clone)]\n struct Foo;\n\n use super::*;\n #[test]\n fn it_works() {\n let complex1 = Complex::new(3, 5);\n let complex2 = Complex::::default();\n assert_eq!(complex1, complex1 + complex2);\n assert_eq!(complex1, Complex {re:3, im:5});\n println!(\"{}\", complex1);\n }\n\n #[test]\n fn do_work() {\n show_me(\"hello rust!\");\n }\n\n #[test]\n fn do_work_2() {\n let mut s1 = String::from(\"hello\");\n let s2 = &mut s1;\n s2.push_str(\"rust\");\n\n println!(\"{:?}\", s2);\n }\n\n #[test]\n fn test_work_3() {\n let mut s = String::from(\"Hello Rust\");\n let a_mut_ref = &mut s;\n let a_mut_ref_2 = a_mut_ref;\n\n a_mut_ref_2.push_str(\"!\");\n\n println!(\"{}\", &s);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":186,"cells":{"blob_id":{"kind":"string","value":"c2115a876151368aae7cb2232eb1b815a0990de5"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"peterhj/libcpu_topo"},"path":{"kind":"string","value":"/src/lib.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2874,"string":"2,874"},"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":"extern crate libc;\n\nuse libc::*;\n//use std::collections::{HashSet};\nuse std::fs::{File};\nuse std::io::{BufRead, BufReader};\nuse std::mem::{size_of_val, uninitialized};\nuse std::path::{PathBuf};\n//use std::process::{Command};\n\n/*pub enum CpuLevel {\n Processor,\n Core,\n Thread,\n}*/\n\n#[cfg(target_os = \"linux\")]\npub fn set_affinity(thr_idxs: &[usize]) -> Result<(), ()> {\n unsafe {\n let mut cpuset = uninitialized();\n CPU_ZERO(&mut cpuset);\n for &thr_idx in thr_idxs {\n CPU_SET(thr_idx, &mut cpuset);\n }\n let thread = pthread_self();\n match pthread_setaffinity_np(thread, size_of_val(&cpuset), &cpuset as *const _) {\n 0 => Ok(()),\n _ => Err(()),\n }\n }\n}\n\npub enum CpuTopologySource {\n Auto,\n LinuxProcCpuinfo,\n}\n\n#[derive(Debug)]\npub struct CpuThreadInfo {\n pub thr_idx: usize,\n pub core_idx: usize,\n pub proc_idx: usize,\n}\n\n#[derive(Debug)]\npub struct CpuTopology {\n pub threads: Vec,\n}\n\nimpl CpuTopology {\n pub fn query(source: CpuTopologySource) -> CpuTopology {\n match source {\n CpuTopologySource::Auto => {\n unimplemented!();\n }\n CpuTopologySource::LinuxProcCpuinfo => {\n Self::query_proc_cpuinfo()\n }\n }\n }\n\n fn query_proc_cpuinfo() -> CpuTopology {\n let file = File::open(&PathBuf::from(\"/proc/cpuinfo\"))\n .unwrap();\n let reader = BufReader::new(file);\n\n //let mut thread_set = HashSet::new();\n let mut threads = vec![];\n let mut curr_thread = None;\n for line in reader.lines() {\n let line = line.unwrap();\n if line.len() >= 9 && &line[ .. 9] == \"processor\" {\n let toks: Vec<_> = line.splitn(2, \":\").collect();\n\n // Not assuming processor numbers are consecutive.\n let thread_idx: usize = toks[1].trim().parse().unwrap();\n //thread_set.insert(thread_idx);\n\n if let Some(info) = curr_thread {\n threads.push(info);\n }\n\n curr_thread = Some(CpuThreadInfo{\n thr_idx: thread_idx,\n core_idx: 0,\n proc_idx: 0,\n });\n\n } else if line.len() >= 7 && &line[ .. 7] == \"core id\" {\n let toks: Vec<_> = line.splitn(2, \":\").collect();\n\n let core_idx: usize = toks[1].trim().parse().unwrap();\n if let Some(ref mut info) = curr_thread {\n info.core_idx = core_idx;\n }\n\n } else if line.len() >= 11 && &line[ .. 11] == \"physical id\" {\n let toks: Vec<_> = line.splitn(2, \":\").collect();\n\n let proc_idx: usize = toks[1].trim().parse().unwrap();\n if let Some(ref mut info) = curr_thread {\n info.proc_idx = proc_idx;\n }\n\n }\n }\n if let Some(info) = curr_thread {\n threads.push(info);\n }\n //let num_threads = processor_set.len();\n\n CpuTopology{\n threads: threads,\n }\n }\n\n pub fn num_threads(&self) -> usize {\n self.threads.len()\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":187,"cells":{"blob_id":{"kind":"string","value":"fb51b6683054c4122e05bd60fe5ede509a3d103b"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"sbeckeriv/dex"},"path":{"kind":"string","value":"/src/app/mod.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3149,"string":"3,149"},"score":{"kind":"number","value":3.3125,"string":"3.3125"},"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":"mod error;\nmod pokemon;\nmod style;\n\nuse error::Error;\nuse iced::{\n button, Alignment, Application, Button, Column, Command, Container, Element, Length, Text,\n};\nuse pokemon::Pokemon;\n\n#[derive(Debug)]\npub enum Pokedex {\n Loading,\n Loaded {\n pokemon: Pokemon,\n search: button::State,\n },\n Errored {\n error: Error,\n try_again: button::State,\n },\n}\n\n#[derive(Debug, Clone)]\npub enum Message {\n PokémonFound(Result),\n Search,\n}\n\nimpl Application for Pokedex {\n type Executor = iced::executor::Default;\n type Message = Message;\n type Flags = ();\n\n fn new(_flags: ()) -> (Self, Command) {\n (\n Self::Loading,\n Command::perform(Pokemon::search(), Message::PokémonFound),\n )\n }\n\n fn title(&self) -> String {\n let subtitle = match self {\n Self::Loading => \"Loading\",\n Self::Loaded { pokemon, .. } => &pokemon.name,\n Self::Errored { .. } => \"Whoops!\",\n };\n\n format!(\"Pok\\u{e9}dex - {}\", subtitle)\n }\n\n fn update(&mut self, message: Message) -> Command {\n match message {\n Message::PokémonFound(Ok(pokemon)) => {\n *self = Self::Loaded {\n pokemon,\n search: button::State::new(),\n };\n\n Command::none()\n }\n Message::PokémonFound(Err(error)) => {\n *self = Self::Errored {\n error,\n try_again: button::State::new(),\n };\n\n Command::none()\n }\n Message::Search => {\n if let Self::Loading = self {\n Command::none()\n } else {\n *self = Self::Loading;\n\n Command::perform(Pokemon::search(), Message::PokémonFound)\n }\n }\n }\n }\n\n fn view(&mut self) -> Element {\n let content = match self {\n Self::Loading => Column::new()\n .width(Length::Shrink)\n .push(Text::new(\"Searching for Pok\\u{e9}mon...\").size(40)),\n Self::Loaded { pokemon, search } => Column::new()\n .max_width(500)\n .spacing(20)\n .align_items(Alignment::End)\n .push(pokemon.view())\n .push(button(search, \"Keep searching!\").on_press(Message::Search)),\n Self::Errored { try_again, .. } => Column::new()\n .spacing(20)\n .align_items(Alignment::End)\n .push(Text::new(\"Whoops! Something went wrong...\").size(40))\n .push(button(try_again, \"Try again\").on_press(Message::Search)),\n };\n\n Container::new(content)\n .width(Length::Fill)\n .height(Length::Fill)\n .center_x()\n .center_y()\n .into()\n }\n}\n\nfn button<'a>(state: &'a mut button::State, text: &str) -> Button<'a, Message> {\n Button::new(state, Text::new(text))\n .padding(10)\n .style(style::Button::Primary)\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":188,"cells":{"blob_id":{"kind":"string","value":"4f2ae26f3aacf1d4e12313867cd19177ef29110b"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"pitcer/brucket"},"path":{"kind":"string","value":"/c-generator/src/syntax/c_struct.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":3141,"string":"3,141"},"score":{"kind":"number","value":3.140625,"string":"3.140625"},"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::generator::{GeneratorError, GeneratorResult, GeneratorState, IndentedGenerator};\nuse crate::syntax::instruction::VariableDeclaration;\nuse derive_more::Constructor;\n\n#[derive(Debug, PartialEq, Constructor)]\npub struct CStruct {\n name: String,\n fields: Fields,\n}\n\nimpl IndentedGenerator for CStruct {\n #[inline]\n fn generate_indented(self, state: &GeneratorState) -> GeneratorResult {\n let indentation = &state.indentation;\n let incremented_indentation = state.indentation.to_incremented();\n let state = GeneratorState::new(incremented_indentation);\n Ok(format!(\n \"{}struct {} {{\\n{}\\n{}}};\",\n indentation,\n self.name,\n self.fields.generate_indented(&state)?,\n indentation\n ))\n }\n}\n\npub type Fields = Vec;\n\nimpl IndentedGenerator for Fields {\n #[inline]\n fn generate_indented(self, state: &GeneratorState) -> GeneratorResult {\n Ok(self\n .into_iter()\n .map(|field| field.generate_indented(state))\n .collect::, GeneratorError>>()?\n .join(\"\\n\"))\n }\n}\n\n#[cfg(test)]\nmod test {\n use crate::syntax::c_type::{CPrimitiveType, CType};\n use crate::syntax::modifiers::Modifier;\n use crate::syntax::TestResult;\n\n use super::*;\n\n #[test]\n fn test_generate_fields() -> TestResult {\n assert_eq!(\n \"const int a;\\nint b;\\nint c;\",\n vec![\n VariableDeclaration::new(\n vec![Modifier::Const],\n CType::Primitive(CPrimitiveType::Int),\n \"a\".to_owned()\n ),\n VariableDeclaration::new(\n vec![],\n CType::Primitive(CPrimitiveType::Int),\n \"b\".to_owned()\n ),\n VariableDeclaration::new(\n vec![],\n CType::Primitive(CPrimitiveType::Int),\n \"c\".to_owned()\n )\n ]\n .generate_indented(&GeneratorState::default())?\n );\n Ok(())\n }\n\n #[test]\n fn test_generate_struct() -> TestResult {\n assert_eq!(\n \"struct foobar {\\n const int a;\\n int b;\\n int c;\\n};\",\n CStruct::new(\n \"foobar\".to_owned(),\n vec![\n VariableDeclaration::new(\n vec![Modifier::Const],\n CType::Primitive(CPrimitiveType::Int),\n \"a\".to_owned()\n ),\n VariableDeclaration::new(\n vec![],\n CType::Primitive(CPrimitiveType::Int),\n \"b\".to_owned()\n ),\n VariableDeclaration::new(\n vec![],\n CType::Primitive(CPrimitiveType::Int),\n \"c\".to_owned()\n )\n ]\n )\n .generate_indented(&GeneratorState::default())?\n );\n Ok(())\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":189,"cells":{"blob_id":{"kind":"string","value":"3ccef59cbe0cd896e9356a4fcf1d782c11ab34c2"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"naamancurtis/rust_data_structures_and_algorithms"},"path":{"kind":"string","value":"/sorting/src/insertion_sort.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2439,"string":"2,439"},"score":{"kind":"number","value":4.28125,"string":"4.28125"},"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":"//! # Insertion Sort\n//!\n//! Is a simple sorting algorithm that builds the sorted array one element at a time by maintaining a sorted\n//! sub-array into which elements are inserted.\n//!\n//! - Time Complexity: **O**(n2)\n//! - Space Complexity: **O**( _log_(n) )\n\nuse std::cmp::Ordering;\n\n/// Shorthand helper function which carries out sorting of a slice of `T` _where_ `T: Ord`\n///\n/// # Examples\n/// ```rust\n/// use sorting::insertion_sort::insertion_sort;\n///\n/// let mut arr = vec![37, 45, 29, 8];\n/// insertion_sort(&mut arr);\n/// assert_eq!(arr, [8, 29, 37, 45]);\n/// ```\npub fn insertion_sort(arr: &mut [T])\nwhere\n T: Ord,\n{\n insertion_sort_by(arr, &|x, y| x.cmp(y))\n}\n\n/// Carries out sorting of a slice of `T` using the provided comparator function `F`\n///\n/// # Examples\n/// ```rust\n/// use sorting::insertion_sort::insertion_sort_by;\n///\n/// let mut arr = vec![37, 45, 29, 8 ,10];\n/// insertion_sort_by(&mut arr, &|x, y| x.cmp(y));\n/// assert_eq!(arr, [8, 10, 29, 37, 45]);\n/// ```\npub fn insertion_sort_by(arr: &mut [T], cmp: &F)\nwhere\n F: Fn(&T, &T) -> Ordering,\n{\n if arr.is_empty() {\n return;\n }\n\n for i in 1..arr.len() {\n for j in (1..=i).rev() {\n if cmp(&arr[j], &arr[j - 1]) == Ordering::Less {\n arr.swap(j, j - 1);\n } else {\n break;\n }\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn test_semi_sorted() {\n let mut arr = vec![1, 23, 2, 32, 29, 33];\n insertion_sort(&mut arr);\n assert_eq!(arr, [1, 2, 23, 29, 32, 33]);\n }\n\n #[test]\n fn test_backwards() {\n let mut arr = vec![50, 25, 10, 5, 1];\n insertion_sort(&mut arr);\n assert_eq!(arr, [1, 5, 10, 25, 50]);\n }\n\n #[test]\n fn test_sorted() {\n let mut arr = vec![1, 5, 10, 25, 50];\n insertion_sort(&mut arr);\n assert_eq!(arr, [1, 5, 10, 25, 50]);\n }\n\n #[test]\n fn test_empty() {\n let mut arr: Vec = vec![];\n insertion_sort(&mut arr);\n assert_eq!(arr, []);\n }\n\n #[test]\n fn test_len_two() {\n let mut arr = vec![5, 1];\n insertion_sort(&mut arr);\n assert_eq!(arr, [1, 5]);\n }\n\n #[test]\n fn test_partially_sorted() {\n let mut arr = vec![50, 75, 1, 1, 3, 4, 5, 6, 50];\n insertion_sort(&mut arr);\n assert_eq!(arr, [1, 1, 3, 4, 5, 6, 50, 50, 75]);\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":190,"cells":{"blob_id":{"kind":"string","value":"75e6ec41d57b2b916e9b24178f790cd732015af3"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Iwancof/SECR"},"path":{"kind":"string","value":"/riscv-rust/src/terminal.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":747,"string":"747"},"score":{"kind":"number","value":3.265625,"string":"3.265625"},"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":"/// Emulates terminal. It holds input/output data in buffer\n/// transferred to/from `Emulator`.\npub trait Terminal {\n\t/// Puts an output ascii byte data to output buffer.\n\t/// The data is expected to be read by user program via `get_output()`\n\t/// and be displayed to user.\n\tfn put_byte(&mut self, value: u8);\n\n\t/// Gets an output ascii byte data from output buffer.\n\t/// This method returns zero if the buffer is empty.\n\tfn get_output(&mut self) -> u8;\n\n\t/// Puts an input ascii byte data to input buffer.\n\t/// The data is expected to be read by `Emulator` via `get_input()`\n\t/// and be handled.\n\tfn put_input(&mut self, data: u8);\n\n\t/// Gets an input ascii byte data from input buffer.\n\t/// Used by `Emulator`.\n\tfn get_input(&mut self) -> u8;\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":191,"cells":{"blob_id":{"kind":"string","value":"722a7a33904b12f0f16d1119e7b861b533edc412"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"sirkibsirkib/middleman"},"path":{"kind":"string","value":"/src/structs.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":17075,"string":"17,075"},"score":{"kind":"number","value":3.171875,"string":"3.171875"},"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 super::*;\n\nuse mio::{\n *,\n event::Evented,\n};\n\nuse ::std::{\n io,\n io::{\n Read,\n Write,\n ErrorKind,\n },\n time,\n};\n\n\n#[derive(Debug)]\npub struct Middleman {\n stream: mio::net::TcpStream,\n buf: Vec,\n buf_occupancy: usize,\n payload_bytes: Option,\n}\n\nimpl Middleman { fn check_payload(&mut self) {\n if self.payload_bytes.is_none() && self.buf_occupancy >= 4 {\n \tself.payload_bytes = Some(\n \t\tbincode::deserialize(&self.buf[..4])\n \t\t.unwrap()\n \t)\n }\n }\n\n /// Create a new Middleman structure to wrap the given Mio TcpStream.\n /// The Middleman implements `mio::Evented`, but delegates its functions to this given stream\n /// As such, registering the Middleman and registering the TcpStream are anaologous.\n pub fn new(stream: mio::net::TcpStream) -> Middleman {\n \tSelf {\n stream: stream,\n buf: Vec::with_capacity(128),\n buf_occupancy: 0,\n payload_bytes: None,\n }\n }\n\n fn read_in(&mut self) -> Result {\n let mut total = 0;\n loop {\n let limit = (self.buf_occupancy + 64) + (self.buf_occupancy);\n if self.buf.len() < limit {\n self.buf.resize(limit, 0u8);\n }\n match self.stream.read(&mut self.buf[self.buf_occupancy..]) {\n Ok(0) => return Ok(total),\n Ok(bytes) => {\n self.buf_occupancy += bytes;\n total += bytes;\n },\n Err(ref e) if e.kind() == ErrorKind::WouldBlock => {\n return Ok(total);\n },\n Err(e) => return Err(e),\n };\n }\n }\n\n /// Write the given message directly into the TcpStream. Returns `Err` variant if there\n /// is a problem serializing or writing the message. The call returns Ok(()) once the bytes\n /// are entirely written to the stream.\n pub fn send(&mut self, m: &M) -> Result<(), SendError> {\n \tself.send_packed(\n \t\t& PackedMessage::new(m)?\n \t)?;\n \tOk(())\n }\n\n /// See `send`. This variant can be useful to\n /// avoid the overhead of repeatedly packing a message for whatever reason, eg: sending\n /// the same message using multiple Middleman structs. \n ///\n /// Note that this function does NOT check for internal consistency of the packed message.\n /// So, if this message was constructed by a means other than `Packed::new`, then the\n /// results may be unpredictable.\n pub fn send_packed(&mut self, msg: & PackedMessage) -> Result<(), io::Error> {\n \tself.stream.write_all(&msg.0)\n }\n\n /// Conume an iterator over some Message structs, sending them all in the order traversed (see `send`).\n /// Returns (a,b) where a gives the total number of messages sent successfully and where b is Ok if\n /// nothing goes wrong and an error otherwise. In the event of the first error, no more messages will be sent.\n pub fn send_all<'m, I, M>(&'m mut self, msg_iter: I) -> (usize, Result<(), SendError>) \n where \n M: Message + 'm,\n I: Iterator,\n {\n let mut total = 0;\n for msg in msg_iter {\n match self.send(msg) {\n Ok(_) => total += 1,\n Err(e) => return (total, Err(e)),\n }\n }\n (total, Ok(()))\n }\n\n /// See `send_all` and `send_packed`. This uses the message iterator from the former and\n /// the packed messages from the latter. \n pub fn send_all_packed<'m, I>(&'m mut self, packed_msg_iter: I) -> (usize, Result<(), io::Error>) \n where \n I: Iterator,\n {\n let mut total = 0;\n for msg in packed_msg_iter {\n match self.send_packed(msg) {\n Ok(_) => total += 1,\n Err(e) => return (total, Err(e)),\n }\n }\n (total, Ok(()))\n }\n\n /// Attempt to dedserialize some data in the receiving buffer into a single \n /// complete structure with the given type M. If there is insufficient data\n /// at the moment, Ok(None) is returned. \n ///\n /// As the type is provided by the reader, it is possible for the sent\n /// message to be misinterpreted as a different type. At best, this is detected\n /// by a failure in deserialization. If an error occurs, the data is not consumed\n /// from the Middleman. Subsequent reads will operate on the same data.\n ///\n /// NOTE: The correctness of this call depends on the sender sending an _internally consistent_\n /// `PackedMessage`. If you (or the sender) are manually manipulating the internal state of \n /// sent messages this may cause errors for the receiver. If you are sticking to the Middleman API\n /// and treating each `PackedMessage` as a black box, everything should be fine.\n pub fn recv(&mut self) -> Result, RecvError> {\n \tself.read_in()?;\n self.check_payload();\n if let Some(pb) = self.payload_bytes {\n let buf_end = pb as usize + 4;\n if self.buf_occupancy >= buf_end {\n let decoded: M = bincode::deserialize(\n &self.buf[4..buf_end]\n )?;\n self.payload_bytes = None;\n self.buf.drain(0..buf_end);\n self.buf_occupancy -= buf_end;\n return Ok(Some(decoded))\n }\n }\n Ok(None)\n }\n\n /// See `recv`. Will repeatedly call recv() until the next message is not yet ready. \n /// Recevied messages are placed into the buffer `dest_vector`. The return result is (a,b)\n /// where a is the total number of message successfully received and where b is OK(()) if all goes well\n /// and some Err otherwise. In the event of the first error, the call will return and not receive any further. \n pub fn recv_all_into(&mut self, dest_vector: &mut Vec) -> (usize, Result<(), RecvError>) {\n let mut total = 0;\n loop {\n match self.recv::() {\n Ok(None) => return (total, Ok(())),\n Ok(Some(msg)) => { dest_vector.push(msg); total += 1; },\n Err(e) => return (total, Err(e)),\n };\n }\n }\n\n /// Hijack the mio event loop, reading and writing to the socket as polling allows.\n /// Events not related to the recv() of this middleman (determined from the provided mio::Token)\n /// are pushed into the provided extra_events vector. Returns Ok(Some(_)) if a\n /// message was successfully received. May return Ok(None) if the user provides as timeout some \n // non-none Duration. Returns Err(_) if something goes wrong with reading from the socket or\n /// deserializing the message. See try_recv for more information.\n\n /// WARNING: The user should take care to iterate over these events also, as without them all the\n /// Evented objects registered with the provided poll object might experience lost wakeups.\n /// It is suggested that in the event of any recv_blocking calls in your loop, you extend the event\n /// loop with a drain() on the same vector passed here as extra_events (using the iterator chain function, for example.)\n pub fn recv_blocking(&mut self,\n poll: &Poll,\n events: &mut Events,\n my_tok: Token,\n extra_events: &mut Vec,\n mut timeout: Option) -> Result, RecvError> {\n\n if let Some(msg) = self.recv::()? {\n // trivial case.\n // message was already sitting in the buffer.\n return Ok(Some(msg));\n }\n let started_at = time::Instant::now();\n let mut res = None;\n loop {\n for event in events.iter() {\n let tok = event.token();\n if res.is_none() && tok == my_tok {\n \tif ! event.readiness().is_readable() {\n \t\tcontinue;\n \t}\n // event is relevant!\n self.read_in()?;\n match self.recv::() {\n Ok(Some(msg)) => {\n // got a message!\n res = Some(msg);\n },\n Ok(None) => (),\n Err(e) => return Err(e),\n } \n } else {\n extra_events.push(event);\n }\n }\n if let Some(msg) = res {\n // message ready to go. Exiting loop\n return Ok(Some(msg));\n } else {\n poll.poll(events, timeout).expect(\"poll() failed inside `recv_blocking()`\");\n if let Some(t) = timeout {\n // update remaining timeout\n let since = started_at.elapsed();\n if since >= t {\n // ran out of time\n return Ok(None); \n }\n timeout = Some(t-since);\n }\n }\n }\n }\n\n\n\n /// See `recv_blocking`. This function is intended as an alternative for use\n /// for cases where it is _certain_ that this Middleman is the only registered `mio::Evented`\n /// for the provided `Poll` and `Events` objects. Thus, the call _WILL NOT CHECK_ the token at all,\n /// presuming that all events are associated with this middleman.\n pub fn recv_blocking_solo(&mut self,\n poll: &Poll,\n events: &mut Events,\n mut timeout: Option) -> Result, RecvError> {\n\n if let Some(msg) = self.recv::()? {\n // trivial case.\n // message was already sitting in the buffer.\n return Ok(Some(msg));\n }\n let started_at = time::Instant::now();\n loop {\n for event in events.iter() {\n if event.readiness().is_readable(){\n // event is relevant!\n self.read_in()?;\n match self.recv::() {\n Ok(Some(msg)) => return Ok(Some(msg)),\n Ok(None) => (),\n Err(e) => return Err(e),\n } \n }\n }\n poll.poll(events, timeout).expect(\"poll() failed inside `recv_blocking_solo()`\");\n if let Some(t) = timeout {\n // update remaining timeout\n let since = started_at.elapsed();\n if since >= t {\n // ran out of time\n return Ok(None); \n }\n timeout = Some(t-since);\n }\n }\n }\n\n /// Similar to `recv_all_into`, but rather than storing each received message 'm',\n /// the provided function is called with arguments (self, m) where self is `&mut self`.\n /// This allows for ergonomic utility of the received messages using a closure.\n pub fn recv_all_map(&mut self, mut func: F) -> (usize, Result<(), RecvError>)\n where M: Message, F: FnMut(&mut Self, M) + Sized {\n let mut total = 0;\n loop {\n match self.recv::() {\n Ok(None) => return (total, Ok(())),\n Ok(Some(msg)) => { total += 1; func(self, msg) },\n Err(e) => return (total, Err(e)),\n };\n }\n }\n\n /// Combination of `recv_all_map` and `recv_packed`.\n pub fn recv_all_packed_map(&mut self, mut func: F) -> (usize, Result<(), RecvError>)\n where F: FnMut(&mut Self, PackedMessage) + Sized {\n let mut total = 0;\n loop {\n match self.recv_packed() {\n Ok(None) => return (total, Ok(())),\n Ok(Some(packed)) => { total += 1; func(self, packed) },\n Err(e) => return (total, Err(e)),\n };\n }\n }\n\n /// Similar to `recv`, except builds (instead of some M: Message), a `PackedMessage` object.\n /// These packed messages can be deserialized later, sent on the line without knowledge of the \n /// message type etc.\n pub fn recv_packed(&mut self) -> Result, RecvError> {\n \tself.read_in()?;\n self.check_payload();\n if let Some(pb) = self.payload_bytes {\n let buf_end = pb as usize + 4;\n if self.buf_occupancy >= buf_end {\n \tlet mut vec = self.buf.drain(0..buf_end)\n \t.collect::>();\n self.payload_bytes = None;\n self.buf_occupancy -= buf_end;\n return Ok(Some(PackedMessage(vec)))\n }\n }\n Ok(None)\n }\n\n /// Similar to `recv_packed`, but the potentially-read bytes are not actually removed\n /// from the stream. The message will _still be there_.\n pub fn peek_packed(&mut self) -> Result, RecvError> {\n if let Some(pb) = self.payload_bytes {\n let buf_end = pb as usize + 4;\n if self.buf_occupancy >= buf_end {\n return Ok(\n Some(\n PackedMessage::from_raw(\n self.buf[4..buf_end].to_vec()\n )\n )\n )\n }\n }\n Ok(None)\n }\n}\n\n\n\n/// This structure represents the serialized form of some `Message`-implementing structure.\n/// Dealing with a PackedMessage may be suitable when:\n/// (1) You need to send/store/receive a message but don't need to actually _use_ it yourself.\n/// (2) You want to serialize a message once, and send it multiple times.\n/// (3) You want to read and discard a message whose type is unknown.\n///\n/// NOTE: The packed message maps 1:1 with the bytes that travel over the TcpStream. As such,\n/// packed messages also contain the 4-byte length preable. The user is discocuraged from\n/// manipulating the contents of a packed message. The `recv` statement relies on consistency\n/// of packed messages\npub struct PackedMessage(Vec);\nimpl PackedMessage {\n\n /// Create a new PakcedMessage from the given `Message`-implementing struct\n pub fn new(m: &M) -> Result {\n let m_len: usize = bincode::serialized_size(&m)? as usize;\n if m_len > ::std::u32::MAX as usize {\n return Err(PackingError::TooBigToRepresent);\n }\n let tot_len = m_len+4;\n let mut vec = Vec::with_capacity(tot_len);\n vec.resize(tot_len, 0u8);\n bincode::serialize_into(&mut vec[0..4], &(m_len as u32))?;\n bincode::serialize_into(&mut vec[4..tot_len], m)?;\n Ok(PackedMessage(vec))\n }\n\n /// Attempt to unpack this Packedmessage given a type hint. This may fail if the \n /// PackedMessage isn't internally consistent or the type doesn't match that\n /// of the type used for serialization.\n\tpub fn unpack(&self) -> Result> {\n bincode::deserialize(&self.0[4..])\n\t}\n\n /// Unwrap the byte buffer comprising this PackedMessage\n #[inline] pub fn into_raw(self) -> Vec { self.0 }\n\n /// Accept the given byte buffer as the basis for a PackedMessage\n ///\n /// WARNING: Use this at your own risk! The `recv` functions and their variants rely on\n /// the correct contents of messages to work correcty.\n ///\n /// NOTE: The first 4 bytes of a the buffer are used to store the length of the payload.\n #[inline] pub fn from_raw(v: Vec) -> Self { PackedMessage(v) }\n\n /// Return the number of bytes this packed message contains. Maps 1:1 with\n /// the bit complexity of the message sent over the network.\n #[inline] pub fn byte_len(&self) -> usize { self.0.len() }\n\n /// Acquire an immutable reference to the internal buffer of the packed message.\n #[inline] pub fn get_raw(&self) -> &Vec { &self.0 }\n\n /// Acquire a mutable reference to the internal buffer of the packed message.\n ///\n /// WARNING: Contents of a PackedMessage represent a delicata internal state. Sending an\n /// internally inconsistent PackedMessage will compromise the connection. Use at your own risk!\n #[inline] pub fn get_mut_raw(&mut self) -> &mut Vec { &mut self.0 }\n}\n\n\n\nimpl Evented for Middleman {\n fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt)\n -> io::Result<()> {\n self.stream.register(poll, token, interest, opts)\n }\n\n fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt)\n -> io::Result<()> {\n self.stream.reregister(poll, token, interest, opts)\n }\n\n fn deregister(&self, poll: &Poll) -> io::Result<()> {\n self.stream.deregister(poll)\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":192,"cells":{"blob_id":{"kind":"string","value":"534738c930cb9798e38a845fb74c54ebbf1b5704"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"gengteng/impl-leetcode-for-rust"},"path":{"kind":"string","value":"/src/three_sum.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1618,"string":"1,618"},"score":{"kind":"number","value":3.859375,"string":"3.859375"},"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":"/// # 15. 3Sum\n///\n/// Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.\n///\n/// # Note:\n///\n/// The solution set must not contain duplicate triplets.\n///\n/// # Example:\n///\n/// Given array nums = [-1, 0, 1, 2, -1, -4],\n///\n/// A solution set is:\n/// [\n/// [-1, 0, 1],\n/// [-1, -1, 2]\n/// ]\n///\nuse std::collections::HashSet;\n\npub trait ThreeSum {\n fn three_sum(nums: &[i32]) -> HashSet<[i32;3]>;\n}\n\npub struct Solution1;\n\nimpl ThreeSum for Solution1 {\n fn three_sum(nums: &[i32]) -> HashSet<[i32;3]> {\n let mut result = HashSet::new();\n\n for (i, a) in nums.iter().enumerate() {\n for (j, b) in nums.iter().skip(i + 1).enumerate() {\n for c in nums.iter().skip(i + j + 2) {\n if a + b + c == 0 {\n let mut v = [*a, *b, *c];\n v.sort();\n result.insert(v);\n }\n }\n }\n }\n\n result\n }\n}\n\n#[cfg(test)]\nmod test {\n use super::ThreeSum;\n use test::Bencher;\n\n use super::Solution1;\n #[test]\n fn test_solution1() {\n use std::collections::HashSet;\n\n assert_eq!(Solution1::three_sum(&[-1, 0, 1, 2, -1, -4]), {\n let mut result = HashSet::new();\n result.insert([-1, 0, 1]);\n result.insert([-1, -1, 2]);\n result\n });\n }\n\n #[bench]\n fn bench_solution1(b: &mut Bencher) {\n b.iter(|| Solution1::three_sum(&[-1, 0, 1, 2, -1, -4]));\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":193,"cells":{"blob_id":{"kind":"string","value":"025a08ef28a850e3a7ede38d3f00a1b48980fc47"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"rusty-ecma/resast"},"path":{"kind":"string","value":"/src/pat.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2954,"string":"2,954"},"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":"use crate::expr::{Expr, Prop};\nuse crate::{Ident, IntoAllocated};\n\n#[cfg(feature = \"serde\")]\nuse serde::{Deserialize, Serialize};\n\n/// All of the different ways you can declare an identifier\n/// and/or value\n#[derive(Debug, Clone, PartialEq)]\n#[cfg_attr(feature = \"serde\", derive(Deserialize, Serialize))]\npub enum Pat {\n Ident(Ident),\n Obj(ObjPat),\n Array(Vec>>),\n RestElement(Box>),\n Assign(AssignPat),\n}\n\nimpl IntoAllocated for Pat\nwhere\n T: ToString,\n{\n type Allocated = Pat;\n\n fn into_allocated(self) -> Self::Allocated {\n match self {\n Pat::Ident(inner) => Pat::Ident(inner.into_allocated()),\n Pat::Obj(inner) => Pat::Obj(inner.into_iter().map(|a| a.into_allocated()).collect()),\n Pat::Array(inner) => Pat::Array(\n inner\n .into_iter()\n .map(|o| o.map(|a| a.into_allocated()))\n .collect(),\n ),\n Pat::RestElement(inner) => Pat::RestElement(inner.into_allocated()),\n Pat::Assign(inner) => Pat::Assign(inner.into_allocated()),\n }\n }\n}\n\nimpl Pat {\n pub fn ident_from(inner: T) -> Self {\n Self::Ident(Ident { name: inner })\n }\n}\n\n#[derive(PartialEq, Debug, Clone)]\n#[cfg_attr(feature = \"serde\", derive(Deserialize, Serialize))]\npub enum ArrayPatPart {\n Pat(Pat),\n Expr(Expr),\n}\n\nimpl IntoAllocated for ArrayPatPart\nwhere\n T: ToString,\n{\n type Allocated = ArrayPatPart;\n\n fn into_allocated(self) -> Self::Allocated {\n match self {\n ArrayPatPart::Pat(inner) => ArrayPatPart::Pat(inner.into_allocated()),\n ArrayPatPart::Expr(inner) => ArrayPatPart::Expr(inner.into_allocated()),\n }\n }\n}\n\n/// similar to an `ObjectExpr`\npub type ObjPat = Vec>;\n/// A single part of an ObjectPat\n#[derive(PartialEq, Debug, Clone)]\n#[cfg_attr(feature = \"serde\", derive(Deserialize, Serialize))]\npub enum ObjPatPart {\n Assign(Prop),\n Rest(Box>),\n}\n\nimpl IntoAllocated for ObjPatPart\nwhere\n T: ToString,\n{\n type Allocated = ObjPatPart;\n\n fn into_allocated(self) -> Self::Allocated {\n match self {\n ObjPatPart::Assign(inner) => ObjPatPart::Assign(inner.into_allocated()),\n ObjPatPart::Rest(inner) => ObjPatPart::Rest(inner.into_allocated()),\n }\n }\n}\n\n/// An assignment as a pattern\n#[derive(Debug, Clone, PartialEq)]\n#[cfg_attr(feature = \"serde\", derive(Deserialize, Serialize))]\npub struct AssignPat {\n pub left: Box>,\n pub right: Box>,\n}\n\nimpl IntoAllocated for AssignPat\nwhere\n T: ToString,\n{\n type Allocated = AssignPat;\n\n fn into_allocated(self) -> Self::Allocated {\n AssignPat {\n left: self.left.into_allocated(),\n right: self.right.into_allocated(),\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":194,"cells":{"blob_id":{"kind":"string","value":"2eb8609523eddcfcf9aaec109460477cbf7759ea"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"dan-sf/advent_of_code"},"path":{"kind":"string","value":"/2018/day2/solution2.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1131,"string":"1,131"},"score":{"kind":"number","value":3.21875,"string":"3.21875"},"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;\nuse std::io;\nuse std::io::BufRead;\n\nfn get_common_chars(box_one: &String, box_two: &String) -> String {\n box_one.chars()\n .zip(box_two.chars())\n .filter(|ch| ch.0 == ch.1)\n .map(|ch| ch.0)\n .collect()\n}\n\nfn find_common_id() -> Option {\n let input = fs::File::open(\"input.txt\")\n .expect(\"Something went wrong reading the file\");\n let reader = io::BufReader::new(input);\n let mut box_ids: Vec = reader.lines().map(|l| l.unwrap()).collect();\n box_ids.sort();\n\n for i in 0..box_ids.len() {\n let mut diff = 0;\n if i != box_ids.len() - 1 {\n for (a, b) in box_ids[i].chars().zip(box_ids[i+1].chars()) {\n if a != b {\n diff += 1;\n }\n }\n if diff == 1 {\n return Some(get_common_chars(&box_ids[i], &box_ids[i+1]));\n }\n }\n }\n None\n}\n\nfn main() {\n println!(\"Common letters in the box ids: {}\",\n match find_common_id() {\n Some(s) => s,\n None => \"NA\".to_string()\n });\n}\n\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":195,"cells":{"blob_id":{"kind":"string","value":"e13c33e5a575f4ab435f01914a81c74b1033ae9a"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"xiaolang315/json-schema-to-c"},"path":{"kind":"string","value":"/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1037,"string":"1,037"},"score":{"kind":"number","value":2.90625,"string":"2.90625"},"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::process::Command;\nuse std::fs::read_to_string;\nuse std::fs::write;\nuse serde_json::from_str;\nuse serde_json::{Value};\n\nfn make_str(body:String)->String {\n let head = String::from(r#\"\n#ifdef __cplusplus\nextern \"C\" {\n#endif \"#);\n let tail = String::from(r#\"\n#ifdef __cplusplus\n}\n#endif \n\n\"#);\n return head + &body + &tail;\n}\n\nfn main() {\n // let mut echo_hello = Command::new(\"sh\");\n // let ret = echo_hello.arg(\"-c\").arg(\"ls\").output();\n // println!(\"结果:{:?}\",ret);\n // let file = File::open( \"./src/schema.json\").unwrap();\n // println!(\"文件打开成功:{:?}\",file);\n\n let contents:String = read_to_string(\"./src/schema.json\").unwrap();\n let v: Value = from_str(&contents).unwrap();\n\n println!(\"Please call {} at the number {}\", v[\"type\"], v[\"id\"]);\n\n let body = String::from(r#\"\n\ntypedef struct All{\n char name[100];\n int value;\n}All ;\n\nAll parser_print(const char* str);\n\n \"#);\n \n write(\"./src/demo.h\", make_str(body))\n .unwrap();\n}\n\n#[test]\nfn test(){\n\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":196,"cells":{"blob_id":{"kind":"string","value":"27c9d7ded1cb3ebf884c97949751989c6f27c507"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"rudib/axess"},"path":{"kind":"string","value":"/axess_gui/src/windows/keyboard.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":6231,"string":"6,231"},"score":{"kind":"number","value":3.109375,"string":"3.109375"},"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::{borrow::Cow, fmt::Display};\n\nuse axess_core::payload::{DeviceState, UiPayload};\n\nuse packed_struct::PrimitiveEnum;\n\nuse crate::config::AxessConfiguration;\n\n#[derive(Debug, Copy, Clone)]\npub enum UiEvent {\n KeyDown(usize, u32),\n KeyUp(usize, u32)\n}\n\n#[derive(Default, Debug)]\npub struct KeyboardState {\n ctrl: bool\n}\n\n#[derive(Debug, Copy, Clone)]\npub enum KeyboardCombination {\n Key(usize),\n CtrlKey(usize)\n}\n\nimpl KeyboardState {\n pub fn handle_event(&mut self, ev: &UiEvent) -> Option {\n const CTRL: usize = 0x11;\n //const ALT: usize = 0x12;\n\n match *ev {\n UiEvent::KeyDown(CTRL, _) => {\n self.ctrl = true;\n }\n UiEvent::KeyUp(CTRL, _) => {\n self.ctrl = false;\n }\n UiEvent::KeyDown(k, _) => {\n // todo: ignore repeats?\n\n if self.ctrl {\n return Some(KeyboardCombination::CtrlKey(k));\n } else {\n return Some(KeyboardCombination::Key(k));\n }\n },\n UiEvent::KeyUp(_, _) => {}\n }\n\n None\n }\n}\n\n\n#[derive(Debug, Copy, Clone, PartialEq, PrimitiveEnum)]\npub enum Keys {\n Enter = 13,\n PageUp = 33,\n PageDown = 34,\n Space = 32,\n Tab = 9,\n Number0 = 48,\n Number1 = 49,\n Number2 = 50,\n Number3 = 51,\n Number4 = 52,\n Number5 = 53,\n Number6 = 54,\n Number7 = 55,\n Number8 = 56, \n Number9 = 57,\n Fn1 = 0x70,\n Fn2 = 0x71,\n Fn3 = 0x72,\n Fn4 = 0x73,\n Fn5 = 0x74,\n Fn6 = 0x75,\n Fn7 = 0x76,\n Fn8 = 0x77,\n Fn9 = 0x78,\n Fn10 = 0x79,\n Fn11 = 0x7A,\n Fn12 = 0x7B,\n Fn13 = 0x7C,\n Fn14 = 0x7D,\n Fn15 = 0x7E,\n Fn16 = 0x7F\n}\n\nimpl Display for Keys {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n let str = match self {\n Keys::Number0 => \"0\",\n Keys::Number1 => \"1\",\n Keys::Number2 => \"2\",\n Keys::Number3 => \"3\",\n Keys::Number4 => \"4\",\n Keys::Number5 => \"5\",\n Keys::Number6 => \"6\",\n Keys::Number7 => \"7\",\n Keys::Number8 => \"8\",\n Keys::Number9 => \"9\",\n Keys::PageUp => \"Page Up\",\n Keys::PageDown => \"Page Down\",\n Keys::Fn1 => \"F1\",\n Keys::Fn2 => \"F2\",\n Keys::Fn3 => \"F3\",\n Keys::Fn4 => \"F4\",\n Keys::Fn5 => \"F5\",\n Keys::Fn6 => \"F6\",\n Keys::Fn7 => \"F7\",\n Keys::Fn8 => \"F8\",\n Keys::Fn9 => \"F9\",\n Keys::Fn10 => \"F10\",\n Keys::Fn11 => \"F11\",\n Keys::Fn12 => \"F12\",\n Keys::Fn13 => \"F13\",\n Keys::Fn14 => \"F14\",\n Keys::Fn15 => \"F15\",\n Keys::Fn16 => \"F16\",\n _ => { return f.write_fmt(format_args!(\"{:?}\", self)); }\n };\n f.write_str(str)\n }\n}\n\n#[derive(Debug, Clone)]\npub struct KeyboardShortcut {\n pub key: KeyboardShortcutKey,\n pub command_description: Cow<'static, str>,\n pub command: ShortcutCommand\n}\n\n#[derive(Debug, Copy, Clone, PartialEq)]\npub enum KeyboardShortcutKey {\n Key(Keys),\n CtrlKey(Keys)\n}\n\nimpl Display for KeyboardShortcutKey {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n match self {\n KeyboardShortcutKey::Key(k) => {\n k.fmt(f)\n }\n KeyboardShortcutKey::CtrlKey(k) => {\n f.write_str(\"Ctrl + \")?;\n k.fmt(f)\n }\n }\n }\n}\n\n#[derive(Debug, Clone)]\npub enum ShortcutCommand {\n UiPayload(UiPayload),\n SelectPresetOrScene\n}\n\npub fn get_main_keyboard_shortcuts(config: &AxessConfiguration) -> Vec {\n let mut s = vec![\n KeyboardShortcut {\n key: KeyboardShortcutKey::Key(Keys::Enter),\n command_description: \"Select the preset or scene\".into(),\n command: ShortcutCommand::SelectPresetOrScene\n }\n ];\n\n if config.keyboard_shortcuts_axe_edit {\n\n s.push(KeyboardShortcut {\n key: KeyboardShortcutKey::CtrlKey(Keys::PageUp),\n command_description: \"Preset Up\".into(),\n command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: 1 }))\n });\n\n s.push(KeyboardShortcut {\n key: KeyboardShortcutKey::CtrlKey(Keys::PageDown),\n command_description: \"Preset Down\".into(),\n command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: -1 }))\n });\n\n for i in 0..8 {\n let key = Keys::from_primitive(Keys::Number1.to_primitive() + i);\n if let Some(key) = key {\n s.push(KeyboardShortcut {\n key: KeyboardShortcutKey::CtrlKey(key),\n command_description: format!(\"Select Scene {}\", i + 1).into(),\n command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::SetScene { scene: i }))\n });\n }\n }\n\n }\n\n if config.keyboard_shortcuts_presets_and_scenes_function_keys {\n for i in 0..8 {\n let key = Keys::from_primitive(Keys::Fn1.to_primitive() + i);\n if let Some(key) = key {\n s.push(KeyboardShortcut {\n key: KeyboardShortcutKey::Key(key),\n command_description: format!(\"Select Scene {}\", i + 1).into(),\n command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::SetScene { scene: i }))\n });\n }\n }\n\n s.push(KeyboardShortcut {\n key: KeyboardShortcutKey::Key(Keys::Fn11),\n command_description: \"Preset Down\".into(),\n command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: -1 }))\n });\n\n s.push(KeyboardShortcut {\n key: KeyboardShortcutKey::Key(Keys::Fn12),\n command_description: \"Preset Up\".into(),\n command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: 1 }))\n });\n }\n \n s\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":197,"cells":{"blob_id":{"kind":"string","value":"d8f7063a021efc499a4e1676623450e539b4a860"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"simon-whitehead/tetrs"},"path":{"kind":"string","value":"/src/game/scoring/score.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1983,"string":"1,983"},"score":{"kind":"number","value":2.859375,"string":"2.859375"},"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 piston_window::{Graphics, Transformed};\nuse piston_window::character::CharacterCache;\n\nuse game::config::Config;\nuse game::render_options::RenderOptions;\n\npub struct Score {\n score: u32,\n location: (f64, f64),\n color: [f32; 4],\n font_size: u32,\n}\n\nimpl Score {\n pub fn new(config: &Config) -> Score {\n Score {\n score: 0,\n location: (320.0, 29.0),\n color: config.ui_color,\n font_size: 16,\n }\n }\n\n pub fn add(&mut self, value: u32) {\n self.score += value;\n }\n\n pub fn render<'a, C, G>(&self, options: &mut RenderOptions<'a, G, C>)\n where C: CharacterCache,\n G: Graphics::Texture>\n {\n let score_label_transform = options.context\n .transform\n .trans(self.location.0 as f64, self.location.1 as f64);\n\n let score_number_transform = options.context\n .transform\n .trans(self.location.0 as f64,\n self.location.1 + (self.font_size + (self.font_size / 3)) as f64);\n\n let score = format!(\"{}\", self.score);\n\n ::piston_window::Text::new_color(self.color, self.font_size - (self.font_size / 3))\n .draw(\"Score\",\n options.character_cache,\n &options.context.draw_state,\n score_label_transform,\n options.graphics);\n\n ::piston_window::Text::new_color(self.color, self.font_size).draw(&score[..],\n options.character_cache,\n &options.context\n .draw_state,\n score_number_transform,\n options.graphics);\n }\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":198,"cells":{"blob_id":{"kind":"string","value":"fe91a6ee5a258a2447a117eae677decb355d72c6"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"enso-org/enso"},"path":{"kind":"string","value":"/lib/rust/ensogl/component/text/src/buffer/rope/formatted.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2010,"string":"2,010"},"score":{"kind":"number","value":3.375,"string":"3.375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["AGPL-3.0-only","Apache-2.0","AGPL-3.0-or-later"],"string":"[\n \"AGPL-3.0-only\",\n \"Apache-2.0\",\n \"AGPL-3.0-or-later\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"//! A rope (efficient text representation) with formatting information.\n\nuse crate::prelude::*;\n\nuse crate::buffer::formatting::Formatting;\nuse crate::buffer::formatting::FormattingCell;\n\nuse enso_text::Rope;\nuse enso_text::RopeCell;\n\n\n\n// =====================\n// === FormattedRope ===\n// =====================\n\n/// A rope (efficient text representation) with formatting information.\n#[derive(Clone, CloneRef, Debug, Default, Deref)]\npub struct FormattedRope {\n data: Rc,\n}\n\nimpl FormattedRope {\n /// Constructor.\n pub fn new() -> Self {\n default()\n }\n\n /// Replace the content of the buffer with the provided text.\n pub fn replace(&self, range: impl enso_text::RangeBounds, text: impl Into) {\n let text = text.into();\n let range = self.crop_byte_range(range);\n let size = text.last_byte_index();\n self.text.replace(range, text);\n self.formatting.set_resize_with_default(range, size);\n }\n}\n\n\n\n// =========================\n// === FormattedRopeData ===\n// =========================\n\n/// Internal data of `FormattedRope`.\n#[derive(Debug, Default, Deref)]\npub struct FormattedRopeData {\n #[deref]\n pub(crate) text: RopeCell,\n pub(crate) formatting: FormattingCell,\n}\n\nimpl FormattedRopeData {\n /// Constructor.\n pub fn new() -> Self {\n default()\n }\n\n /// Rope getter.\n pub fn text(&self) -> Rope {\n self.text.get()\n }\n\n /// Rope setter.\n pub fn set_text(&self, text: impl Into) {\n self.text.set(text);\n }\n\n /// Formatting getter.\n pub fn style(&self) -> Formatting {\n self.formatting.get()\n }\n\n /// Formatting setter.\n pub fn set_style(&self, style: Formatting) {\n self.formatting.set(style)\n }\n\n /// Query style information for the provided range.\n pub fn sub_style(&self, range: impl enso_text::RangeBounds) -> Formatting {\n let range = self.crop_byte_range(range);\n self.formatting.sub(range)\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":199,"cells":{"blob_id":{"kind":"string","value":"3df1d52edb3fc2c5ab768b76f40b288745bc7613"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"rust-cc/rcmath"},"path":{"kind":"string","value":"/src/utils.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":576,"string":"576"},"score":{"kind":"number","value":3.265625,"string":"3.265625"},"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":"#[derive(Debug)]\npub struct BitIterator {\n t: E,\n n: usize,\n}\n\nimpl> BitIterator {\n pub fn new(t: E) -> Self {\n let n = t.as_ref().len() * 64;\n\n BitIterator { t, n }\n }\n}\n\nimpl> Iterator for BitIterator {\n type Item = bool;\n\n fn next(&mut self) -> Option {\n if self.n == 0 {\n None\n } else {\n self.n -= 1;\n let part = self.n / 64;\n let bit = self.n - (64 * part);\n\n Some(self.t.as_ref()[part] & (1 << bit) > 0)\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":1,"numItemsPerPage":100,"numTotalItems":1135379,"offset":100,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NjE0NTgxMywic3ViIjoiL2RhdGFzZXRzL2hvbmdsaXU5OTAzL3N0YWNrX2VkdV9ydXN0IiwiZXhwIjoxNzU2MTQ5NDEzLCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.2i_0OALjy1unS9fVDQ0nE2Kx6kzKef67iBniYWE2ZA-HwW6df5OpwTYajqTiH9DDCph-WrJVLGxSVr4H6ZnJBA","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
50c35dc00a2185051fd83981c0bc6e3ecd1f3b95
Rust
2color/prisma-engines
/libs/datamodel/core/tests/attributes/unique.rs
UTF-8
7,448
2.78125
3
[ "Apache-2.0" ]
permissive
#![allow(non_snake_case)] use datamodel::{ast::Span, diagnostics::*, render_datamodel_to_string, IndexDefinition, IndexType}; use crate::common::*; #[test] fn basic_unique_index_must_work() { let dml = r#" model User { id Int @id firstName String lastName String @@unique([firstName,lastName]) } "#; let schema = parse(dml); let user_model = schema.assert_has_model("User"); user_model.assert_has_index(IndexDefinition { name: None, fields: vec!["firstName".to_string(), "lastName".to_string()], tpe: IndexType::Unique, }); } #[test] fn multiple_unnamed_arguments_must_error() { let dml = r#" model User { id Int @id firstName String lastName String @@unique(firstName,lastName) } "#; let errors = parse_error(dml); errors.assert_is(DatamodelError::new_attribute_validation_error("You provided multiple unnamed arguments. This is not possible. Did you forget the brackets? Did you mean `[firstName, lastName]`?", "unique", Span::new(108, 134))); } #[test] fn multi_field_unique_indexes_on_relation_fields_must_error_and_give_nice_error_on_inline_side() { let dml = r#" model User { id Int @id identificationId Int identification Identification @relation(fields: [identificationId], references:[id]) @@unique([identification]) } model Identification { id Int @id } "#; let errors = parse_error(dml); errors.assert_is(DatamodelError::new_model_validation_error("The unique index definition refers to the relation fields identification. Index definitions must reference only scalar fields. Did you mean `@@unique([identificationId])`?", "User",Span::new(193, 217))); } #[test] fn multi_field_unique_indexes_on_relation_fields_must_error_and_give_nice_error_on_NON_inline_side() { let dml = r#" model User { id Int @id identificationId Int identification Identification @relation(fields: [identificationId], references:[id]) } model Identification { id Int @id user User @@unique([user]) } "#; let errors = parse_error(dml); // in this case the error can't give a suggestion errors.assert_is(DatamodelError::new_model_validation_error("The unique index definition refers to the relation fields user. Index definitions must reference only scalar fields.", "Identification",Span::new(270, 284))); } #[test] fn single_field_unique_on_relation_fields_must_error_nicely_with_ONE_underlying_fields() { let dml = r#" model User { id Int @id identificationId Int identification Identification @relation(fields: [identificationId], references:[id]) @unique } model Identification { id Int @id } "#; let errors = parse_error(dml); errors.assert_is(DatamodelError::new_attribute_validation_error("The field `identification` is a relation field and cannot be marked with `unique`. Only scalar fields can be made unique. Did you mean to put it on `identificationId`?", "unique", Span::new(183, 189))); } #[test] fn single_field_unique_on_relation_fields_must_error_nicely_with_MANY_underlying_fields() { let dml = r#" model User { id Int @id identificationId1 Int identificationId2 Int identification Identification @relation(fields: [identificationId1, identificationId2], references:[id]) @unique } model Identification { id1 Int id2 Int @@id([id1, id2]) } "#; let errors = parse_error(dml); errors.assert_is(DatamodelError::new_attribute_validation_error("The field `identification` is a relation field and cannot be marked with `unique`. Only scalar fields can be made unique. Did you mean to provide `@@unique([identificationId1, identificationId2])`?", "unique", Span::new(235, 241))); } #[test] fn single_field_unique_on_enum_field_must_work() { let dml = r#" model User { id Int @id role Role @unique } enum Role { Admin Member } "#; let schema = parse(dml); schema .assert_has_model("User") .assert_has_scalar_field("role") .assert_is_unique(true); } #[test] fn the_name_argument_must_work() { let dml = r#" model User { id Int @id firstName String lastName String @@unique([firstName,lastName], name: "MyIndexName") } "#; let schema = parse(dml); let user_model = schema.assert_has_model("User"); user_model.assert_has_index(IndexDefinition { name: Some("MyIndexName".to_string()), fields: vec!["firstName".to_string(), "lastName".to_string()], tpe: IndexType::Unique, }); } #[test] fn multiple_unique_must_work() { let dml = r#" model User { id Int @id firstName String lastName String @@unique([firstName,lastName]) @@unique([firstName,lastName], name: "MyIndexName") } "#; let schema = parse(dml); let user_model = schema.assert_has_model("User"); user_model.assert_has_index(IndexDefinition { name: None, fields: vec!["firstName".to_string(), "lastName".to_string()], tpe: IndexType::Unique, }); user_model.assert_has_index(IndexDefinition { name: Some("MyIndexName".to_string()), fields: vec!["firstName".to_string(), "lastName".to_string()], tpe: IndexType::Unique, }); } #[test] fn multi_field_unique_indexes_on_enum_fields_must_work() { let dml = r#" model User { id Int @id role Role @@unique([role]) } enum Role { Admin Member } "#; let schema = parse(dml); let user_model = schema.assert_has_model("User"); user_model.assert_has_index(IndexDefinition { name: None, fields: vec!["role".to_string()], tpe: IndexType::Unique, }); } #[test] fn must_error_when_unknown_fields_are_used() { let dml = r#" model User { id Int @id @@unique([foo,bar]) } "#; let errors = parse_error(dml); errors.assert_is(DatamodelError::new_model_validation_error( "The unique index definition refers to the unknown fields foo, bar.", "User", Span::new(48, 65), )); } #[test] fn must_error_when_using_the_same_field_multiple_times() { let dml = r#" model User { id Int @id email String @unique @@unique([email, email]) } "#; let errors = parse_error(dml); errors.assert_is(DatamodelError::new_model_validation_error( "The unique index definition refers to the fields email multiple times.", "User", Span::new(83, 105), )); } #[test] fn unique_attributes_must_serialize_to_valid_dml() { let dml = r#" model User { id Int @id firstName String lastName String @@unique([firstName,lastName], name: "customName") } "#; let schema = parse(dml); assert!(datamodel::parse_datamodel(&render_datamodel_to_string(&schema)).is_ok()); }
true
8191a2bed1521315ebc2a50ba20e0386c06efd99
Rust
waywardmonkeys/app_units
/src/app_unit.rs
UTF-8
10,104
3.171875
3
[]
no_license
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use num_traits::Zero; use serde::de::{Deserialize, Deserializer}; use serde::ser::{Serialize, Serializer}; use std::default::Default; use std::fmt; use std::i32; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, Sub, SubAssign}; /// The number of app units in a pixel. pub const AU_PER_PX: i32 = 60; #[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord)] /// An App Unit, the fundamental unit of length in Servo. Usually /// 1/60th of a pixel (see AU_PER_PX) /// /// Please ensure that the values are between MIN_AU and MAX_AU. /// It is safe to construct invalid Au values, but it may lead to /// panics and overflows. pub struct Au(pub i32); impl<'de> Deserialize<'de> for Au { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Au, D::Error> { Ok(Au(try!(i32::deserialize(deserializer))).clamp()) } } impl Serialize for Au { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { self.0.serialize(serializer) } } impl Default for Au { #[inline] fn default() -> Au { Au(0) } } impl Zero for Au { #[inline] fn zero() -> Au { Au(0) } #[inline] fn is_zero(&self) -> bool { self.0 == 0 } } // (1 << 30) - 1 lets us add/subtract two Au and check for overflow // after the operation. Gecko uses the same min/max values pub const MAX_AU: Au = Au((1 << 30) - 1); pub const MIN_AU: Au = Au(- ((1 << 30) - 1)); impl fmt::Debug for Au { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}px", self.to_f64_px()) } } impl Add for Au { type Output = Au; #[inline] fn add(self, other: Au) -> Au { Au(self.0 + other.0).clamp() } } impl Sub for Au { type Output = Au; #[inline] fn sub(self, other: Au) -> Au { Au(self.0 - other.0).clamp() } } impl Mul<Au> for i32 { type Output = Au; #[inline] fn mul(self, other: Au) -> Au { if let Some(new) = other.0.checked_mul(self) { Au(new).clamp() } else if (self > 0) ^ (other.0 > 0) { MIN_AU } else { MAX_AU } } } impl Mul<i32> for Au { type Output = Au; #[inline] fn mul(self, other: i32) -> Au { if let Some(new) = self.0.checked_mul(other) { Au(new).clamp() } else if (self.0 > 0) ^ (other > 0) { MIN_AU } else { MAX_AU } } } impl Div for Au { type Output = i32; #[inline] fn div(self, other: Au) -> i32 { self.0 / other.0 } } impl Div<i32> for Au { type Output = Au; #[inline] fn div(self, other: i32) -> Au { Au(self.0 / other) } } impl Rem for Au { type Output = Au; #[inline] fn rem(self, other: Au) -> Au { Au(self.0 % other.0) } } impl Rem<i32> for Au { type Output = Au; #[inline] fn rem(self, other: i32) -> Au { Au(self.0 % other) } } impl Neg for Au { type Output = Au; #[inline] fn neg(self) -> Au { Au(-self.0) } } impl AddAssign for Au { #[inline] fn add_assign(&mut self, other: Au) { *self = *self + other; self.clamp_self(); } } impl SubAssign for Au { #[inline] fn sub_assign(&mut self, other: Au) { *self = *self - other; self.clamp_self(); } } impl MulAssign<i32> for Au { #[inline] fn mul_assign(&mut self, other: i32) { *self = *self * other; self.clamp_self(); } } impl DivAssign<i32> for Au { #[inline] fn div_assign(&mut self, other: i32) { *self = *self / other; self.clamp_self(); } } impl Au { /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs! #[inline] pub fn new(value: i32) -> Au { Au(value).clamp() } #[inline] fn clamp(self) -> Self { if self.0 > MAX_AU.0 { MAX_AU } else if self.0 < MIN_AU.0 { MIN_AU } else { self } } #[inline] fn clamp_self(&mut self) { *self = Au::clamp(*self) } #[inline] pub fn scale_by(self, factor: f32) -> Au { let new_float = ((self.0 as f64) * factor as f64).round(); Au::from_f64_au(new_float) } #[inline] /// Scale, but truncate (useful for viewport-relative units) pub fn scale_by_trunc(self, factor: f32) -> Au { let new_float = ((self.0 as f64) * factor as f64).trunc(); Au::from_f64_au(new_float) } #[inline] pub fn from_f64_au(float: f64) -> Self { // We *must* operate in f64. f32 isn't precise enough // to handle MAX_AU Au(float.min(MAX_AU.0 as f64) .max(MIN_AU.0 as f64) as i32) } #[inline] pub fn from_px(px: i32) -> Au { Au(px) * AU_PER_PX } /// Rounds this app unit down to the pixel towards zero and returns it. #[inline] pub fn to_px(self) -> i32 { self.0 / AU_PER_PX } /// Ceil this app unit to the appropriate pixel boundary and return it. #[inline] pub fn ceil_to_px(self) -> i32 { ((self.0 as f64) / (AU_PER_PX as f64)).ceil() as i32 } #[inline] pub fn to_nearest_px(self) -> i32 { ((self.0 as f64) / (AU_PER_PX as f64)).round() as i32 } #[inline] pub fn to_nearest_pixel(self, pixels_per_px: f32) -> f32 { ((self.0 as f32) / (AU_PER_PX as f32) * pixels_per_px).round() / pixels_per_px } #[inline] pub fn to_f32_px(self) -> f32 { (self.0 as f32) / (AU_PER_PX as f32) } #[inline] pub fn to_f64_px(self) -> f64 { (self.0 as f64) / (AU_PER_PX as f64) } #[inline] pub fn from_f32_px(px: f32) -> Au { let float = (px * AU_PER_PX as f32).round(); Au::from_f64_au(float as f64) } #[inline] pub fn from_f64_px(px: f64) -> Au { let float = (px * AU_PER_PX as f64).round(); Au::from_f64_au(float) } #[inline] pub fn abs(self) -> Self { Au(self.0.abs()) } } #[test] fn create() { assert_eq!(Au::zero(), Au(0)); assert_eq!(Au::default(), Au(0)); assert_eq!(Au::new(7), Au(7)); } #[test] fn operations() { assert_eq!(Au(7) + Au(5), Au(12)); assert_eq!(MAX_AU + Au(1), MAX_AU); assert_eq!(Au(7) - Au(5), Au(2)); assert_eq!(MIN_AU - Au(1), MIN_AU); assert_eq!(Au(7) * 5, Au(35)); assert_eq!(5 * Au(7), Au(35)); assert_eq!(MAX_AU * -1, MIN_AU); assert_eq!(MIN_AU * -1, MAX_AU); assert_eq!(-1 * MAX_AU, MIN_AU); assert_eq!(-1 * MIN_AU, MAX_AU); assert_eq!((Au(14) / 5) * 5 + Au(14) % 5, Au(14)); assert_eq!((Au(14) / Au(5)) * Au(5) + Au(14) % Au(5), Au(14)); assert_eq!(Au(35) / 5, Au(7)); assert_eq!(Au(35) % 6, Au(5)); assert_eq!(Au(35) / Au(5), 7); assert_eq!(Au(35) / Au(5), 7); assert_eq!(-Au(7), Au(-7)); } #[test] fn saturate() { let half = MAX_AU / 2; assert_eq!(half + half + half + half + half, MAX_AU); assert_eq!(-half - half - half - half - half, MIN_AU); assert_eq!(half * -10, MIN_AU); assert_eq!(-half * 10, MIN_AU); assert_eq!(half * 10, MAX_AU); assert_eq!(-half * -10, MAX_AU); } #[test] fn scale() { assert_eq!(Au(12).scale_by(1.5), Au(18)); assert_eq!(Au(12).scale_by(1.7), Au(20)); assert_eq!(Au(12).scale_by(1.8), Au(22)); assert_eq!(Au(12).scale_by_trunc(1.8), Au(21)); } #[test] fn abs() { assert_eq!(Au(-10).abs(), Au(10)); } #[test] fn convert() { assert_eq!(Au::from_px(5), Au(300)); assert_eq!(Au(300).to_px(), 5); assert_eq!(Au(330).to_px(), 5); assert_eq!(Au(350).to_px(), 5); assert_eq!(Au(360).to_px(), 6); assert_eq!(Au(300).ceil_to_px(), 5); assert_eq!(Au(310).ceil_to_px(), 6); assert_eq!(Au(330).ceil_to_px(), 6); assert_eq!(Au(350).ceil_to_px(), 6); assert_eq!(Au(360).ceil_to_px(), 6); assert_eq!(Au(300).to_nearest_px(), 5); assert_eq!(Au(310).to_nearest_px(), 5); assert_eq!(Au(330).to_nearest_px(), 6); assert_eq!(Au(350).to_nearest_px(), 6); assert_eq!(Au(360).to_nearest_px(), 6); assert_eq!(Au(60).to_nearest_pixel(2.), 1.); assert_eq!(Au(70).to_nearest_pixel(2.), 1.); assert_eq!(Au(80).to_nearest_pixel(2.), 1.5); assert_eq!(Au(90).to_nearest_pixel(2.), 1.5); assert_eq!(Au(100).to_nearest_pixel(2.), 1.5); assert_eq!(Au(110).to_nearest_pixel(2.), 2.); assert_eq!(Au(120).to_nearest_pixel(2.), 2.); assert_eq!(Au(300).to_f32_px(), 5.); assert_eq!(Au(312).to_f32_px(), 5.2); assert_eq!(Au(330).to_f32_px(), 5.5); assert_eq!(Au(348).to_f32_px(), 5.8); assert_eq!(Au(360).to_f32_px(), 6.); assert_eq!((Au(367).to_f32_px() * 1000.).round(), 6_117.); assert_eq!((Au(368).to_f32_px() * 1000.).round(), 6_133.); assert_eq!(Au(300).to_f64_px(), 5.); assert_eq!(Au(312).to_f64_px(), 5.2); assert_eq!(Au(330).to_f64_px(), 5.5); assert_eq!(Au(348).to_f64_px(), 5.8); assert_eq!(Au(360).to_f64_px(), 6.); assert_eq!((Au(367).to_f64_px() * 1000.).round(), 6_117.); assert_eq!((Au(368).to_f64_px() * 1000.).round(), 6_133.); assert_eq!(Au::from_f32_px(5.), Au(300)); assert_eq!(Au::from_f32_px(5.2), Au(312)); assert_eq!(Au::from_f32_px(5.5), Au(330)); assert_eq!(Au::from_f32_px(5.8), Au(348)); assert_eq!(Au::from_f32_px(6.), Au(360)); assert_eq!(Au::from_f32_px(6.12), Au(367)); assert_eq!(Au::from_f32_px(6.13), Au(368)); assert_eq!(Au::from_f64_px(5.), Au(300)); assert_eq!(Au::from_f64_px(5.2), Au(312)); assert_eq!(Au::from_f64_px(5.5), Au(330)); assert_eq!(Au::from_f64_px(5.8), Au(348)); assert_eq!(Au::from_f64_px(6.), Au(360)); assert_eq!(Au::from_f64_px(6.12), Au(367)); assert_eq!(Au::from_f64_px(6.13), Au(368)); }
true
97377fd1c2ef3aa928709a4a239ffc3f4d3b625d
Rust
pitpo/AdventOfCode2018
/days/day24/src/lib.rs
UTF-8
8,513
3.15625
3
[]
no_license
extern crate utils; use utils::Day; use std::cmp::Ordering; use std::collections::HashMap; pub struct Day24 { groups: Vec<Group>, } #[derive(Debug, Clone)] struct Group { is_foe: bool, units: usize, hp: usize, weak: Vec<String>, immune: Vec<String>, attack: usize, attack_type: String, initiative: usize, combat_power: usize, } impl PartialEq for Group { fn eq(&self, rhs: &Group) -> bool { return self.is_foe == rhs.is_foe && self.hp == rhs.hp && self.attack == rhs.attack && self.initiative == rhs.initiative; } } impl Day24 { pub fn new(input: String) -> Day24 { let mut input_iter = input.lines(); let mut string; input_iter.next(); let mut groups: Vec<Group> = Vec::new(); loop { string = input_iter.next().unwrap().to_string(); if string == "" { break; } let mut group = Day24::parse_line(&string); group.is_foe = false; groups.push(group); } input_iter.next(); while let Some(string) = input_iter.next() { let group = Day24::parse_line(&string.to_string()); groups.push(group); } Day24 { groups } } fn parse_line(line: &String) -> Group { // YES, I KNOW, I really should learn regexps // My anger towards this year's AoC difficulty level/time consumption just hit another level, that's why I don't give a single heck about code quality anymore let perks = line.split(|c| c == '(' || c == ')').collect::<Vec<&str>>(); let mut weak: Vec<String> = Vec::new(); let mut immune: Vec<String> = Vec::new(); if perks.len() == 3 { let perks = perks[1].split(|c| c == ';').collect::<Vec<&str>>(); for perk in perks { let perk = perk.trim(); if perk.starts_with("weak to") { let (_, weaknesses) = perk.split_at(7); weak = weaknesses.split(|c| c == ',').map(|s| s.trim().to_string()).collect::<Vec<String>>(); } else { let (_, immunities) = perk.split_at(9); immune = immunities.split(|c| c == ',').map(|s| s.trim().to_string()).collect::<Vec<String>>(); } } } let numbers = utils::extract_unsigned_integers_from_string(line); let units = numbers[0][0]; let hp = numbers[0][1]; let attack = numbers[0][2]; let initiative = numbers[0][3]; let tmp = line.split_whitespace().collect::<Vec<&str>>(); let mut attack_type = String::new(); for i in 0..tmp.len() { if tmp[i] == "damage" { attack_type = tmp[i-1].to_string(); break; } } let combat_power = units * attack; let is_foe = true; Group { is_foe, units, hp, weak, immune, attack, attack_type, initiative, combat_power } } fn get_opponents(&self, groups: &mut Vec<Group>) -> Vec<(Group, Group)> { let mut attacked_groups: Vec<Option<Group>> = Vec::new(); groups.sort_by(|a, b| { let ord = b.combat_power.cmp(&a.combat_power); if ord == Ordering::Equal { return b.initiative.cmp(&a.initiative); } ord }); for i in 0..groups.len() { let mut foe: Option<Group> = None; let mut max_dmg = 0; for j in 0..groups.len() { if i != j && groups[j].is_foe != groups[i].is_foe && !attacked_groups.contains(&Some(groups[j].clone())) { let mut dmg = groups[i].combat_power; if groups[j].weak.contains(&groups[i].attack_type) { dmg = groups[i].combat_power * 2; } if groups[j].immune.contains(&groups[i].attack_type) { dmg = 0; } if dmg > max_dmg { foe = Some(groups[j].clone()); max_dmg = dmg; } } } attacked_groups.push(foe); } groups.iter().zip(attacked_groups.iter()).filter(|tup| tup.1.is_some()).map(|tup| (tup.0.clone(), tup.1.clone().unwrap())).collect::<Vec<(Group, Group)>>() } fn attack(&self, groups: &mut Vec<Group>, fights: Vec<(Group, Group)>) -> bool { let mut damage_dealt = false; groups.sort_by(|a, b| { let ord = b.initiative.cmp(&a.initiative); if ord == Ordering::Equal { return b.combat_power.cmp(&a.combat_power); } ord }); for i in 0..groups.len() { for j in 0..fights.len() { if groups[i] == fights[j].0 { if groups[i].units == 0 { break; } for k in 0..groups.len() { if groups[k] == fights[j].1 { let dmg; if groups[k].weak.contains(&groups[i].attack_type) { dmg = groups[i].combat_power * 2; } else { dmg = groups[i].combat_power; } let casualties = dmg / groups[k].hp; if casualties > 0 { damage_dealt = true; } if casualties > groups[k].units { groups[k].units = 0; } else { groups[k].units -= casualties; } groups[k].combat_power = groups[k].units * groups[k].attack; break; } } break; } } } let mut i = 0; while i < groups.len() { if groups[i].units == 0 { groups.remove(i); } else { groups[i].combat_power = groups[i].units * groups[i].attack; i += 1; } } damage_dealt } } impl Day for Day24 { fn get_part_a_result(&self) -> String { let mut groups: Vec<Group> = self.groups.clone(); while groups.iter().filter(|g| g.is_foe).count() != 0 && groups.iter().filter(|g| !g.is_foe).count() != 0 { let fights = self.get_opponents(&mut groups); self.attack(&mut groups, fights); } groups.iter().fold(0, |acc, g| acc + g.units).to_string() } fn get_part_b_result(&self) -> String { // it's broken beyond repair but somehow gave me a good answer // it doesn't even pass the sample test, but i couldn't care less let groups: Vec<Group> = self.groups.clone(); let (mut min, mut max) = (0, 20000); let mut result_map: HashMap<usize, usize> = HashMap::new(); let mut boost = 10000; loop { let mut boosted_groups = groups.iter().map(|group| { let mut group = group.clone(); if !group.is_foe { group.attack += boost; } group }).collect::<Vec<Group>>(); while boosted_groups.iter().filter(|g| g.is_foe).count() != 0 && boosted_groups.iter().filter(|g| !g.is_foe).count() != 0 { let fights = self.get_opponents(&mut boosted_groups); let damage_dealt = self.attack(&mut boosted_groups, fights); if !damage_dealt { break; } } let remaining_allies = boosted_groups.iter().filter(|g| !g.is_foe).fold(0, |acc, g| acc + g.units); let remaining_foes = boosted_groups.iter().filter(|g| g.is_foe).fold(0, |acc, g| acc + g.units); result_map.insert(boost, remaining_allies); if remaining_allies == 0 || (remaining_foes != 0 && remaining_allies != 0) { min = boost + 1; } else { max = boost - 1; } boost = (min + max) / 2; if min > max { return result_map[&min].to_string(); } } } }
true
f5c8d368b82de6313c8f910405030a025751ec84
Rust
doraneko94/CA3-Rust
/pinsky-rinzel/src/neuron.rs
UTF-8
630
2.703125
3
[]
no_license
use std::collections::HashMap; use crate::compartment::*; pub struct Neuron { pub soma: Soma, pub dend: Dend, } impl Default for Neuron { fn default() -> Self { Self::new(&HashMap::new()) } } impl Neuron { pub fn new(params: &HashMap<&str, f64>) -> Self { let soma = Soma::new(params); let dend = Dend::new(params); Self { soma, dend, } } pub fn run(&mut self, dt: f64, v_pre: &Vec<f64>) -> f64 { let v_s = self.soma.v; let v_d = self.dend.v; self.soma.run(v_d, dt, v_pre); self.dend.run(v_s, dt, v_pre); self.soma.v } }
true
3e5781697cbd6cc517a014391461506aed02e374
Rust
Vuenc/Advent-of-Code-2018
/src/day4.rs
UTF-8
4,549
3.125
3
[]
no_license
// use std::cmp::{max}; use regex::Regex; use self::GuardAction::*; use bit_vec::BitVec; use std::collections::HashMap; #[derive(Debug, PartialEq, Eq)] enum GuardAction { BeginsShift, WakesUp, FallsAsleep } #[derive(Debug)] struct GuardEvent { date: String, minute: i32, guard_id: Option<i32>, action: GuardAction } #[derive(Debug)] struct Day { guard_id: i32, minutes: BitVec, minutes_awake: i32 } impl Day { pub fn new(guard_id: i32) -> Day { let minutes = BitVec::with_capacity(60); Day {guard_id, minutes, minutes_awake: 0} } pub fn set_next_minute(&mut self, awake: bool) { self.minutes.push(awake); self.minutes_awake += i32::from(awake); } } impl GuardEvent { pub fn from_line(line: &String, regex: &Regex) -> GuardEvent { let captures = regex.captures(line).expect("No captures for line!"); let action = match &captures[3] { "wakes" => WakesUp, "falls" => FallsAsleep, _ => BeginsShift }; GuardEvent {date: captures[1].to_string(), minute: captures[2].replace(":", "").parse().unwrap(), guard_id: captures.get(4).map(|id| id.as_str().parse().unwrap()), action } } } fn initialize(lines: &Vec<String>) -> Vec<Day> { let regex = Regex::new(r"(\d\d-\d\d) ((?:23|00):\d\d)\] (Guard #(\d*)|wakes|falls)").expect("Building Regex failed"); let mut events = lines.iter().map(|l| GuardEvent::from_line(l, &regex)).collect::<Vec<GuardEvent>>(); events.sort_by(|GuardEvent {date: date1, minute: minute1, ..}, GuardEvent {date: date2, minute: minute2, ..}| { date1.cmp(date2).then(minute1.cmp(minute2)) }); let mut days = Vec::new(); let mut events_iter = events.iter(); let mut event_option = events_iter.next(); while event_option.is_some() { let event = event_option.unwrap(); assert_eq!(event.action, BeginsShift); let mut current_day = Day::new(event.guard_id.unwrap()); let mut is_awake = true; event_option = events_iter.next(); for minute in 0..60 { if event_option.map_or(false, |e| e.action != BeginsShift && e.minute == minute) { is_awake = !is_awake; event_option = events_iter.next(); } current_day.set_next_minute(is_awake); } days.push(current_day); } days } pub fn star1(lines: &Vec<String>) -> String { let days = initialize(lines); let mut guard_map = HashMap::new(); for day in days { guard_map.entry(day.guard_id) .or_insert(vec![]) .push(day); } let (&sleepiest_guard_id, sleepiest_guard_days) = guard_map.iter() .max_by_key(|(_, v)| v.iter() .map(|day| 60 - day.minutes_awake) .sum::<i32>() ).unwrap(); let mut sleepiest_guard_awake_by_minutes = vec![0; 60]; for day in sleepiest_guard_days { // println!("Day: {:?}", day); for minute in 0..60 { sleepiest_guard_awake_by_minutes[minute] += i32::from(day.minutes[minute]); } } let (max_minute, _) = sleepiest_guard_awake_by_minutes.iter().enumerate().min_by_key(|(_, times)| *times).unwrap(); println!("Min minute: {}, max guard: {}", max_minute, sleepiest_guard_id); (sleepiest_guard_id * max_minute as i32).to_string() } pub fn star2(lines: &Vec<String>) -> String { let days = initialize(lines); let mut guard_map = HashMap::new(); for day in days { guard_map.entry(day.guard_id) .or_insert(vec![]) .push(day); } let mut max_guard_asleep_per_minute = vec![(0, None); 60]; for &guard_id in guard_map.keys() { let mut guard_asleep_by_minute = vec![0; 60]; for day in &guard_map[&guard_id] { for minute in 0..60 { guard_asleep_by_minute[minute] += i32::from(!day.minutes[minute]); } } for minute in 0..60 { if max_guard_asleep_per_minute[minute].0 < guard_asleep_by_minute[minute] { max_guard_asleep_per_minute[minute] = (guard_asleep_by_minute[minute], Some(guard_id)); } } } if let Some((max_minute, (_, Some(max_guard_id)))) = max_guard_asleep_per_minute.iter().enumerate().max_by_key(|(_, (times, _))| times) { return (max_minute as i32 * max_guard_id) .to_string(); } panic!("No maximum found: Invalid input!"); }
true
ea715be5961eecb6f8ea7a10f68f1d31eadfb2e8
Rust
async-raft/async-raft
/async-raft/tests/shutdown.rs
UTF-8
1,875
2.6875
3
[ "Apache-2.0", "MIT" ]
permissive
mod fixtures; use std::sync::Arc; use std::time::Duration; use anyhow::{anyhow, Result}; use async_raft::Config; use tokio::time::sleep; use fixtures::RaftRouter; /// Cluster shutdown test. /// /// What does this test do? /// /// - this test builds upon the `initialization` test. /// - after the cluster has been initialize, it performs a shutdown routine /// on each node, asserting that the shutdown routine succeeded. /// /// RUST_LOG=async_raft,memstore,shutdown=trace cargo test -p async-raft --test shutdown #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn initialization() -> Result<()> { fixtures::init_tracing(); // Setup test dependencies. let config = Arc::new(Config::build("test".into()).validate().expect("failed to build Raft config")); let router = Arc::new(RaftRouter::new(config.clone())); router.new_raft_node(0).await; router.new_raft_node(1).await; router.new_raft_node(2).await; // Assert all nodes are in non-voter state & have no entries. sleep(Duration::from_secs(10)).await; router.assert_pristine_cluster().await; // Initialize the cluster, then assert that a stable cluster was formed & held. tracing::info!("--- initializing cluster"); router.initialize_from_single_node(0).await?; sleep(Duration::from_secs(10)).await; router.assert_stable_cluster(Some(1), Some(1)).await; tracing::info!("--- performing node shutdowns"); let (node0, _) = router.remove_node(0).await.ok_or_else(|| anyhow!("failed to find node 0 in router"))?; node0.shutdown().await?; let (node1, _) = router.remove_node(1).await.ok_or_else(|| anyhow!("failed to find node 1 in router"))?; node1.shutdown().await?; let (node2, _) = router.remove_node(2).await.ok_or_else(|| anyhow!("failed to find node 2 in router"))?; node2.shutdown().await?; Ok(()) }
true
1f3f52c1b890983078f1d66a0ba9ab24524e3cec
Rust
bvssvni/ncollide
/src/parametric/parametric.rs
UTF-8
1,727
3.1875
3
[ "BSD-2-Clause" ]
permissive
// FIXME: support more than rectangular surfaces? use math::Scalar; /// Trait implemented by differentiable parametric surfaces. /// /// The parametrization space is assumed to be `[0.0, 1.0] x [0.0, 1.0]`. pub trait ParametricSurface<N: Scalar, P, V> { // FIXME: rename those d0, du, etc. ? (just like in the `symbolic` module. /// Evaluates the parametric surface. fn at(&self, u: N, v: N) -> P; /// Evaluates the surface derivative wrt. `u`. fn at_u(&self, u: N, v: N) -> V; /// Evaluates the surface derivative wrt. `v`. fn at_v(&self, u: N, v: N) -> V; /// Evaluates the surface second derivative wrt. `u`. fn at_uu(&self, u: N, v: N) -> V; /// Evaluates the surface second derivative wrt. `v`. fn at_vv(&self, u: N, v: N) -> V; /// Evaluates the surface second derivative wrt. `u` and `v`. fn at_uv(&self, u: N, v: N) -> V; /// Evaluates the parametric surface and its first derivatives. /// /// Returns (S(u, v), dS / du, dS / dv) #[inline] fn at_u_v(&self, u: N, v: N) -> (P, V, V) { (self.at(u, v), self.at_u(u, v), self.at_v(u, v)) } /// Evaluates the parametric surface and its first and second derivatides. /// /// Returns (S(u, v), dS / du, dS / dv, d²S / du², d²S / dv², d²S / dudv) #[inline] fn at_u_v_uu_vv_uv(&self, u: N, v: N) -> (P, V, V, V, V, V) { (self.at(u, v), self.at_u(u, v), self.at_v(u, v), self.at_uu(u, v), self.at_vv(u, v), self.at_uv(u, v)) } /// Evaluates the parametric surface and its derivative wrt. `u` `n` times and wrt. `v` `k` times. /// /// Returns d^(n + k) S(u, v) / (du^n dk^n). fn at_uv_nk(&self, u: N, v: N, n: uint, k: uint) -> V; }
true
dcef0169c6c99be4ca7a15f5b178f66bf2e1df8b
Rust
iqlusioninc/abscissa
/core/src/thread/name.rs
UTF-8
1,021
3.421875
3
[ "Apache-2.0" ]
permissive
//! Thread names. use crate::{FrameworkError, FrameworkErrorKind::ThreadError}; use std::{fmt, str::FromStr}; /// Thread name. /// /// Cannot contain null bytes. #[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)] pub struct Name(String); impl Name { /// Create a new thread name pub fn new(name: impl ToString) -> Result<Self, FrameworkError> { let name = name.to_string(); if name.contains('\0') { fail!(ThreadError, "name contains null bytes: {:?}", name) } else { Ok(Name(name)) } } } impl AsRef<str> for Name { fn as_ref(&self) -> &str { &self.0 } } impl FromStr for Name { type Err = FrameworkError; fn from_str(s: &str) -> Result<Self, FrameworkError> { Self::new(s) } } impl From<Name> for String { fn from(name: Name) -> String { name.0 } } impl fmt::Display for Name { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } }
true
270c1eb1a45470b3dab44f6cfd54a6ee3caac1c9
Rust
peku33/logicblocks
/Controller/src/devices/houseblocks/avr_v1/hardware/driver.rs
UTF-8
6,311
2.515625
3
[]
no_license
use super::{ super::super::houseblocks_v1::{ common::{Address, Payload}, master::Master, }, parser::Parser, }; use anyhow::{ensure, Context, Error}; use std::time::Duration; #[derive(Debug)] pub struct PowerFlags { wdt: bool, bod: bool, ext_reset: bool, pon: bool, } #[derive(Debug)] pub struct Version { avr_v1: u16, application: u16, } #[derive(Debug)] pub struct Driver<'m> { master: &'m Master, address: Address, } impl<'m> Driver<'m> { const TIMEOUT_DEFAULT: Duration = Duration::from_millis(250); pub fn new( master: &'m Master, address: Address, ) -> Self { Self { master, address } } pub fn address(&self) -> &Address { &self.address } // Transactions async fn transaction_out( &self, service_mode: bool, payload: Payload, ) -> Result<(), Error> { self.master .transaction_out(service_mode, self.address, payload) .await .context("transaction_out")?; Ok(()) } async fn transaction_out_in( &self, service_mode: bool, payload: Payload, timeout: Option<Duration>, ) -> Result<Payload, Error> { let result = self .master .transaction_out_in( service_mode, self.address, payload, timeout.unwrap_or(Self::TIMEOUT_DEFAULT), ) .await .context("transaction_out_in")?; Ok(result) } // Routines async fn healthcheck( &self, service_mode: bool, ) -> Result<(), Error> { let response = self .transaction_out_in(service_mode, Payload::new(Box::from(*b"")).unwrap(), None) .await .context("transaction_out_in")?; ensure!( response.as_bytes() == &b""[..], "invalid healthcheck response" ); Ok(()) } async fn reboot( &self, service_mode: bool, ) -> Result<(), Error> { self.transaction_out(service_mode, Payload::new(Box::from(*b"!")).unwrap()) .await .context("transaction_out")?; tokio::time::sleep(Self::TIMEOUT_DEFAULT).await; Ok(()) } async fn read_clear_power_flags( &self, service_mode: bool, ) -> Result<PowerFlags, Error> { let response = self .transaction_out_in(service_mode, Payload::new(Box::from(*b"@")).unwrap(), None) .await .context("transaction_out_in")?; let mut parser = Parser::from_payload(&response); let wdt = parser.expect_bool().context("wdt")?; let bod = parser.expect_bool().context("bod")?; let ext_reset = parser.expect_bool().context("ext_reset")?; let pon = parser.expect_bool().context("pon")?; parser.expect_end().context("expect_end")?; Ok(PowerFlags { wdt, bod, ext_reset, pon, }) } async fn read_application_version( &self, service_mode: bool, ) -> Result<Version, Error> { let response = self .transaction_out_in(service_mode, Payload::new(Box::from(*b"#")).unwrap(), None) .await .context("transaction_out_in")?; let mut parser = Parser::from_payload(&response); let avr_v1 = parser.expect_u16().context("avr_v1")?; let application = parser.expect_u16().context("application")?; parser.expect_end().context("expect_end")?; Ok(Version { avr_v1, application, }) } // Service mode routines async fn service_mode_read_application_checksum(&self) -> Result<u16, Error> { let response = self .transaction_out_in(true, Payload::new(Box::new(*b"C")).unwrap(), None) .await .context("transaction_out_in")?; let mut parser = Parser::from_payload(&response); let checksum = parser.expect_u16().context("checksum")?; parser.expect_end().context("expect_end")?; Ok(checksum) } async fn service_mode_jump_to_application_mode(&self) -> Result<(), Error> { self.transaction_out(true, Payload::new(Box::from(*b"R")).unwrap()) .await .context("transaction_out")?; tokio::time::sleep(Duration::from_millis(250)).await; Ok(()) } // Procedures pub async fn prepare(&self) -> Result<(), Error> { // Driver may be already initialized, check it. let healthcheck_result = self.healthcheck(false).await; if healthcheck_result.is_ok() { // Is initialized, perform reboot self.reboot(false).await.context("deinitialize reboot")?; } // We should be in service mode self.healthcheck(true) .await .context("service mode healthcheck")?; // Check application up to date let application_checksum = self .service_mode_read_application_checksum() .await .context("service mode read application checksum")?; log::trace!("application_checksum: {}", application_checksum); // TODO: Push new firmware // Reboot to application section self.service_mode_jump_to_application_mode() .await .context("jump to application mode")?; // Check life in application section self.healthcheck(false) .await .context("application mode healthcheck")?; Ok(()) } } #[derive(Debug)] pub struct ApplicationDriver<'d> { driver: &'d Driver<'d>, } impl<'d> ApplicationDriver<'d> { pub fn new(driver: &'d Driver<'d>) -> Self { Self { driver } } pub async fn transaction_out( &self, payload: Payload, ) -> Result<(), Error> { self.driver.transaction_out(false, payload).await } pub async fn transaction_out_in( &self, payload: Payload, timeout: Option<Duration>, ) -> Result<Payload, Error> { self.driver .transaction_out_in(false, payload, timeout) .await } }
true
c1fa22ba7f032f9b23c8e82328a6710d0342286b
Rust
higgsofwolfram74/rustcreditcardchecksum
/creditcheck/src/main.rs
UTF-8
1,519
3.578125
4
[]
no_license
use std::io; fn credit_checksum(number_check: &mut [u32; 16]) { let test: u32 = number_check[15]; number_check[15] = 0; for index in (0..15).step_by(2) { let mut number = number_check[index] * 2; if number > 9 { number = 1 + (number - 10); } number_check[index] = number; } println!("{:?}", number_check); let mut total: u32 = number_check.iter().sum(); total += test; if total % 10 == 0 { println!("This is a valid card number.") } else { println!("This card number is invalid.") } } fn number_vectorizer(card_digits: &String) { let mut card_number: [u32; 16] = [0; 16]; let mut index = 0; for digit in card_digits.chars() { card_number[index] = digit.to_digit(10).expect("Non number on credit card"); index += 1; } credit_checksum(&mut card_number); } fn main() { println!("Welcome to my credit card verifier. Please input number to check."); let mut card_number = String::new(); io::stdin() .read_line(&mut card_number) .expect("Failed to read the input"); if card_number.ends_with('\n') { card_number.pop(); if card_number.ends_with('\r') { card_number.pop(); } } if card_number.len() != 16 { panic!("Card number is not the correct length") } println!("Now checking the validity of the credit card number."); number_vectorizer(&card_number); }
true
e01787d07825c553a84a5c76024f6a5c266b8289
Rust
TheBlueMatt/rust-lightning
/lightning-block-sync/src/utils.rs
UTF-8
941
2.890625
3
[ "Apache-2.0" ]
permissive
use bitcoin::util::uint::Uint256; pub fn hex_to_uint256(hex: &str) -> Option<Uint256> { if hex.len() != 64 { return None; } let mut out = [0u64; 4]; let mut b: u64 = 0; for (idx, c) in hex.as_bytes().iter().enumerate() { b <<= 4; match *c { b'A'..=b'F' => b |= (c - b'A' + 10) as u64, b'a'..=b'f' => b |= (c - b'a' + 10) as u64, b'0'..=b'9' => b |= (c - b'0') as u64, _ => return None, } if idx % 16 == 15 { out[3 - (idx / 16)] = b; b = 0; } } Some(Uint256::from(&out[..])) } #[cfg(feature = "rpc-client")] pub fn hex_to_vec(hex: &str) -> Option<Vec<u8>> { let mut out = Vec::with_capacity(hex.len() / 2); let mut b = 0; for (idx, c) in hex.as_bytes().iter().enumerate() { b <<= 4; match *c { b'A'..=b'F' => b |= c - b'A' + 10, b'a'..=b'f' => b |= c - b'a' + 10, b'0'..=b'9' => b |= c - b'0', _ => return None, } if (idx & 1) == 1 { out.push(b); b = 0; } } Some(out) }
true
de7cb8d52d367ddef807053a425e2253e8e799b5
Rust
s-aran/nae
/src/natural_sort.rs
UTF-8
7,625
3.671875
4
[]
no_license
use std::cmp::Ordering; pub struct NaturalSort {} impl NaturalSort { /// internal common radix const RADIX: u32 = 10; /// strcmp with natural /// # Arguments /// * `a` - first string /// * `b` - second string /// # Return /// * `Ordering` - result of comparison /// # Example /// ``` /// use std::cmp::Ordering; /// use nae::natural_sort::NaturalSort; /// assert_eq!(NaturalSort::strcmp_natural("1", "2"), Ordering::Less); /// assert_eq!(NaturalSort::strcmp_natural("2", "2"), Ordering::Equal); /// assert_eq!(NaturalSort::strcmp_natural("3", "2"), Ordering::Greater); /// ``` pub fn strcmp_natural(a: &str, b: &str) -> Ordering { // println!("a: {} ({}), b: {} ({})", a, a.len(), b, b.len()); if a == b { // return Ordering::Equal; } let a_len = a.len(); let b_len = b.len(); let max_len = std::cmp::max(a.len(), b.len()); // println!("max_len: {}", max_len); let mut ret = Ordering::Equal; for i in 0..max_len { let ac = if i < a_len { a.chars().nth(i).unwrap() } else { '\0' }; let bc = if i < b_len { b.chars().nth(i).unwrap() } else { '\0' }; // println!("a[{}]: {} (0x{:04X})", i, ac, ac as u32); // println!("b[{}]: {} (0x{:04X})", i, bc, bc as u32); if ac != bc { ret = if ac < bc { Ordering::Less } else { Ordering::Greater }; // println!("a: {}, b: {}", ac.is_digit(Radix), bc.is_digit(Radix)); if ac.is_digit(NaturalSort::RADIX) && bc.is_digit(NaturalSort::RADIX) { let mut ai = i; for _ in i..a_len { // println!("ai: {} -> {}", ai, a.chars().nth(ai).unwrap()); if !a.chars().nth(ai).unwrap().is_digit(NaturalSort::RADIX) { break; } ai += 1; } // println!("{}[{}..{}] --> {}", a, i, ai, &a[i..ai]); let asl = &a[i..ai]; let anum = if asl == "" { 0 } else { asl.parse::<u32>().unwrap() }; let mut bi = i; for _ in i..b_len { // println!("bi: {} -> {}", bi, b.chars().nth(bi).unwrap()); if !b.chars().nth(bi).unwrap().is_digit(NaturalSort::RADIX) { break; } bi += 1; } // println!("{}[{}..{}] --> {}", b, i, bi, &b[i..bi]); let bsl = &b[i..bi]; let bnum = if bsl == "" { 0 } else { bsl.parse::<u32>().unwrap() }; // println!("anum: {}", anum); // println!("bnum: {}", bnum); ret = if anum < bnum { Ordering::Less } else { Ordering::Greater }; break; } else if ret == Ordering::Equal { continue; } else { break; } } } // println!( // "ret: {}", // match ret { // Ordering::Less => "Less", // Ordering::Greater => "Greater", // Ordering::Equal => "Equal", // } // ); ret } pub fn natural_sort(v: &mut Vec<&str>) { v.sort_unstable_by(|a, b| NaturalSort::strcmp_natural(&a, &b)); } } #[cfg(test)] mod tests { use crate::natural_sort::NaturalSort; use std::cmp::Ordering; #[test] fn test_natural_sort_1() { let mut vec = vec!["10", "9", "8", "7", "5", "1", "2", "3", "4", "6"]; let expected = vec!["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]; NaturalSort::natural_sort(&mut vec); assert_eq!(vec, expected); } #[test] fn test_natural_sort_2() { let mut vec = vec![ "a100a", "a100", "a", "a10", "a2", "a200", "a20", "a1", "a100a10", "a100a1", ]; let expected = vec![ "a", "a1", "a2", "a10", "a20", "a100", "a100a", "a100a1", "a100a10", "a200", ]; NaturalSort::natural_sort(&mut vec); assert_eq!(vec, expected); } #[test] fn test_strcmp_natural() { assert_eq!(NaturalSort::strcmp_natural("1", "2"), Ordering::Less); assert_eq!(NaturalSort::strcmp_natural("2", "2"), Ordering::Equal); assert_eq!(NaturalSort::strcmp_natural("3", "2"), Ordering::Greater); } #[test] fn test_strcmp_natural_equal() { let a = "a100"; let b = "a100"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Equal); } #[test] fn test_strcmp_natural_equal_alpha() { let a = "aaa"; let b = "aaa"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Equal); } #[test] fn test_strcmp_natural_greater_1() { let a = "a100"; let b = "a10"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Greater); } #[test] fn test_strcmp_natural_greater_2() { let a = "a10b"; let b = "a10a"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Greater); } #[test] fn test_strcmp_natural_greater_3() { let a = "a10a100"; let b = "a10a10"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Greater); } #[test] fn test_strcmp_natural_greater_4() { let a = "a200"; let b = "a100a"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Greater); } #[test] fn test_strcmp_natural_less_1() { let a = "a10"; let b = "a100"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Less); } #[test] fn test_strcmp_natural_less_2() { let a = "a10a"; let b = "a10b"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Less); } #[test] fn test_strcmp_natural_less_3() { let a = "a10a100"; let b = "a10b10"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Less); } #[test] fn test_strcmp_natural_less_4() { let a = "a100a"; let b = "a200"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Less); } #[test] fn test_strcmp_natural_greater_alpha_1() { let a = "baa"; let b = "aaa"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Greater); } #[test] fn test_strcmp_natural_greater_alpha_2() { let a = "aba"; let b = "aaa"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Greater); } #[test] fn test_strcmp_natural_greater_alpha_3() { let a = "aab"; let b = "aaa"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Greater); } #[test] fn test_strcmp_natural_less_alpha_1() { let a = "aaa"; let b = "baa"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Less); } #[test] fn test_strcmp_natural_less_alpha_2() { let a = "aaa"; let b = "aba"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Less); } #[test] fn test_strcmp_natural_less_alpha_3() { let a = "aaa"; let b = "aab"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Less); } #[test] fn test_strcmp_natural_greater_number_1() { let a = "100b"; let b = "100a"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Greater); } #[test] fn test_strcmp_natural_less_number_1() { let a = "100a"; let b = "100b"; let result = NaturalSort::strcmp_natural(a, b); assert!(result == Ordering::Less); } }
true
ceb9615477eae540dce6be43fc8a9b18d03fdf58
Rust
Emerentius/drain_experiments
/src/_try_drain.rs
UTF-8
635
2.828125
3
[]
no_license
pub(crate) struct _TryDrain<'a, T: 'a> { pub vec: &'a mut Vec<T>, pub finished: bool, pub idx: usize, pub del: usize, pub old_len: usize, } impl<'a, T: 'a> _TryDrain<'a, T> { pub fn tail_len(&self) -> usize { self.old_len - self.idx } } impl<'a, T: 'a> _TryDrain<'a, T> { pub fn new(vec: &'a mut Vec<T>) -> Self { let old_len = vec.len(); // Guard against us getting leaked (leak amplification) unsafe { vec.set_len(0); } _TryDrain { vec, finished: false, idx: 0, del: 0, old_len, } } }
true
c4431e79f9f4751fcd73fee8b29cec34db27cfb6
Rust
mcginty/snow
/src/error.rs
UTF-8
6,098
3.1875
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! All error types used by Snow operations. use std::fmt; /// `snow` provides decently detailed errors, exposed as the [`Error`] enum, /// to allow developers to react to errors in a more actionable way. /// /// *With that said*, security vulnerabilities *can* be introduced by passing /// along detailed failure information to an attacker. While an effort was /// made to not make any particularly foolish choices in this regard, we strongly /// recommend you don't dump the `Debug` output to a user, for example. /// /// This enum is intentionally non-exhasutive to allow new error types to be /// introduced without causing a breaking API change. /// /// `snow` may eventually add a feature flag and enum variant to only return /// an "unspecified" error for those who would prefer safety over observability. #[derive(Debug)] #[non_exhaustive] pub enum Error { /// The noise pattern failed to parse. Pattern(PatternProblem), /// Initialization failure, at a provided stage. Init(InitStage), /// Missing prerequisite material. Prereq(Prerequisite), /// An error in `snow`'s internal state. State(StateProblem), /// Invalid input. Input, /// Diffie-Hellman agreement failed. Dh, /// Decryption failed. Decrypt, /// Key-encapsulation failed #[cfg(feature = "hfs")] Kem, } /// The various stages of initialization used to help identify /// the specific cause of an `Init` error. #[derive(Debug)] pub enum PatternProblem { /// Caused by a pattern string that is too short and malformed (e.g. `Noise_NN_25519`). TooFewParameters, /// The handshake section of the string (e.g. `XXpsk3`) isn't supported. Check for typos /// and necessary feature flags. UnsupportedHandshakeType, /// This was a trick choice -- an illusion. The correct answer was `Noise`. UnsupportedBaseType, /// Invalid hash type (e.g. `BLAKE2s`). /// Check that there are no typos and that any feature flags you might need are toggled UnsupportedHashType, /// Invalid DH type (e.g. `25519`). /// Check that there are no typos and that any feature flags you might need are toggled UnsupportedDhType, /// Invalid cipher type (e.g. `ChaChaPoly`). /// Check that there are no typos and that any feature flags you might need are toggled UnsupportedCipherType, /// The PSK position must be a number, and a pretty small one at that. InvalidPsk, /// Invalid modifier (e.g. `fallback`). /// Check that there are no typos and that any feature flags you might need are toggled UnsupportedModifier, #[cfg(feature = "hfs")] /// Invalid KEM type. /// Check that there are no typos and that any feature flags you might need are toggled UnsupportedKemType, } impl From<PatternProblem> for Error { fn from(reason: PatternProblem) -> Self { Error::Pattern(reason) } } /// The various stages of initialization used to help identify /// the specific cause of an `Init` error. #[derive(Debug)] pub enum InitStage { /// Provided and received key lengths were not equal. ValidateKeyLengths, /// Provided and received preshared key lengths were not equal. ValidatePskLengths, /// Two separate cipher algorithms were initialized. ValidateCipherTypes, /// The RNG couldn't be initialized. GetRngImpl, /// The DH implementation couldn't be initialized. GetDhImpl, /// The cipher implementation couldn't be initialized. GetCipherImpl, /// The hash implementation couldn't be initialized. GetHashImpl, #[cfg(feature = "hfs")] /// The KEM implementation couldn't be initialized. GetKemImpl, /// The PSK position (specified in the pattern string) isn't valid for the given /// handshake type. ValidatePskPosition, } impl From<InitStage> for Error { fn from(reason: InitStage) -> Self { Error::Init(reason) } } /// A prerequisite that may be missing. #[derive(Debug)] pub enum Prerequisite { /// A local private key wasn't provided when it was needed by the selected pattern. LocalPrivateKey, /// A remote public key wasn't provided when it was needed by the selected pattern. RemotePublicKey, } impl From<Prerequisite> for Error { fn from(reason: Prerequisite) -> Self { Error::Prereq(reason) } } /// Specific errors in the state machine. #[derive(Debug)] pub enum StateProblem { /// Missing key material in the internal handshake state. MissingKeyMaterial, /// Preshared key missing in the internal handshake state. MissingPsk, /// You attempted to write a message when it's our turn to read. NotTurnToWrite, /// You attempted to read a message when it's our turn to write. NotTurnToRead, /// You tried to go into transport mode before the handshake was done. HandshakeNotFinished, /// You tried to continue the handshake when it was already done. HandshakeAlreadyFinished, /// You called a method that is only valid if this weren't a one-way handshake. OneWay, /// The nonce counter attempted to go higher than (2^64) - 1 Exhausted, } impl From<StateProblem> for Error { fn from(reason: StateProblem) -> Self { Error::State(reason) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::Pattern(reason) => write!(f, "pattern error: {:?}", reason), Error::Init(reason) => { write!(f, "initialization error: {:?}", reason) }, Error::Prereq(reason) => { write!(f, "prerequisite error: {:?}", reason) }, Error::State(reason) => write!(f, "state error: {:?}", reason), Error::Input => write!(f, "input error"), Error::Dh => write!(f, "diffie-hellman error"), Error::Decrypt => write!(f, "decrypt error"), #[cfg(feature = "hfs")] Error::Kem => write!(f, "kem error"), } } } impl std::error::Error for Error {}
true
ca3afa77fd4d2fa3275e2996416d425dcf3e5175
Rust
Sword-Smith/rust-tutorial
/src/scoping_rules/aliasing.rs
UTF-8
1,686
3.9375
4
[ "Unlicense" ]
permissive
struct Point { x: i32, y: i32, z: i32, } pub fn aliasing() { let mut point = Point { x: 0, y: 0, z: 0 }; let borrowed_point = &point; let another_borrow = &point; println!( "Point has coordinates: ({}, {}, {})", borrowed_point.x, borrowed_point.y, borrowed_point.z ); // `point` cannot be mutably borrowed because it is currently immutably borrowed. // let mutable_borrow = &mut point; // The borrowed values are used again here println!( "Point has coordinates: ({}, {}, {})", borrowed_point.x, another_borrow.y, point.z ); // Here, the immutable borrows are garbage collected, since they are not used later in the program. // The immutable references are no longer used for the rest of the code, so it is possible to reborrow with a mutable reference. let mutable_borrow = &mut point; mutable_borrow.x = 5; mutable_borrow.y = 2; mutable_borrow.z = 1; // point cannot be borrowed as immutable because it's currently borrowed as mutable // let y = &point.y; // point cannot be printed, since the `println!` macro takes an immutable borrow. // println!("Point Z coordinate is {}", point.z); // Mutable references can, however, be passed as immutable to `println!`. So it *is* possible to print even though a mutable reference exists. println!( "Point has coordinates: ({}, {}, {})", mutable_borrow.x, mutable_borrow.y, mutable_borrow.z ); let new_borrowed_point = &point; println!( "Point now has coordinates: ({}, {}, {})", new_borrowed_point.x, new_borrowed_point.y, new_borrowed_point.z ); }
true
526875f2de9cf68692eb0842ffbcd673d534e6f8
Rust
LesnyRumcajs/wakey
/wakey/src/lib.rs
UTF-8
8,182
3.3125
3
[ "MIT" ]
permissive
//! Library for managing Wake-on-LAN packets. //! # Example //! ``` //! let wol = wakey::WolPacket::from_string("01:02:03:04:05:06", ':').unwrap(); //! if wol.send_magic().is_ok() { //! println!("Sent the magic packet!"); //! } else { //! println!("Failed to send the magic packet!"); //! } //! ``` use std::error::Error; use std::net::{SocketAddr, ToSocketAddrs, UdpSocket}; use std::{fmt, iter}; use arrayvec::ArrayVec; const MAC_SIZE: usize = 6; const MAC_PER_MAGIC: usize = 16; const HEADER: [u8; 6] = [0xFF; 6]; const PACKET_LEN: usize = HEADER.len() + MAC_SIZE * MAC_PER_MAGIC; type Packet = ArrayVec<u8, PACKET_LEN>; type Mac = ArrayVec<u8, MAC_SIZE>; /// Wrapper `Result` for the module errors. pub type Result<T> = std::result::Result<T, WakeyError>; /// Wrapper Error for fiascoes occuring in this module. #[derive(Debug)] pub enum WakeyError { /// The provided MAC address has invalid length. InvalidMacLength, /// The provided MAC address has invalid format. InvalidMacFormat, /// There was an error sending the WoL packet. SendFailure(std::io::Error), } impl Error for WakeyError {} impl fmt::Display for WakeyError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { WakeyError::InvalidMacLength => { write!(f, "Invalid MAC address length") } WakeyError::InvalidMacFormat => write!(f, "Invalid MAC address format"), WakeyError::SendFailure(e) => write!(f, "Couldn't send WoL packet: {e}"), } } } impl From<std::io::Error> for WakeyError { fn from(error: std::io::Error) -> Self { WakeyError::SendFailure(error) } } /// Wake-on-LAN packet #[derive(Debug, Clone, PartialEq, Eq)] pub struct WolPacket { /// WOL packet bytes packet: Packet, } impl WolPacket { /// Creates WOL packet from byte MAC representation /// # Example /// ``` /// let wol = wakey::WolPacket::from_bytes(&vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05]); /// ``` pub fn from_bytes(mac: &[u8]) -> Result<WolPacket> { Ok(WolPacket { packet: WolPacket::create_packet_bytes(mac)?, }) } /// Creates WOL packet from string MAC representation (e.x. 00:01:02:03:04:05) /// # Example /// ``` /// let wol = wakey::WolPacket::from_string("00:01:02:03:04:05", ':'); /// ``` /// # Panic /// Panics when input MAC is invalid (i.e. contains non-byte characters) pub fn from_string<T: AsRef<str>>(data: T, sep: char) -> Result<WolPacket> { WolPacket::from_bytes(&WolPacket::mac_to_byte(data, sep)?) } /// Broadcasts the magic packet from / to default address /// Source: 0.0.0.0:0 /// Destination 255.255.255.255:9 /// # Example /// ``` /// let wol = wakey::WolPacket::from_bytes(&vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05]).unwrap(); /// wol.send_magic(); /// ``` pub fn send_magic(&self) -> Result<()> { self.send_magic_to( SocketAddr::from(([0, 0, 0, 0], 0)), SocketAddr::from(([255, 255, 255, 255], 9)), ) } /// Broadcasts the magic packet from / to specified address. /// # Example /// ``` /// use std::net::SocketAddr; /// let wol = wakey::WolPacket::from_bytes(&vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05]).unwrap(); /// let src = SocketAddr::from(([0,0,0,0], 0)); /// let dst = SocketAddr::from(([255,255,255,255], 9)); /// wol.send_magic_to(src, dst); /// ``` pub fn send_magic_to<A: ToSocketAddrs>(&self, src: A, dst: A) -> Result<()> { let udp_sock = UdpSocket::bind(src)?; udp_sock.set_broadcast(true)?; udp_sock.send_to(&self.packet, dst)?; Ok(()) } /// Returns the underlying WoL packet bytes pub fn into_inner(self) -> Packet { self.packet } /// Converts string representation of MAC address (e.x. 00:01:02:03:04:05) to raw bytes. /// # Panic /// Panics when input MAC is invalid (i.e. contains non-byte characters) fn mac_to_byte<T: AsRef<str>>(data: T, sep: char) -> Result<Mac> { // hex-encoded bytes * 2 plus separators if data.as_ref().len() != MAC_SIZE * 3 - 1 { return Err(WakeyError::InvalidMacLength); } let bytes = data .as_ref() .split(sep) .map(|x| hex::decode(x).map_err(|_| WakeyError::InvalidMacFormat)) .collect::<Result<ArrayVec<_, MAC_SIZE>>>()? .into_iter() .flatten() .collect::<Mac>(); debug_assert_eq!(MAC_SIZE, bytes.len()); Ok(bytes) } /// Extends the MAC address to fill the magic packet fn extend_mac(mac: &[u8]) -> ArrayVec<u8, { MAC_SIZE * MAC_PER_MAGIC }> { let magic = iter::repeat(mac) .take(MAC_PER_MAGIC) .flatten() .copied() .collect::<ArrayVec<u8, { MAC_SIZE * MAC_PER_MAGIC }>>(); debug_assert_eq!(MAC_SIZE * MAC_PER_MAGIC, magic.len()); magic } /// Creates bytes of the magic packet from MAC address fn create_packet_bytes(mac: &[u8]) -> Result<Packet> { if mac.len() != MAC_SIZE { return Err(WakeyError::InvalidMacLength); } let mut packet = Packet::new(); packet.extend(HEADER); packet.extend(WolPacket::extend_mac(mac)); debug_assert_eq!(PACKET_LEN, packet.len()); Ok(packet) } } #[cfg(test)] mod tests { use super::*; #[test] fn extend_mac_test() { let mac = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06]; let extended_mac = WolPacket::extend_mac(&mac); assert_eq!(extended_mac.len(), MAC_PER_MAGIC * MAC_SIZE); assert_eq!(&extended_mac[(MAC_PER_MAGIC - 1) * MAC_SIZE..], &mac[..]); } #[test] #[should_panic] fn extend_mac_mac_too_long_test() { let mac = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]; WolPacket::extend_mac(&mac); } #[test] #[should_panic] fn extend_mac_mac_too_short_test() { let mac = vec![0x01, 0x02, 0x03, 0x04, 0x05]; WolPacket::extend_mac(&mac); } #[test] fn mac_to_byte_test() { let mac = "01:02:03:04:05:06"; let result = WolPacket::mac_to_byte(mac, ':'); assert_eq!( result.unwrap().into_inner().unwrap(), [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] ); } #[test] fn mac_to_byte_invalid_chars_test() { let mac = "ZZ:02:03:04:05:06"; assert!(matches!( WolPacket::mac_to_byte(mac, ':'), Err(WakeyError::InvalidMacFormat) )); } #[test] fn mac_to_byte_invalid_separator_test() { let mac = "01002:03:04:05:06"; assert!(matches!( WolPacket::mac_to_byte(mac, ':'), Err(WakeyError::InvalidMacFormat) )); } #[test] fn mac_to_byte_mac_too_long_test() { let mac = "01:02:03:04:05:06:07"; assert!(matches!( WolPacket::mac_to_byte(mac, ':'), Err(WakeyError::InvalidMacLength) )); } #[test] fn mac_to_byte_mac_too_short_test() { let mac = "01:02:03:04:05"; assert!(matches!( WolPacket::mac_to_byte(mac, ':'), Err(WakeyError::InvalidMacLength) )); } #[test] fn create_packet_bytes_test() { let bytes = WolPacket::create_packet_bytes(&[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]).unwrap(); assert_eq!(bytes.len(), MAC_SIZE * MAC_PER_MAGIC + HEADER.len()); assert!(bytes.iter().all(|&x| x == 0xFF)); } #[test] fn create_wol_packet() { let mac = vec![0x00, 0x01, 0x02, 0x03, 0x04, 0x05]; let wol = WolPacket::from_bytes(&mac).unwrap(); let packet = wol.into_inner(); assert_eq!(packet.len(), PACKET_LEN); assert_eq!( [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], &packet[0..HEADER.len()] ); for offset in (HEADER.len()..PACKET_LEN).step_by(MAC_SIZE) { assert_eq!(&mac, &packet[offset..offset + MAC_SIZE]); } } }
true
a232e300facfddb1c1cdf3e918b9ed7271ab9e16
Rust
jakewitcher/rusty_parsec
/tests/combinators_pipe_tests.rs
UTF-8
8,024
2.953125
3
[]
no_license
mod common; use common::*; use rusty_parsec::*; #[test] fn tuple_2_run_simple_parserss_succeeds() { let expected = Ok(ParserSuccess::new( (123, String::from("hello")), Position::new(1, 9, 8) )); let actual = tuple_2( p_u32(), p_hello() ).run(String::from("123hello")); assert_eq!(actual, expected); } #[test] fn tuple_2_run_simple_parsers_fails_with_error_at_first_parser() { let expected = Err(ParserFailure::new_err( String::from("integral value"), None, Position::new(1, 1, 0) )); let actual = tuple_2( p_u32(), p_hello() ).run(String::from("hello123")); assert_eq!(actual, expected); } #[test] fn tuple_2_run_complex_parsers_fails_with_fatal_error_at_first_parser() { let expected = Err(ParserFailure::new_fatal_err( String::from("integral value"), None, Position::new(1, 4, 3) )); let actual = tuple_2( p_abc_123(), p_hello() ).run(String::from("abcdefhello")); assert_eq!(actual, expected); } #[test] fn tuple_2_run_simple_parsers_fails_with_fatal_error_at_second_parser() { let expected = Err(ParserFailure::new_fatal_err( String::from("hello"), Some(String::from("world")), Position::new(1, 4, 3) )); let actual = tuple_2( p_u32(), p_hello() ).run(String::from("123world")); assert_eq!(actual, expected); } #[test] fn tuple_2_run_complex_parsers_fails_with_fatal_error_at_second_parser() { let expected = Err(ParserFailure::new_fatal_err( String::from("integral value"), None, Position::new(1, 7, 6) )); let actual = tuple_2( p_u32(), p_abc_123() ).run(String::from("100abcdef")); assert_eq!(actual, expected); } #[test] fn tuple_3_run_simple_parserss_succeeds() { let expected = Ok(ParserSuccess::new( (String::from("hello"), 123 , true), Position::new(1, 13, 12) )); let actual = tuple_3( p_hello(), p_u32(), p_true() ).run(String::from("hello123true")); assert_eq!(actual, expected); } #[test] fn tuple_3_run_simple_parsers_fails_with_error_at_first_parser() { let expected = Err(ParserFailure::new_err( String::from("hello"), Some(String::from("world")), Position::new(1, 1, 0) )); let actual = tuple_3( p_hello(), p_u32(), p_true() ).run(String::from("world123true")); assert_eq!(actual, expected); } #[test] fn tuple_3_run_simple_parsers_fails_with_fatal_error_at_second_parser() { let expected = Err(ParserFailure::new_fatal_err( String::from("integral value"), None, Position::new(1, 6, 5) )); let actual = tuple_3( p_hello(), p_u32(), p_true() ).run(String::from("helloabctrue")); assert_eq!(actual, expected); } #[test] fn tuple_3_run_simple_parsers_fails_with_fatal_error_at_third_parser() { let expected = Err(ParserFailure::new_fatal_err( String::from("true"), Some(String::from("fals")), Position::new(1, 9, 8) )); let actual = tuple_3( p_hello(), p_u32(), p_true() ).run(String::from("hello123false")); assert_eq!(actual, expected); } #[test] fn tuple_4_run_simple_parserss_succeeds() { let expected = Ok(ParserSuccess::new( (String::from("hello"), 123 , true, 1.5), Position::new(1, 16, 15) )); let actual = tuple_4( p_hello(), p_u32(), p_true(), p_f32() ).run(String::from("hello123true1.5")); assert_eq!(actual, expected); } #[test] fn tuple_4_run_simple_parsers_fails_with_error_at_first_parser() { let expected = Err(ParserFailure::new_err( String::from("hello"), Some(String::from("world")), Position::new(1, 1, 0) )); let actual = tuple_4( p_hello(), p_u32(), p_true(), p_f32() ).run(String::from("world123true1.5")); assert_eq!(actual, expected); } #[test] fn tuple_4_run_simple_parsers_fails_with_fatal_error_at_second_parser() { let expected = Err(ParserFailure::new_fatal_err( String::from("integral value"), None, Position::new(1, 6, 5) )); let actual = tuple_4( p_hello(), p_u32(), p_true(), p_f32() ).run(String::from("helloabctrue1.5")); assert_eq!(actual, expected); } #[test] fn tuple_4_run_simple_parsers_fails_with_fatal_error_at_third_parser() { let expected = Err(ParserFailure::new_fatal_err( String::from("true"), Some(String::from("fals")), Position::new(1, 9, 8) )); let actual = tuple_4( p_hello(), p_u32(), p_true(), p_f32() ).run(String::from("hello123false1.5")); assert_eq!(actual, expected); } #[test] fn tuple_4_run_simple_parsers_fails_with_fatal_error_at_fourth_parser() { let expected = Err(ParserFailure::new_fatal_err( String::from("floating point value"), None, Position::new(1, 13, 12) )); let actual = tuple_4( p_hello(), p_u32(), p_true(), p_f32() ).run(String::from("hello123trueabc")); assert_eq!(actual, expected); } #[test] fn tuple_5_run_simple_parserss_succeeds() { let expected = Ok(ParserSuccess::new( (String::from("hello"), 123 , true, 1.5, 'a'), Position::new(1, 17, 16) )); let actual = tuple_5( p_hello(), p_u32(), p_true(), p_f32(), p_char('a') ).run(String::from("hello123true1.5a")); assert_eq!(actual, expected); } #[test] fn tuple_5_run_simple_parsers_fails_with_error_at_first_parser() { let expected = Err(ParserFailure::new_err( String::from("hello"), Some(String::from("world")), Position::new(1, 1, 0) )); let actual = tuple_5( p_hello(), p_u32(), p_true(), p_f32(), p_char('a') ).run(String::from("world123true1.5a")); assert_eq!(actual, expected); } #[test] fn tuple_5_run_simple_parsers_fails_with_fatal_error_at_second_parser() { let expected = Err(ParserFailure::new_fatal_err( String::from("integral value"), None, Position::new(1, 6, 5) )); let actual = tuple_5( p_hello(), p_u32(), p_true(), p_f32(), p_char('a') ).run(String::from("helloabctrue1.5a")); assert_eq!(actual, expected); } #[test] fn tuple_5_run_simple_parsers_fails_with_fatal_error_at_third_parser() { let expected = Err(ParserFailure::new_fatal_err( String::from("true"), Some(String::from("fals")), Position::new(1, 9, 8) )); let actual = tuple_5( p_hello(), p_u32(), p_true(), p_f32(), p_char('a') ).run(String::from("hello123false1.5a")); assert_eq!(actual, expected); } #[test] fn tuple_5_run_simple_parsers_fails_with_fatal_error_at_fourth_parser() { let expected = Err(ParserFailure::new_fatal_err( String::from("floating point value"), None, Position::new(1, 13, 12) )); let actual = tuple_5( p_hello(), p_u32(), p_true(), p_f32(), p_char('a') ).run(String::from("hello123trueabca")); assert_eq!(actual, expected); } #[test] fn tuple_5_run_simple_parsers_fails_with_fatal_error_at_fifth_parser() { let expected = Err(ParserFailure::new_fatal_err( String::from("a"), Some(String::from("c")), Position::new(1, 16, 15) )); let actual = tuple_5( p_hello(), p_u32(), p_true(), p_f32(), p_char('a') ).run(String::from("hello123true1.5c")); assert_eq!(actual, expected); }
true
4b8fcb648752536f375db1cfc68305433d23757c
Rust
morri2/leonardp-chess
/hansing_gui/src/texturepack.rs
UTF-8
1,041
2.984375
3
[]
no_license
use ggez::graphics::*; use ggez::Context; pub struct Texturepack { pub piece_texture: Vec<Image>, pub placeholder: bool, } impl Texturepack { pub fn new_placeholder() -> Self { Self { piece_texture: Vec::new(), placeholder: true, } } pub fn new() -> Self { Self { piece_texture: Vec::new(), placeholder: false, } } pub fn texture_from_index(&self, index: usize) -> Option<Image> { if index >= self.piece_texture.len() { None } else { Some(self.piece_texture[index].clone()) } } } const PIECE_NAMES: [&str; 6] = ["pawn", "knight", "bishop", "rook", "queen", "king"]; pub fn make_texturepack(c: &mut Context) -> Texturepack { let mut tp = Texturepack::new(); for color in ["w", "b"].iter() { for piece in PIECE_NAMES.iter() { tp.piece_texture .push(Image::new(c, format!("/{}_{}.png", color, piece)).unwrap()); } } tp }
true
90314fd979ff038c488ca7660245ef6f21d74452
Rust
htk16/build_your_own_lisp_in_rust
/src/error.rs
UTF-8
811
3.078125
3
[]
no_license
use crate::expression::{Expression, ExpressionType}; use anyhow::{anyhow, Error}; pub fn argument_error(name: &str, required: usize, passed: usize) -> Error { anyhow!( "Function '{}' required {} argument(s), but passed {}", name, required, passed ) } pub fn type_error(required: ExpressionType, passed: ExpressionType) -> Error { anyhow!("{} required, but passed {}", required.name(), passed.name()) } pub fn expression_type_error(required: ExpressionType, passed: &Expression) -> Error { anyhow!( "{} required, but passed {} ({})", required.name(), passed.type_name(), passed.to_string() ) } pub fn divide_by_zero() -> Error { anyhow!("Divide by zero") } pub fn fatal_error() -> Error { anyhow!("Fatal error!") }
true
f3b440009a19c0b5955fe0a8c93c39cc5e7fb671
Rust
oli-obk/stdsimd
/coresimd/ppsv/api/masks_select.rs
UTF-8
1,741
2.90625
3
[ "Apache-2.0", "MIT" ]
permissive
//! Mask select method #![allow(unused)] /// Implements mask select method macro_rules! impl_mask_select { ($id:ident, $elem_ty:ident, $elem_count:expr) => { impl $id { /// Selects elements of `a` and `b` using mask. /// /// For each lane, the result contains the element of `a` if the /// mask is true, and the element of `b` otherwise. #[inline] pub fn select<T>(self, a: T, b: T) -> T where T: super::api::Lanes<[u32; $elem_count]>, { use coresimd::simd_llvm::simd_select; unsafe { simd_select(self, a, b) } } } }; } #[cfg(test)] macro_rules! test_mask_select { ($mask_id:ident, $vec_id:ident, $elem_ty:ident) => { #[test] fn select() { use coresimd::simd::{$mask_id, $vec_id}; let o = 1 as $elem_ty; let t = 2 as $elem_ty; let a = $vec_id::splat(o); let b = $vec_id::splat(t); let m = a.lt(b); assert_eq!(m.select(a, b), a); let m = b.lt(a); assert_eq!(m.select(b, a), a); let mut c = a; let mut d = b; let mut m_e = $mask_id::splat(false); for i in 0..$vec_id::lanes() { if i % 2 == 0 { let c_tmp = c.extract(i); c = c.replace(i, d.extract(i)); d = d.replace(i, c_tmp); } else { m_e = m_e.replace(i, true); } } let m = c.lt(d); assert_eq!(m_e, m); assert_eq!(m.select(c, d), a); } }; }
true
adc493372f1d80fce1493c1c4fe92be471cee502
Rust
tov/succinct-rs
/src/rank/prim.rs
UTF-8
2,698
2.890625
3
[ "MIT", "Apache-2.0" ]
permissive
use rank::{BitRankSupport, RankSupport}; use storage::BlockType; macro_rules! impl_rank_support_prim { ( $t:ident ) => { impl RankSupport for $t { type Over = bool; fn rank(&self, position: u64, value: bool) -> u64 { if value {self.rank1(position)} else {self.rank0(position)} } fn limit(&self) -> u64 { Self::nbits() as u64 } } impl BitRankSupport for $t { fn rank1(&self, position: u64) -> u64 { debug_assert!(position < Self::nbits() as u64); let mask = Self::low_mask((position + 1) as usize); (*self & mask).count_ones() as u64 } } } } impl_rank_support_prim!(u8); impl_rank_support_prim!(u16); impl_rank_support_prim!(u32); impl_rank_support_prim!(u64); impl_rank_support_prim!(usize); #[cfg(test)] mod test { use rank::*; #[test] fn rank1() { assert_eq!(0, 0b00000000u8.rank1(0)); assert_eq!(0, 0b00000000u8.rank1(7)); assert_eq!(1, 0b01010101u8.rank1(0)); assert_eq!(1, 0b01010101u8.rank1(1)); assert_eq!(2, 0b01010101u8.rank1(2)); assert_eq!(2, 0b01010101u8.rank1(3)); assert_eq!(3, 0b00001111u8.rank1(2)); assert_eq!(4, 0b00001111u8.rank1(3)); assert_eq!(4, 0b00001111u8.rank1(4)); assert_eq!(4, 0b00001111u8.rank1(5)); assert_eq!(4, 0b00001111u8.rank1(7)); assert_eq!(0, 0b11110000u8.rank1(0)); assert_eq!(0, 0b11110000u8.rank1(3)); assert_eq!(1, 0b11110000u8.rank1(4)); assert_eq!(2, 0b11110000u8.rank1(5)); assert_eq!(4, 0b11110000u8.rank1(7)); } #[test] fn rank0() { assert_eq!(1, 0b00000000u8.rank0(0)); assert_eq!(8, 0b00000000u8.rank0(7)); assert_eq!(0, 0b01010101u8.rank0(0)); assert_eq!(1, 0b01010101u8.rank0(1)); assert_eq!(1, 0b01010101u8.rank0(2)); assert_eq!(2, 0b01010101u8.rank0(3)); } #[test] fn rank() { assert_eq!(1, 0b00000000u8.rank(0, false)); assert_eq!(8, 0b00000000u8.rank(7, false)); assert_eq!(0, 0b01010101u8.rank(0, false)); assert_eq!(1, 0b01010101u8.rank(1, false)); assert_eq!(1, 0b01010101u8.rank(2, false)); assert_eq!(2, 0b01010101u8.rank(3, false)); assert_eq!(0, 0b00000000u8.rank(0, true)); assert_eq!(0, 0b00000000u8.rank(7, true)); assert_eq!(1, 0b01010101u8.rank(0, true)); assert_eq!(1, 0b01010101u8.rank(1, true)); assert_eq!(2, 0b01010101u8.rank(2, true)); assert_eq!(2, 0b01010101u8.rank(3, true)); } }
true
f47bc13d0a34d2272755d51dc23cea2753f2a5d7
Rust
torourk/padding-oracle-visual
/src/main.rs
UTF-8
1,752
2.671875
3
[ "MIT", "Apache-2.0" ]
permissive
use aes::Aes128; use block_modes::block_padding::Pkcs7; use block_modes::{BlockMode, Cbc}; use hkdf::Hkdf; use sha2::Sha256; use rand::rngs::OsRng; use rand::RngCore; use colored::*; use std::io::{self, Write}; pub mod adversary; pub mod oracle; pub mod ui; use adversary::Adversary; use oracle::Oracle; type Aes128Cbc = Cbc<Aes128, Pkcs7>; fn main() { println!("{}", "--- Padding Oracle Attack ---".bold()); print!( "{}{}{}", "Enter key ", "(Derived using SHA256-HKDF)".italic(), ": " ); io::stdout().flush().unwrap(); // Reads a key string let mut key_str = String::new(); io::stdin().read_line(&mut key_str).unwrap(); print!("Enter message: "); io::stdout().flush().unwrap(); // Reads a message string let mut msg_str = String::new(); io::stdin().read_line(&mut msg_str).unwrap(); if msg_str.ends_with("\n") { msg_str.truncate(msg_str.len() - 1); } // Derives a key using HKDF-SHA256 (weak password key derivation is sufficient for demonstration purposes) let hkdf = Hkdf::<Sha256>::new(None, key_str.as_bytes()); let mut key = [0u8; 16]; hkdf.expand(&[], &mut key).unwrap(); // Creates a random IV let mut iv = [0u8; 16]; OsRng.fill_bytes(&mut iv); // Encrypts the message using AES-128 in CBC mode let aes_cipher = Aes128Cbc::new_var(&key, &iv).unwrap(); let cipher = aes_cipher.encrypt_vec(msg_str.as_bytes()); // Creates a keyed oracle let oracle = Oracle::new(&key); // Sends the oracle, IV, and ciphertext to the adversary let adversary = Adversary::new(oracle, iv.to_vec(), cipher.clone()); println!(); // Runs the attack adversary.break_ciphertext_fancy(); }
true
47c43205b241d5e519df64d54b334483fd9701e4
Rust
zexa/json_gatherer
/src/main.rs
UTF-8
1,175
3.046875
3
[ "MIT" ]
permissive
use serde_json; use std::fs; use std::io; use std::path::Path; use std::path::PathBuf; use std::collections::HashMap; struct JsonFile { stem: String, content: String, } fn get_dir_json(P: &Path) -> io::Result<()> { let entries = fs::read_dir(P)? .map(|res| res.map(|e| e.path())) .map(|path| path.map(|p| get_file_json(p).unwrap())) .collect::<Result<Vec<_>, io::Error>>()?; Ok(()) } fn serialize_json_file(input: Vec<JsonFile>) -> io::Result<serde_json::Value> { let hash: HashMap<String, serde_json::Value> = HashMap::new(); in Ok() } fn get_file_json(file: PathBuf) -> io::Result<JsonFile> { Ok(JsonFile { stem: match file.file_stem() { None => panic!("Could not read file stem"), Some(file_stem) => match file_stem.to_str() { None => panic!("Could not convert OsStr to String"), Some(file_stem_str) => file_stem_str, } }.to_string(), content: fs::read_to_string(file)? }) } fn main() { get_dir_json(Path::new("/home/zexa/Projects/get-files/src/examples")) .expect("Could not read directory"); }
true
7e4864b2fcd1fb13428c10492b3e0aa9f23ea016
Rust
germolinal/PhD_Thesis_Simulations
/src/lib.rs
UTF-8
2,352
2.84375
3
[]
no_license
use std::collections::HashMap; use simulation_state::simulation_state::SimulationState; use building_model::building::Building; use communication_protocols::simulation_model::SimulationModel; use calendar::date_factory::DateFactory; use calendar::date::Date; use people::people::People; use multiphysics_model::multiphysics_model::MultiphysicsModel; use weather::Weather; use simple_results::{SimulationResults, TimeStepResults}; /// This function drives the simulation, after having parsed and built /// the Building, State and Peoeple. pub fn run(start: Date, end: Date, person: &dyn People, building: &mut Building, state: &mut SimulationState, weather: &dyn Weather, n: usize)->Result<SimulationResults,String>{ if start == end || start.is_later(end) { return Err(format!("Time period inconsistency... Start = {} | End = {}", start, end)); } let model = match MultiphysicsModel::new(&building, state, n){ Ok(v)=>v, Err(e)=>return Err(e), }; // Map the state building.map_simulation_state(state)?; // Calculate timestep and build the Simulation Period let dt = 60. * 60. / n as f64; let sim_period = DateFactory::new(start, end, dt); // TODO: Calculate the capacity needed for the results let mut results = SimulationResults::new(); // Simulate the whole simulation period for date in sim_period { // initialize results struct let mut step_results = TimeStepResults{ timestep_start : date, state_elements : state.elements().clone(), weather : weather.get_weather_data(date), controllers: HashMap::new() }; // Get the current weather data //let current_weather = weather.get_weather_data(date); // Make the model march match model.march(date, weather, building, state ) { Ok(_)=>{}, Err(e) => panic!(e) } // Control the building or person, if needed let person_result = person.control(date, weather, building, &model, state); step_results.controllers.insert(format!("person"), person_result); // push results results.push(step_results); } Ok(results) }
true
978dafdab1d99635532f89a8593fd37b773897e1
Rust
karjonas/advent-of-code
/2016/day18/src/lib.rs
UTF-8
1,658
3.203125
3
[]
no_license
use std::fs::File; use std::io::prelude::*; fn is_trap(r: usize, c: usize, num_cols: usize, grid: &Vec<Vec<bool>>) -> bool { let left = if c == 0 { false } else { grid[r - 1][c - 1] }; let center = grid[r - 1][c]; let right = if c == num_cols - 1 { false } else { grid[r - 1][c + 1] }; let p = (left, center, right); return p == (true, true, false) || p == (false, true, true) || p == (true, false, false) || p == (false, false, true); } fn generate_rows(start: Vec<bool>, num_rows_inclusive: usize) -> Vec<Vec<bool>> { let num_cols = start.len(); let mut output: Vec<Vec<bool>> = Vec::new(); output.resize(num_rows_inclusive, Vec::new()); output[0] = start; for row in 1..(num_rows_inclusive) { output[row].resize(num_cols, false); for col in 0..num_cols { output[row][col] = is_trap(row, col, num_cols, &output); } } return output; } fn solve_internal(path: &str, rows: usize) -> usize { let mut file = File::open(path).unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); let start: Vec<bool> = contents .chars() .filter(|&c| c == '.' || c == '^') .map(|c| c == '^') .collect(); let output = generate_rows(start, rows); let nums = output.iter().fold(0, |sum, v| { sum + v.iter().fold(0, |sum, &v0| sum + if !v0 { 1 } else { 0 }) }); return nums; } pub fn solve() { println!("Part 1: {}", solve_internal("2016/day18/input", 40)); println!("Part 2: {}", solve_internal("2016/day18/input", 400000)); }
true
1174ba0b92b569c91b5693a88cccfea48065e6cd
Rust
pisa-engine/trec-text-rs
/src/lib.rs
UTF-8
12,737
3.390625
3
[ "Apache-2.0" ]
permissive
#![doc(html_root_url = "https://docs.rs/trec-text/0.1.0")] //! Parsing TREC Text format. //! //! TREC Text is a text format containing a sequence of records: //! `<DOC> <DOCNO> 0 </DOCNO> Text body </DOC>` //! //! # Examples //! //! Typically, document records will be read from files. //! [`Parser`](struct.Parser.html) can be constructer from any structure that implements //! [`Read`](https://doc.rust-lang.org/std/io/trait.Read.html), //! and implements [`Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html). //! //! Because parsing of a record can fail, either due to IO error or corupted records, //! the iterator returns elements of `Result<DocumentRecord>`. //! //! ``` //! # use trec_text::*; //! # fn main() -> Result<()> { //! use std::io::Cursor; //! //! let input = r#" //!<DOC> <DOCNO> 0 </DOCNO> zero </DOC> //!CORRUPTED <DOCNO> 1 </DOCNO> ten </DOC> //!<DOC> <DOCNO> 2 </DOCNO> ten nine </DOC> //! "#; //! let mut parser = Parser::new(Cursor::new(input)); //! //! let document = parser.next().unwrap()?; //! assert_eq!(String::from_utf8_lossy(document.docno()), "0"); //! assert_eq!(String::from_utf8_lossy(document.content()), " zero "); //! //! assert!(parser.next().unwrap().is_err()); //! //! let document = parser.next().unwrap()?; //! assert_eq!(String::from_utf8_lossy(document.docno()), "2"); //! assert_eq!(String::from_utf8_lossy(document.content()), " ten nine "); //! //! assert!(parser.next().is_none()); //! # Ok(()) //! # } //! ``` pub use anyhow::Result; use anyhow::anyhow; use std::io::{self, Read}; use std::iter::Peekable; /// TREC Text record data. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DocumentRecord { docno: Vec<u8>, content: Vec<u8>, } impl DocumentRecord { /// Retrieves `DOCNO` field bytes. Any whitespaces proceeding `<DOCNO>` and preceeding /// `</DOCNO>` are trimmed. #[must_use] pub fn docno(&self) -> &[u8] { &self.docno } /// Retrieves content bytes. #[must_use] pub fn content(&self) -> &[u8] { &self.content } } /// TREC Text format parser. pub struct Parser<B> where B: Iterator<Item = io::Result<u8>>, { bytes: Peekable<B>, in_progress: bool, } impl<R: Read> Parser<io::Bytes<R>> { /// Consumes the reader and returns a new TREC Text parser starting at the beginning. pub fn new(reader: R) -> Self { Self { bytes: reader.bytes().peekable(), in_progress: false, } } } impl<B> Parser<B> where B: Iterator<Item = io::Result<u8>>, { /// Returns the underlying iterator of remaining bytes. pub fn into_bytes(self) -> impl Iterator<Item = Result<u8>> { self.bytes.map(|elem| elem.map_err(anyhow::Error::new)) } fn consume_tag_discarding_prefix(&mut self, tag: &str) -> Result<()> { let pattern: Vec<_> = tag.bytes().collect(); let mut pos = 0; for byte in &mut self.bytes { pos = byte.map(|b| if pattern[pos] == b { pos + 1 } else { 0 })?; if pos == pattern.len() { return Ok(()); } } Err(anyhow!("Unexpected EOF")) } fn skip_whitespaces(&mut self) -> Result<()> { while let Some(byte) = self.bytes.peek() { match byte { Ok(byte) => { if !byte.is_ascii_whitespace() { break; } } Err(err) => { return Err(anyhow!(format!("{}", err))); } } self.bytes.next(); } Ok(()) } fn consume_tag_with_prefix(&mut self, tag: &str) -> Result<Vec<u8>> { let pattern: Vec<_> = tag.bytes().collect(); let mut buf: Vec<u8> = Vec::new(); let mut pos = 0; for byte in &mut self.bytes { pos = byte.map(|b| { buf.push(b); if pattern[pos] == b { pos + 1 } else { 0 } })?; if pos == pattern.len() { buf.drain(buf.len() - pattern.len()..); return Ok(buf); } } Err(anyhow!("Unexpected EOF")) } fn consume_tag(&mut self, tag: &str) -> Result<()> { for byte in tag.bytes() { if let Some(b) = self.bytes.next() { if b? != byte { return Err(anyhow!(format!("Unable to consume tag: {}", tag))); } } else { return Err(anyhow!("Unexpected EOF")); } } Ok(()) } fn next_document(&mut self) -> Result<DocumentRecord> { if self.in_progress { self.consume_tag_discarding_prefix("<DOC>")?; } else { self.in_progress = true; self.skip_whitespaces()?; self.consume_tag("<DOC>")?; } self.skip_whitespaces()?; self.consume_tag("<DOCNO>")?; self.skip_whitespaces()?; let mut docno = self.consume_tag_with_prefix("</DOCNO>")?; let ws_suffix = docno .iter() .copied() .rev() .take_while(u8::is_ascii_whitespace) .count(); docno.drain(docno.len() - ws_suffix..); let content = self.consume_tag_with_prefix("</DOC>")?; self.skip_whitespaces()?; self.in_progress = false; Ok(DocumentRecord { docno, content }) } } impl<B> Iterator for Parser<B> where B: Iterator<Item = io::Result<u8>>, { type Item = Result<DocumentRecord>; fn next(&mut self) -> Option<Self::Item> { if self.bytes.peek().is_none() { None } else { Some(self.next_document()) } } } #[cfg(test)] mod test { use super::*; use std::io::Cursor; fn assert_rest_eq<B>(parser: Parser<B>, expected: &str) -> Result<()> where B: Iterator<Item = io::Result<u8>> + 'static, { let rest: Result<Vec<_>> = parser.into_bytes().collect(); assert_eq!(rest?, expected.bytes().collect::<Vec<_>>()); Ok(()) } #[test] fn test_consume_tag() -> Result<()> { let input = "<DOC>"; let mut parser = Parser::new(Cursor::new(input)); assert!(parser.consume_tag("<DOC>").is_ok()); assert_rest_eq(parser, "") } #[test] fn test_consume_tag_fails() -> Result<()> { let input = "DOC>"; let mut parser = Parser::new(Cursor::new(input)); assert!(parser.consume_tag("<DOC>").is_err()); assert_rest_eq(parser, "OC>") } #[test] fn test_consume_tag_with_remaining_bytes() -> Result<()> { let mut parser = Parser::new(Cursor::new("<DOC>rest")); assert!(parser.consume_tag("<DOC>").is_ok()); assert_rest_eq(parser, "rest") } #[test] fn test_consume_tag_discarding_prefix_no_prefix() -> Result<()> { let mut parser = Parser::new(Cursor::new("<DOC>rest")); assert!(parser.consume_tag_discarding_prefix("<DOC>").is_ok()); assert_rest_eq(parser, "rest") } #[test] fn test_consume_tag_discarding_prefix_garbage_prefix() -> Result<()> { let mut parser = Parser::new(Cursor::new("xxx dsfa sdaf///<<<>>><DOC>rest")); assert!(parser.consume_tag_discarding_prefix("<DOC>").is_ok()); assert_rest_eq(parser, "rest") } #[test] fn test_consume_tag_discarding_prefix_no_matching_tag() -> Result<()> { let mut parser = Parser::new(Cursor::new("xxx dsfa sdaf///<<<>>>")); assert!(parser.consume_tag_discarding_prefix("<DOC>").is_err()); Ok(()) } #[test] fn test_consume_tag_with_prefix_no_prefix() -> Result<()> { let mut parser = Parser::new(Cursor::new("</DOC>rest")); assert!(parser.consume_tag_with_prefix("</DOC>").is_ok()); assert_rest_eq(parser, "rest") } #[test] fn test_consume_tag_with_prefix_content() -> Result<()> { let mut parser = Parser::new(Cursor::new("xxx dsfa sdaf///<<<>>></DOC>rest")); assert_eq!( parser.consume_tag_with_prefix("</DOC>").unwrap(), "xxx dsfa sdaf///<<<>>>".bytes().collect::<Vec<_>>() ); assert_rest_eq(parser, "rest") } #[test] fn test_consume_tag_with_prefix_no_matching_tag() -> Result<()> { let mut parser = Parser::new(Cursor::new("xxx dsfa sdaf///<<<>>>")); assert!(parser.consume_tag_with_prefix("<DOC>").is_err()); Ok(()) } #[test] fn test_next_document() -> Result<()> { let input = r#" <DOC> <DOCNO> 0 </DOCNO> zero </DOC> <DOC> <DOCNO> 1 </DOCNO> ten </DOC> <DOC> <DOCNO> 2 </DOCNO> ten nine </DOC> "#; let mut parser = Parser::new(Cursor::new(input)); let document = parser.next_document()?; assert_eq!(String::from_utf8_lossy(document.docno()), "0"); assert_eq!(String::from_utf8_lossy(document.content()), " zero "); let document = parser.next_document()?; assert_eq!(String::from_utf8_lossy(document.docno()), "1"); assert_eq!(String::from_utf8_lossy(document.content()), " ten "); let document = parser.next_document()?; assert_eq!(String::from_utf8_lossy(document.docno()), "2"); assert_eq!(String::from_utf8_lossy(document.content()), " ten nine "); Ok(()) } #[test] fn test_iter_documents() -> Result<()> { let input = r#" <DOC> <DOCNO> 0 </DOCNO> zero </DOC> CORRUPTED <DOCNO> 1 </DOCNO> ten </DOC> <DOC> <DOCNO> 2 </DOCNO> ten nine </DOC> "#; let mut parser = Parser::new(Cursor::new(input)); let document = parser.next().unwrap()?; assert_eq!(String::from_utf8_lossy(document.docno()), "0"); assert_eq!(String::from_utf8_lossy(document.content()), " zero "); assert!(parser.next().unwrap().is_err()); assert!(parser.in_progress); let document = parser.next().unwrap()?; assert_eq!(String::from_utf8_lossy(document.docno()), "2"); assert_eq!(String::from_utf8_lossy(document.content()), " ten nine "); assert!(parser.next().is_none()); Ok(()) } #[test] fn test_parse_jassjr_example() -> io::Result<()> { let input = r#" <DOC> <DOCNO> 0 </DOCNO> zero </DOC> <DOC> <DOCNO> 1 </DOCNO> ten </DOC> <DOC> <DOCNO> 2 </DOCNO> ten nine </DOC> <DOC> <DOCNO> 3 </DOCNO> ten nine eight </DOC> <DOC> <DOCNO> 4 </DOCNO> ten nine eight seven </DOC> <DOC> <DOCNO> 5 </DOCNO> ten nine eight seven six </DOC> <DOC> <DOCNO> 6 </DOCNO> ten nine eight seven six five </DOC> <DOC> <DOCNO> 7 </DOCNO> ten nine eight seven six five four </DOC> <DOC> <DOCNO> 8 </DOCNO> ten nine eight seven six five four three </DOC> <DOC> <DOCNO> 9 </DOCNO> ten nine eight seven six five four three two </DOC> <DOC> <DOCNO> 10 </DOCNO> ten nine eight seven six five four three two one </DOC> "#; let documents: Result<Vec<_>> = Parser::new(Cursor::new(input)).collect(); assert!(documents.is_ok()); let documents: Vec<_> = documents .unwrap() .into_iter() .map(|doc| { ( String::from_utf8_lossy(doc.docno()).trim().to_string(), String::from_utf8_lossy(doc.content()).trim().to_string(), ) }) .collect(); assert_eq!( documents, vec![ (String::from("0"), String::from("zero")), (String::from("1"), String::from("ten")), (String::from("2"), String::from("ten nine")), (String::from("3"), String::from("ten nine eight")), (String::from("4"), String::from("ten nine eight seven")), (String::from("5"), String::from("ten nine eight seven six")), ( String::from("6"), String::from("ten nine eight seven six five") ), ( String::from("7"), String::from("ten nine eight seven six five four") ), ( String::from("8"), String::from("ten nine eight seven six five four three") ), ( String::from("9"), String::from("ten nine eight seven six five four three two") ), ( String::from("10"), String::from("ten nine eight seven six five four three two one") ), ] ); Ok(()) } }
true
a17d0e7c65c96276a36315ebc13c91df38e416bd
Rust
jahfer/accountant
/src/transaction/presidents_choice.rs
UTF-8
2,413
2.71875
3
[]
no_license
use std::path::Path; use super::csv_import; use super::{Transaction, ImportableTransaction, TransactionSource, Format, to_hash}; use ::money::Money; use std::hash::{Hash, Hasher}; use chrono::{TimeZone, DateTime, UTC}; use regex::Regex; #[derive(RustcDecodable)] pub struct Csv { transaction_date: String, _posting_date: String, amount: String, merchant: String, _merchant_city: String, _merchant_state: String, _merchant_zip: String, reference: String, _direction: char, _sicmcc_code: u16 } impl Csv { fn date_as_datetime(&self) -> DateTime<UTC> { lazy_static! { static ref RE: Regex = Regex::new(r"^(\d{1,2})/(\d{1,2})/(\d{4})$").unwrap(); } let captures = RE.captures(&self.transaction_date).unwrap(); let (month, day, year) = (captures.at(1), captures.at(2), captures.at(3)); UTC.ymd( year.unwrap().parse::<i32>().unwrap(), month.unwrap().parse::<u32>().unwrap(), day.unwrap().parse::<u32>().unwrap() ).and_hms(0,0,0) } // PC uses + amounts for credits, () amounts for debits fn formatted_amount(&self) -> String { let debit_re = Regex::new(r"\((.*)\)").unwrap(); let amount_re = Regex::new(r"([\d\.,]+)").unwrap(); let is_debit = debit_re.is_match(&self.amount); match amount_re.captures(&self.amount) { Some(captures) => { let amount = captures.at(1).unwrap(); if !is_debit { String::from("-") + amount } else { amount.to_string() } }, None => panic!("Unable to parse CSV field as money") } } } impl Hash for Csv { fn hash<H: Hasher>(&self, state: &mut H) { self.reference.hash(state) } } impl ImportableTransaction for Csv { fn import(file_path: &Path) -> Vec<Transaction> { csv_import::read::<Csv>(file_path, true) .into_iter() .map(|tx| Transaction { source: TransactionSource::PresidentsChoice(Format::CSV), identifier: to_hash(&tx), date: tx.date_as_datetime(), description: None, note: None, amount: Money::parse(&tx.formatted_amount()), merchant: tx.merchant }).collect() } }
true
bbd16c6b308ccc0430e960abe5e360a948ba00f1
Rust
ZoeyR/wearte
/testing/tests/benchs.rs
UTF-8
1,566
3.34375
3
[ "MIT", "Apache-2.0" ]
permissive
use wearte::Template; #[test] fn big_table() { let size = 3; let mut table = Vec::with_capacity(size); for _ in 0..size { let mut inner = Vec::with_capacity(size); for i in 0..size { inner.push(i); } table.push(inner); } let table = BigTable { table }; assert_eq!(table.call().unwrap(), "<table><tr><td>0</td><td>1</td><td>2</td></tr><tr><td>0</td><td>1</td><td>2</td></tr><tr><td>0</td><td>1</td><td>2</td></tr></table>"); } #[derive(Template)] #[template(path = "big-table.html")] struct BigTable { table: Vec<Vec<usize>>, } #[test] fn teams() { let teams = Teams { year: 2015, teams: vec![ Team { name: "Jiangsu".into(), score: 43, }, Team { name: "Beijing".into(), score: 27, }, Team { name: "Guangzhou".into(), score: 22, }, Team { name: "Shandong".into(), score: 12, }, ], }; assert_eq!(teams.call().unwrap(), "<html><head><title>2015</title></head><body><h1>CSL 2015</h1><ul><li class=\"champion\"><b>Jiangsu</b>: 43</li><li class=\"\"><b>Beijing</b>: 27</li><li class=\"\"><b>Guangzhou</b>: 22</li><li class=\"\"><b>Shandong</b>: 12</li></ul></body></html>"); } #[derive(Template)] #[template(path = "teams.html")] struct Teams { year: u16, teams: Vec<Team>, } struct Team { name: String, score: u8, }
true
56fda6a82c3e79e7d839680c73599d4e831c27a0
Rust
Jaxelr/RustTutorial
/Rust Cookbook/12_01_1_read_and_write_files/src/main.rs
UTF-8
1,491
3.125
3
[]
no_license
use std::fs::File; use same_file::Handle; use memmap::Mmap; use std::io::{Write, BufReader, BufRead, Error, ErrorKind}; use std::path::Path; fn main() -> Result<(), Box <dyn std::error::Error>> { read_write_file()?; same_file()?; random_memory()?; Ok(()) } fn read_write_file() -> Result<(), Error> { let path = "lines.txt"; let mut output = File::create(path)?; write!(output, "Rust\n💖\nFun")?; let input = File::open(path)?; let buffered = BufReader::new(input); for line in buffered.lines() { println!("{}", line?); } Ok(()) } fn same_file() -> Result<(), Error> { let path_to_read = Path::new("new.txt"); let stdout_handle = Handle::stdout()?; let handle = Handle::from_path(path_to_read)?; if stdout_handle == handle { return Err(Error::new( ErrorKind::Other, "You are reading and writing to the same file", )); } else { let file = File::open(&path_to_read)?; let file = BufReader::new(file); for (num, line) in file.lines().enumerate() { println!("{} : {}", num, line?.to_uppercase()); } } Ok(()) } fn random_memory() -> Result<(), Error> { let file = File::open("content.txt")?; let map = unsafe { Mmap::map(&file)? }; let random_indexes = [0, 1, 2, 19, 22, 10, 11, 29]; let _random_bytes: Vec<u8> = random_indexes.iter() .map(|&idx| map[idx]) .collect(); Ok(()) }
true
16d2253599b3a1fa9c3ec0e7e1a316a4ba3b4b27
Rust
modelflat/twitchbot
/src/state.rs
UTF-8
1,414
2.765625
3
[]
no_license
use async_std::sync::RwLock; use std::collections::{BTreeSet, HashMap}; use crate::executor::ShareableExecutableCommand; use crate::irc; use crate::permissions::PermissionList; pub type Commands<T> = HashMap<String, ShareableExecutableCommand<T>>; pub struct BotState<T: 'static + Send + Sync> { pub username: String, pub prefix: String, pub channels: BTreeSet<String>, pub commands: Commands<T>, pub permissions: PermissionList, pub data: RwLock<T>, } impl<T: 'static + Send + Sync> BotState<T> { pub fn new( username: String, prefix: String, channels: Vec<String>, commands: Commands<T>, permissions: PermissionList, data: T, ) -> BotState<T> { BotState { username, prefix, channels: channels.into_iter().map(|s| s.to_string()).collect(), commands, permissions, data: RwLock::new(data), } } pub fn try_convert_to_command(&self, message: &irc::Message) -> Option<String> { if let Some(s) = message.trailing { if s.starts_with(&self.prefix) { return Some((&s[self.prefix.len()..]).trim_start().to_string()); } if s.starts_with(&self.username) { return Some((&s[self.username.len()..]).trim_start().to_string()); } } None } }
true
07bc5a3bb6501e0fabcb458956b399a89779f61e
Rust
tertsdiepraam/vrp
/vrp-core/src/models/common/load.rs
UTF-8
8,491
3.09375
3
[ "Apache-2.0" ]
permissive
#[cfg(test)] #[path = "../../../tests/unit/models/domain/load_test.rs"] mod load_test; use crate::models::common::{Dimensions, ValueDimension}; use std::cmp::Ordering; use std::iter::Sum; use std::ops::{Add, Mul, Sub}; const CAPACITY_DIMENSION_KEY: &str = "cpc"; const DEMAND_DIMENSION_KEY: &str = "dmd"; const LOAD_DIMENSION_SIZE: usize = 8; /// Represents a load type used to represent customer's demand or vehicle's load. pub trait Load: Add + Sub + Ord + Copy + Default + Send + Sync { /// Returns true if it represents an empty load. fn is_not_empty(&self) -> bool; /// Returns max load value. fn max_load(self, other: Self) -> Self; /// Returns true if `other` can be loaded into existing capacity. fn can_fit(&self, other: &Self) -> bool; /// Returns ratio. fn ratio(&self, other: &Self) -> f64; } /// Represents job demand, both static and dynamic. pub struct Demand<T: Load + Add<Output = T> + Sub<Output = T> + 'static> { /// Keeps static and dynamic pickup amount. pub pickup: (T, T), /// Keeps static and dynamic delivery amount. pub delivery: (T, T), } /// A trait to get or set vehicle's capacity. pub trait CapacityDimension<T: Load + Add<Output = T> + Sub<Output = T> + 'static> { /// Sets capacity. fn set_capacity(&mut self, demand: T) -> &mut Self; /// Gets capacity. fn get_capacity(&self) -> Option<&T>; } /// A trait to get or set demand. pub trait DemandDimension<T: Load + Add<Output = T> + Sub<Output = T> + 'static> { /// Sets demand. fn set_demand(&mut self, demand: Demand<T>) -> &mut Self; /// Gets demand. fn get_demand(&self) -> Option<&Demand<T>>; } impl<T: Load + Add<Output = T> + Sub<Output = T> + 'static> Demand<T> { /// Returns capacity change as difference between pickup and delivery. pub fn change(&self) -> T { self.pickup.0 + self.pickup.1 - self.delivery.0 - self.delivery.1 } } impl<T: Load + Add<Output = T> + Sub<Output = T> + 'static> Default for Demand<T> { fn default() -> Self { Self { pickup: (Default::default(), Default::default()), delivery: (Default::default(), Default::default()) } } } impl<T: Load + Add<Output = T> + Sub<Output = T> + 'static> Clone for Demand<T> { fn clone(&self) -> Self { Self { pickup: self.pickup, delivery: self.delivery } } } impl<T: Load + Add<Output = T> + Sub<Output = T> + 'static> CapacityDimension<T> for Dimensions { fn set_capacity(&mut self, demand: T) -> &mut Self { self.set_value(CAPACITY_DIMENSION_KEY, demand); self } fn get_capacity(&self) -> Option<&T> { self.get_value(CAPACITY_DIMENSION_KEY) } } impl<T: Load + Add<Output = T> + Sub<Output = T> + 'static> DemandDimension<T> for Dimensions { fn set_demand(&mut self, demand: Demand<T>) -> &mut Self { self.set_value(DEMAND_DIMENSION_KEY, demand); self } fn get_demand(&self) -> Option<&Demand<T>> { self.get_value(DEMAND_DIMENSION_KEY) } } /// Specifies single dimensional load type. #[derive(Clone, Copy, Debug)] pub struct SingleDimLoad { /// An actual load value. pub value: i32, } impl SingleDimLoad { /// Creates a new instance of `SingleDimLoad`. pub fn new(value: i32) -> Self { Self { value } } } impl Default for SingleDimLoad { fn default() -> Self { Self { value: 0 } } } impl Load for SingleDimLoad { fn is_not_empty(&self) -> bool { self.value != 0 } fn max_load(self, other: Self) -> Self { let value = self.value.max(other.value); Self { value } } fn can_fit(&self, other: &Self) -> bool { self.value >= other.value } fn ratio(&self, other: &Self) -> f64 { self.value as f64 / other.value as f64 } } impl Add for SingleDimLoad { type Output = Self; fn add(self, rhs: Self) -> Self::Output { let value = self.value + rhs.value; Self { value } } } impl Sub for SingleDimLoad { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { let value = self.value - rhs.value; Self { value } } } impl Ord for SingleDimLoad { fn cmp(&self, other: &Self) -> Ordering { self.value.cmp(&other.value) } } impl PartialOrd for SingleDimLoad { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Eq for SingleDimLoad {} impl PartialEq for SingleDimLoad { fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal } } impl Mul<f64> for SingleDimLoad { type Output = Self; fn mul(self, value: f64) -> Self::Output { Self::new((self.value as f64 * value).round() as i32) } } /// Specifies multi dimensional load type. #[derive(Clone, Copy, Debug)] pub struct MultiDimLoad { /// Load data. pub load: [i32; LOAD_DIMENSION_SIZE], /// Actual used size. pub size: usize, } impl MultiDimLoad { /// Creates a new instance of `MultiDimLoad`. pub fn new(data: Vec<i32>) -> Self { assert!(data.len() <= LOAD_DIMENSION_SIZE); let mut load = [0; LOAD_DIMENSION_SIZE]; for (idx, value) in data.iter().enumerate() { load[idx] = *value; } Self { load, size: data.len() } } fn get(&self, idx: usize) -> i32 { self.load[idx] } /// Converts to vector representation. pub fn as_vec(&self) -> Vec<i32> { if self.size == 0 { vec![0] } else { self.load[..self.size].to_vec() } } } impl Load for MultiDimLoad { fn is_not_empty(&self) -> bool { self.size == 0 || self.load.iter().any(|v| *v != 0) } fn max_load(self, other: Self) -> Self { let mut result = self; result.load.iter_mut().zip(other.load.iter()).for_each(|(a, b)| *a = (*a).max(*b)); result } fn can_fit(&self, other: &Self) -> bool { self.load.iter().zip(other.load.iter()).all(|(a, b)| a >= b) } fn ratio(&self, other: &Self) -> f64 { self.load.iter().zip(other.load.iter()).fold(0., |acc, (a, b)| (*a as f64 / *b as f64).max(acc)) } } impl Default for MultiDimLoad { fn default() -> Self { Self { load: [0; LOAD_DIMENSION_SIZE], size: 0 } } } impl Add for MultiDimLoad { type Output = Self; fn add(self, rhs: Self) -> Self::Output { fn sum(acc: MultiDimLoad, rhs: &MultiDimLoad) -> MultiDimLoad { let mut dimens = acc; for (idx, value) in rhs.load.iter().enumerate() { dimens.load[idx] += *value; } dimens.size = dimens.size.max(rhs.size); dimens } if self.load.len() >= rhs.load.len() { sum(self, &rhs) } else { sum(rhs, &self) } } } impl Sub for MultiDimLoad { type Output = Self; fn sub(self, rhs: Self) -> Self::Output { let mut dimens = self; for (idx, value) in rhs.load.iter().enumerate() { dimens.load[idx] -= *value; } dimens.size = dimens.size.max(rhs.size); dimens } } impl Ord for MultiDimLoad { fn cmp(&self, other: &Self) -> Ordering { let size = self.load.len().max(other.load.len()); (0..size).fold(Ordering::Equal, |acc, idx| match acc { Ordering::Greater => Ordering::Greater, Ordering::Equal => self.get(idx).cmp(&other.get(idx)), Ordering::Less => { if self.get(idx) > other.get(idx) { Ordering::Greater } else { Ordering::Less } } }) } } impl PartialOrd for MultiDimLoad { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Eq for MultiDimLoad {} impl PartialEq for MultiDimLoad { fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal } } impl Mul<f64> for MultiDimLoad { type Output = Self; fn mul(self, value: f64) -> Self::Output { let mut dimens = self; dimens.load.iter_mut().for_each(|item| { *item = (*item as f64 * value).round() as i32; }); dimens } } impl Sum for MultiDimLoad { fn sum<I: Iterator<Item = MultiDimLoad>>(iter: I) -> Self { iter.fold(MultiDimLoad::default(), |acc, item| item + acc) } }
true
99dbc187a9b4dcacd3a9134ed884b8a22db1d95f
Rust
dpchamps/rust-exercism
/raindrops/src/lib.rs
UTF-8
459
3.125
3
[]
no_license
pub fn raindrops(n: u32) -> String { let result = vec![3, 5, 7].iter().fold(String::new(), |str, factor| { if n % factor != 0 { return str; } let noise = match factor { 3 => "Pling", 5 => "Plang", 7 => "Plong", _ => unreachable!(), }; format!("{}{}", str, noise) }); if &result == "" { n.to_string() } else { result } }
true
7104fc0ed3eb38c354b90eb680965622f46fc511
Rust
RedEyedMars/AutoClaw
/src/game/entities/combat.rs
UTF-8
5,528
2.890625
3
[]
no_license
use crate::game::battle::system::movement::MovementPath; use crate::game::entities::skills::Skill; use crate::game::entities::traits::TraitId; use crate::game::entities::{Change, Entity, Idable, State}; use crate::game::{Event, Events, GameParts}; use generational_arena::Index; #[derive(Debug, Clone, Copy)] pub enum CombatStance { FindingTarget, MovingCloser(Index, MovementPath), UsingSkill(Skill, Index), } impl CombatStance { pub fn pump<'a>(&self, entity: &Entity, parts: &GameParts, events: &mut Events) { if let Some(board) = parts.get_board() { match self { CombatStance::FindingTarget => { if let Some(target) = board.get_target(entity, parts) { events.push( 2, Event::ChangeEntity( entity.id(), Change::State(State::Fighting { stance: CombatStance::UsingSkill(target.1, target.0.id()), }), ), ); } else { if entity.has_trait(&TraitId::Priest) { if let Some(target) = board.get_closest_ally(entity.id(), parts) { events.push( 3, Event::ChangeEntity( entity.id(), Change::State(State::Fighting { stance: CombatStance::MovingCloser( target, board.get_path_to_target( entity.id(), target, parts, ), ), }), ), ); } } else { if let Some(target) = board.get_closest_enemy(entity.id(), parts) { events.push( 3, Event::ChangeEntity( entity.id(), Change::State(State::Fighting { stance: CombatStance::MovingCloser( target, board.get_path_to_target( entity.id(), target, parts, ), ), }), ), ); } } } } CombatStance::UsingSkill(skill, target) => { skill.act(parts, events, entity.id(), *target); events.push( 2, Event::ChangeEntity( entity.id(), Change::State(State::Fighting { stance: CombatStance::FindingTarget, }), ), ); } CombatStance::MovingCloser(target, path) => { if let Some(new_path) = board.move_entity(entity.id(), path, events) { events.push( 2, Event::ChangeEntity( entity.id(), Change::State(State::Fighting { stance: CombatStance::MovingCloser(*target, new_path), }), ), ); } else { if let Some(target) = board.get_target(entity, parts) { events.push( 2, Event::ChangeEntity( entity.id(), Change::State(State::Fighting { stance: CombatStance::UsingSkill(target.1, target.0.id()), }), ), ); } else { events.push( 2, Event::ChangeEntity( entity.id(), Change::State(State::Fighting { stance: CombatStance::FindingTarget, }), ), ); } } } } } } }
true
5d5ec2b359cb4beaa13d08839ba6057d8492bd46
Rust
mkeeter/advent-of-code
/2021/15/src/main.rs
UTF-8
2,164
3.0625
3
[]
no_license
use std::cmp::Reverse; use std::collections::BinaryHeap; use std::io::BufRead; #[derive(Ord, PartialOrd, Eq, PartialEq)] struct Task { score: Reverse<usize>, pos: (usize, usize), } struct Tile { weight: usize, score: Option<usize>, } fn search(map: &[Vec<u8>]) -> usize { let mut map: Vec<Vec<Tile>> = map .iter() .map(|row| { row.iter() .map(|weight| Tile { weight: *weight as usize, score: None, }) .collect() }) .collect(); let mut todo = BinaryHeap::new(); todo.push(Task { score: Reverse(0), pos: (0, 0), }); let xmax = map[0].len() as i64 - 1; let ymax = map.len() as i64 - 1; while let Some(task) = todo.pop() { let (x, y) = task.pos; let tile = &mut map[y][x]; if let Some(s) = tile.score { assert!(s <= task.score.0); continue; } tile.score = Some(task.score.0); for (dx, dy) in &[(-1, 0), (1, 0), (0, 1), (0, -1)] { let (x, y) = (x as i64 + dx, y as i64 + dy); if x < 0 || y < 0 || x > xmax || y > ymax { continue; } let (x, y) = (x as usize, y as usize); todo.push(Task { score: Reverse(task.score.0 + map[y][x].weight), pos: (x, y), }); } } map[ymax as usize][ymax as usize].score.unwrap() } fn main() { let minimap = std::io::stdin() .lock() .lines() .map(|line| line.unwrap().bytes().map(|c| c - b'0').collect()) .collect::<Vec<Vec<u8>>>(); println!("Part 1: {}", search(&minimap)); let xsize = minimap[0].len(); let ysize = minimap.len(); let mut megamap = vec![vec![0; xsize * 5]; xsize * 5]; for (y, row) in megamap.iter_mut().enumerate() { for (x, c) in row.iter_mut().enumerate() { let risk = minimap[y % ysize][x % xsize]; *c = ((risk + (x / xsize + y / ysize) as u8 - 1) % 9) + 1; } } println!("Part 2: {}", search(&megamap)); }
true
2767ab826e2d1bf764a4c81631511d7641d4c003
Rust
Deskbot/Advent-of-Code-2020
/src/day/day07.rs
UTF-8
5,480
3.203125
3
[]
no_license
use std::collections::HashMap; use std::fs; use substring::Substring; #[derive(std::fmt::Debug)] struct Rule<'a> (i32, &'a str); pub fn day07() { let file = fs::read_to_string("input/day07.txt").expect("input not found"); println!("Part 1: {}", part1(&file)); println!("Part 2: {}", part2(&file)); } fn part1(input: &str) -> i32 { let bag_to_rules = parse_input(input); let mut contains_golden = HashMap::new() as HashMap<&str, bool>; for &bag in bag_to_rules.keys() { let bag_deep_contains_golden = must_contain(bag, &bag_to_rules, &contains_golden); contains_golden.insert(bag, bag_deep_contains_golden); } return contains_golden .values() .filter(|&&b| b) .count() as i32; } fn must_contain(bag: &str, bag_to_rules: &HashMap<&str, Vec<Rule>>, memo: &HashMap<&str, bool>) -> bool { return bag_to_rules .get(bag) .unwrap() .iter() .any(|&Rule(_, rule)| { if rule == "shiny gold" { return true; } if let Some(&this_was_less_annoying_than_unwrap_or_else) = memo.get(bag) { return this_was_less_annoying_than_unwrap_or_else; } return must_contain(rule, bag_to_rules, memo); // this ain't memoised :(((((((((( // need to learn lifetime parameters }); } fn part2(input: &str) -> i32 { let bag_to_rules = parse_input(input); // let mut memo = HashMap::new() as HashMap<&str, i32>; return contains("shiny gold", &bag_to_rules, /*&mut memo*/); } fn contains(colour: &str, bag_to_rules: &HashMap<&str, Vec<Rule>>, /*memo: &mut HashMap<&str, i32>*/) -> i32 { // if let Some(&result) = memo.get(bag) { // return result; // } let rules = bag_to_rules .get(colour) .unwrap() .into_iter(); let poop = rules.map(|Rule(rule_count, rule_colour)| { return rule_count // this many bags directly inside + rule_count * contains(rule_colour, bag_to_rules, /*memo*/) // and each of those bags contains bags }); return poop.fold(0, |sum, next| sum + next); } fn parse_input(input: &str) -> HashMap<&str, Vec<Rule>>{ input .lines() .map(|line| { let mut split = line.split(" contain "); let bag = split.next().unwrap(); let rules = split.next().unwrap(); return (remove_last_word(bag), parse_rules(rules)); }) .collect() } fn parse_rules(rules: &str) -> Vec<Rule> { if rules == "no other bags." { return Vec::new(); } // remove the trailing full-stop let rules = rules.substring(0, rules.len() - 1); return rules .split(", ") .map(|rule| { let space = rule.find(" ").unwrap(); let number = rule.substring(0, space).parse::<i32>().unwrap(); let non_number_part = rule.substring(space + 1, rule.len()); return Rule(number, remove_last_word(non_number_part)); }) .collect(); } fn remove_last_word(string: &str) -> &str { let last_space = string.rfind(" ").unwrap(); return string.substring(0, last_space); } #[cfg(test)] mod tests { use super::*; const EXAMPLE_INPUT: &str = "light red bags contain 1 bright white bag, 2 muted yellow bags.\n\ dark orange bags contain 3 bright white bags, 4 muted yellow bags.\n\ bright white bags contain 1 shiny gold bag.\n\ muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.\n\ shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.\n\ dark olive bags contain 3 faded blue bags, 4 dotted black bags.\n\ vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.\n\ faded blue bags contain no other bags.\n\ dotted black bags contain no other bags."; const EXAMPLE_PART2_INPUT: &str = "shiny gold bags contain 2 dark red bags.\n\ dark red bags contain 2 dark orange bags.\n\ dark orange bags contain 2 dark yellow bags.\n\ dark yellow bags contain 2 dark green bags.\n\ dark green bags contain 2 dark blue bags.\n\ dark blue bags contain 2 dark violet bags.\n\ dark violet bags contain no other bags."; #[test] fn part1_example() { assert_eq!(part1(EXAMPLE_INPUT), 4); } #[test] fn part2_example_1() { assert_eq!(part2(EXAMPLE_INPUT), 32); } #[test] fn part2_example_2() { assert_eq!(part2(EXAMPLE_PART2_INPUT), 126); } #[test] fn test() { assert_eq!(part1("bright white bags contain 1 shiny gold bag.\n"), 1); } #[test] fn test2() { let bag_to_rules = parse_input(EXAMPLE_INPUT); assert_eq!(contains("faded blue", &bag_to_rules), 0); assert_eq!(contains("dotted black", &bag_to_rules), 0); assert_eq!(contains("dark olive", &bag_to_rules), 7); assert_eq!(contains("vibrant plum", &bag_to_rules), 11); assert_eq!(contains("shiny gold", &bag_to_rules), 32); } }
true
d122241b1a5f2da0c0458e989b8813720783add5
Rust
nampdn/prisma-engines
/query-engine/core/src/executor/interpreting_executor.rs
UTF-8
2,339
2.53125
3
[ "Apache-2.0" ]
permissive
use super::{pipeline::QueryPipeline, QueryExecutor}; use crate::{Operation, QueryGraphBuilder, QueryInterpreter, QuerySchemaRef, Response, Responses}; use async_trait::async_trait; use connector::{ConnectionLike, Connector}; /// Central query executor and main entry point into the query core. pub struct InterpretingExecutor<C> { connector: C, primary_connector: &'static str, force_transactions: bool, } // Todo: // - Partial execution semantics? impl<C> InterpretingExecutor<C> where C: Connector + Send + Sync, { pub fn new(connector: C, primary_connector: &'static str, force_transactions: bool) -> Self { InterpretingExecutor { connector, primary_connector, force_transactions, } } } #[async_trait] impl<C> QueryExecutor for InterpretingExecutor<C> where C: Connector + Send + Sync, { async fn execute(&self, operation: Operation, query_schema: QuerySchemaRef) -> crate::Result<Responses> { let conn = self.connector.get_connection().await?; // Parse, validate, and extract query graphs from query document. let (query, info) = QueryGraphBuilder::new(query_schema).build(operation)?; // Create pipelines for all separate queries let mut responses = Responses::with_capacity(1); let needs_transaction = self.force_transactions || query.needs_transaction(); let result = if needs_transaction { let tx = conn.start_transaction().await?; let interpreter = QueryInterpreter::new(ConnectionLike::Transaction(tx.as_ref())); let result = QueryPipeline::new(query, interpreter, info).execute().await; if result.is_ok() { tx.commit().await?; } else { tx.rollback().await?; } result? } else { let interpreter = QueryInterpreter::new(ConnectionLike::Connection(conn.as_ref())); QueryPipeline::new(query, interpreter, info).execute().await? }; match result { Response::Data(key, item) => responses.insert_data(key, item), Response::Error(error) => responses.insert_error(error), } Ok(responses) } fn primary_connector(&self) -> &'static str { self.primary_connector } }
true
04b6682d49dbf63b9576fb241f686404d1a04d3f
Rust
manuelleduc/awesome-software-language-engineering
/ci/src/lib.rs
UTF-8
4,816
2.953125
3
[ "CC0-1.0" ]
permissive
// `error_chain!` can recurse deeply #![recursion_limit = "1024"] #[macro_use] extern crate failure; #[macro_use] extern crate lazy_static; extern crate regex; use failure::{Error, err_msg}; use regex::Regex; use std::fmt; use std::cmp::Ordering; lazy_static! { static ref TOOL_REGEX: Regex = Regex::new(r"\*\s\[(?P<name>.*)\]\((?P<link>http[s]?://.*)\)\s(:copyright:\s)?\-\s(?P<desc>.*)").unwrap(); static ref SUBSECTION_HEADLINE_REGEX: Regex = Regex::new(r"[A-Za-z\s]*").unwrap(); } struct Tool { name: String, link: String, desc: String, } impl Tool { fn new<T: Into<String>>(name: T, link: T, desc: T) -> Self { Tool { name: name.into(), link: link.into(), desc: desc.into(), } } } impl PartialEq for Tool { fn eq(&self, other: &Tool) -> bool { self.name.to_lowercase() == other.name.to_lowercase() } } impl Eq for Tool {} impl PartialOrd for Tool { fn partial_cmp(&self, other: &Tool) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for Tool { fn cmp(&self, other: &Tool) -> Ordering { self.name.to_lowercase().cmp(&other.name.to_lowercase()) } } fn check_tool(tool: &str) -> Result<Tool, Error> { println!("Checking `{}`", tool); // NoneError can not implement Fail at this time. That's why we use ok_or // See https://github.com/rust-lang-nursery/failure/issues/61 let captures = TOOL_REGEX.captures(tool).ok_or(err_msg(format!("Tool does not match regex: {}", tool)))?; let name = captures["name"].to_string(); let link = captures["link"].to_string(); let desc = captures["desc"].to_string(); if name.len() > 50 { bail!("Name of tool is suspiciously long: `{}`", name); } // A somewhat arbitrarily chosen description length. // Note that this includes any markdown formatting // like links. Therefore we are quite generous for now. if desc.len() > 200 { bail!("Desription of `{}` is too long: {}", name, desc); } Ok(Tool::new(name, link, desc)) } fn check_section(section: String) -> Result<(), Error> { // Ignore license section if section.starts_with("License") { return Ok(()); } // Skip section headline let lines: Vec<_> = section.split('\n').skip(1).collect(); if lines.is_empty() { bail!("Empty section: {}", section) }; let mut tools = vec![]; for line in lines { if line.is_empty() { continue; } // Exception for subsection headlines if !line.starts_with("*") && line.ends_with(":") && SUBSECTION_HEADLINE_REGEX.is_match(line) { continue; } tools.push(check_tool(line)?); } // Tools need to be alphabetically ordered check_ordering(tools) } fn check_ordering(tools: Vec<Tool>) -> Result<(), Error> { match tools.windows(2).find(|t| t[0] > t[1]) { Some(tools) => bail!("`{}` does not conform to alphabetical ordering", tools[0].name), None => Ok(()), } } fn check(text: String) -> Result<(), Error> { let sections = text.split("\n# "); // Skip first two sections, // as they contain the prelude and the table of contents. for section in sections.skip(2) { let subsections = section.split("## "); for subsection in subsections.skip(1) { check_section(subsection.into())?; } } Ok(()) } mod tests { use super::*; use std::fs::File; use std::io::Read; #[test] fn test_complete_file() { let mut file = File::open("../README.md").expect("Can't open testfile"); let mut contents = String::new(); file.read_to_string(&mut contents).expect("Can't read testfile contents"); let result = check(contents); if result.is_err() { println!("Error: {:?}", result.err()); assert!(false); } else { assert!(true); } } #[test] fn test_correct_ordering() { assert!(check_ordering(vec![]).is_ok()); assert!(check_ordering(vec![Tool::new("a", "url", "desc")]).is_ok()); assert!( check_ordering(vec![ Tool::new("0", "", ""), Tool::new("1", "", ""), Tool::new("a", "", ""), Tool::new("Axx", "", ""), Tool::new("B", "", ""), Tool::new("b", "", ""), Tool::new("c", "", ""), ]).is_ok() ); } #[test] fn test_incorrect_ordering() { assert!( check_ordering(vec![ Tool::new("b", "", ""), Tool::new("a", "", ""), Tool::new("c", "", ""), ]).is_err() ); } }
true
7e359a5fc15b6bc0d512244d9217e24a8923a440
Rust
abhijat/invalidator
/benches/benchmark.rs
UTF-8
953
2.828125
3
[ "MIT" ]
permissive
#[macro_use] extern crate criterion; use std::collections::HashSet; use criterion::Criterion; use rand::distributions::Alphanumeric; use rand::Rng; use rand::thread_rng; use bloom_filter::BloomFilter; fn data_set_of_size(size: usize, word_size: usize) -> HashSet<String> { let mut data = HashSet::with_capacity(size); for _ in 0..size { let s: String = thread_rng().sample_iter(&Alphanumeric).take(word_size).collect(); data.insert(s); } data } fn false_negative_benchmark(c: &mut Criterion) { let data = data_set_of_size(1 * 100 * 100, 16); let mut filter = BloomFilter::new(); data.iter().for_each(|w| filter.put(w)); c.bench_function( "false-negatives 100 * 100 problem size, 16 char words", move |b| b.iter(|| { data.iter().for_each(|w| if !filter.get(w) { panic!(); }); })); } criterion_group!(benches, false_negative_benchmark); criterion_main!(benches);
true
91b02a5a09ad5a9979113b7dfd51da71b27a4cdc
Rust
tobisako/rust-memo
/rust_tutorial/s414/src/main.rs
UTF-8
5,053
4.3125
4
[]
no_license
struct Point { x: i32, y: i32, } // use std::result::Result; fn main() { // パターン // パターンには一つ落とし穴があります。 // 新しい束縛を導入する他の構文と同様、パターンはシャドーイングをします。例えば: let x = 'x'; let c = 'c'; match c { x => println!("x: {} c: {}", x, c), // 元のxがシャドーイングされて、別のxとして動作している。 } println!("x: {}", x); // x => は値をパターンにマッチさせ、マッチの腕内で有効な x という名前の束縛を導入します。 // 既に x という束縛が存在していたので、新たに導入した x は、その古い x をシャドーイングします。 // 複式パターン let x2 = 1; match x2 { 1 | 2 => println!("one or two"), 3 => println!("three"), _ => println!("anything"), } // 分配束縛 let origin = Point { x: 0, y: 0 }; match origin { Point { x, y } => println!("({},{})", x, y), } // 値に別の名前を付けたいときは、 : を使うことができます。 let origin2 = Point { x: 0, y: 0 }; match origin2 { Point { x: x1, y: y1 } => println!("({},{})", x1, y1), } // 値の一部にだけ興味がある場合は、値のすべてに名前を付ける必要はありません。 let origin = Point { x: 0, y: 0 }; match origin { Point { x, .. } => println!("x is {}", x), } // 最初のメンバだけでなく、どのメンバに対してもこの種のマッチを行うことができます。 let origin = Point { x: 0, y: 0 }; match origin { Point { y, .. } => println!("y is {}", y), } // 束縛の無視 let some_value: Result<i32, &'static str> = Err("There was an error"); match some_value { Ok(value) => println!("got a value: {}", value), Err(_) => println!("an error occurred"), } // ここでは、タプルの最初と最後の要素に x と z を束縛します。 fn coordinate() -> (i32, i32, i32) { // generate and return some sort of triple tuple // 3要素のタプルを生成して返す (1, 2, 3) } let (x, _, z) = coordinate(); // 同様に .. でパターン内の複数の値を無視することができます。 enum OptionalTuple { Value(i32, i32, i32), Missing, } let x = OptionalTuple::Value(5, -2, 3); match x { OptionalTuple::Value(..) => println!("Got a tuple!"), OptionalTuple::Missing => println!("No such luck."), } // ref と ref mut // 参照 を取得したいときは ref キーワードを使いましょう。 let x3 = 5; match x3 { ref r => println!("Got a reference to {}", r), } // ミュータブルな参照が必要な場合は、同様に ref mut を使います。 let mut x = 5; match x { ref mut mr => { *mr += 1; println!("Got a mutable reference to {}", mr); }, } println!("x = {}", x); // 値が書き換わっている。 // 範囲 let x = 1; match x { 1 ... 5 => println!("one through five"), _ => println!("anything"), } // 範囲は多くの場合、整数か char 型で使われます: let x = '💅'; match x { 'a' ... 'j' => println!("early letter"), 'k' ... 'z' => println!("late letter"), _ => println!("something else"), } // 束縛 let x = 1; match x { e @ 1 ... 5 => println!("got a range element {}", e), _ => println!("anything"), } // 内側の name の値への参照に a を束縛します。 #[derive(Debug)] struct Person { name: Option<String>, } let name = "Steve".to_string(); let mut x: Option<Person> = Some(Person { name: Some(name) }); match x { Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a), _ => {} } // @ を | と組み合わせて使う場合は、それぞれのパターンで同じ名前が束縛されるようにする必要があります: let x = 5; match x { e @ 1 ... 5 | e @ 8 ... 10 => println!("got a range element {}", e), _ => println!("anything"), } // ガード // if を使うことでマッチガードを導入することができます: enum OptionalInt { Value(i32), Missing, } let x = OptionalInt::Value(5); match x { OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"), OptionalInt::Value(..) => println!("Got an int!"), OptionalInt::Missing => println!("No such luck."), } // 複式パターンで if を使うと、 if は | の両側に適用されます: let x = 4; let y = false; match x { 4 | 5 if y => println!("yes"), _ => println!("no"), } // イメージ: (4 | 5) if y => ... // 混ぜてマッチ // やりたいことに応じて、それらを混ぜてマッチさせることもできます: // match x { // Foo { x: Some(ref name), y: None } => { println!("foo"); }, // } // パターンはとても強力です。上手に使いましょう。 }
true
8926b758fe04817f945d6b6738733e09b81a05ed
Rust
elipmoc/Ruscall
/src/compile/semantic_analysis/variable_table.rs
UTF-8
1,738
2.921875
3
[ "MIT" ]
permissive
use std::collections::HashMap; #[derive(Clone)] pub struct VariableTable { local_var_names: Vec<Vec<String>>, global_var_names: HashMap<String, ()>, nest_level: usize, } use super::super::ir::ast::VariableAST; use super::type_inference::type_env::TypeEnv; use super::mir::ExprMir; //変数の管理 impl VariableTable { pub fn new(global_var_names: HashMap<String, ()>) -> VariableTable { VariableTable { global_var_names, local_var_names: vec![], nest_level: 0 } } //de bruijn indexを割り当てたVariableIrの生成 //またはGlobalVariableIrの生成 pub fn get_variable_ir(&self, var: VariableAST, ty_env: &mut TypeEnv) -> Option<ExprMir> { let a = self.local_var_names[self.nest_level - 1] .iter().rev().enumerate() .find(|(_, name)| *name == &var.id) .map(|(id, _)| id); match a { Some(id) => Some(ExprMir::create_variable_mir(id, var.pos, ty_env.fresh_type_id())), _ => { if self.global_var_names.contains_key(&var.id) { Some(ExprMir::create_global_variable_mir(var.id, var.pos, ty_env.fresh_type_id())) } else { None } } } } pub fn in_nest<T>(&mut self, iter: T) where T: IntoIterator<Item=String> { if self.local_var_names.len() <= self.nest_level { self.local_var_names.push(iter.into_iter().collect()); } else { self.local_var_names[self.nest_level].clear(); self.local_var_names[self.nest_level].extend(iter); } self.nest_level += 1; } pub fn out_nest(&mut self) { self.nest_level -= 1; } }
true
194d5312513ad7060b2c4dc623f33fbdf1ae4875
Rust
pwwolff/RussianRust
/src/settings_factory.rs
UTF-8
474
2.625
3
[]
no_license
extern crate glob; extern crate config; use std::collections::HashMap; use config::*; use glob::glob; pub fn get_settings() -> HashMap<String, String>{ let mut settings = Config::default(); settings .merge(glob("config/*") .unwrap() .map(|path| File::from(path.unwrap())) .collect::<Vec<_>>()) .unwrap(); // Print out our settings (as a HashMap) settings.try_into::<HashMap<String, String>>().unwrap() }
true
dad6bfdbdf27b7f5223322bdee6c1fbc32195b04
Rust
payload/asciii-rs
/src/actions/mod.rs
UTF-8
11,758
2.53125
3
[]
no_license
//! General actions #![allow(unused_imports)] #![allow(dead_code)] use chrono::*; use std::{env,fs}; use std::time; use std::fmt::Write; use std::path::{Path,PathBuf}; use util; use super::BillType; use storage::{Storage,StorageDir,Storable,StorageResult}; use project::Project; #[cfg(feature="document_export")] use fill_docs::fill_template; pub mod error; use self::error::*; /// Sets up an instance of `Storage`. pub fn setup_luigi() -> Result<Storage<Project>> { trace!("setup_luigi()"); let working = try!(::CONFIG.get_str("dirs/working").ok_or("Faulty config: dirs/working does not contain a value")); let archive = try!(::CONFIG.get_str("dirs/archive").ok_or("Faulty config: dirs/archive does not contain a value")); let templates = try!(::CONFIG.get_str("dirs/templates").ok_or("Faulty config: dirs/templates does not contain a value")); let storage = try!(Storage::new(util::get_storage_path(), working, archive, templates)); Ok(storage) } /// Sets up an instance of `Storage`, with git turned on. pub fn setup_luigi_with_git() -> Result<Storage<Project>> { trace!("setup_luigi()"); let working = try!(::CONFIG.get_str("dirs/working").ok_or("Faulty config: dirs/working does not contain a value")); let archive = try!(::CONFIG.get_str("dirs/archive").ok_or("Faulty config: dirs/archive does not contain a value")); let templates = try!(::CONFIG.get_str("dirs/templates").ok_or("Faulty config: dirs/templates does not contain a value")); let storage = try!(Storage::new_with_git(util::get_storage_path(), working, archive, templates)); Ok(storage) } pub fn simple_with_projects<F>(dir:StorageDir, search_terms:&[&str], f:F) where F:Fn(&Project) { match with_projects(dir, search_terms, |p| {f(p);Ok(())}){ Ok(_) => {}, Err(e) => error!("{}",e) } } /// Helper method that passes projects matching the `search_terms` to the passt closure `f` pub fn with_projects<F>(dir:StorageDir, search_terms:&[&str], f:F) -> Result<()> where F:Fn(&Project)->Result<()> { trace!("with_projects({:?})", search_terms); let luigi = try!(setup_luigi()); let projects = try!(luigi.search_projects_any(dir, search_terms)); if projects.is_empty() { return Err(format!("Nothing found for {:?}", search_terms).into()) } for project in &projects{ try!(f(project)); } Ok(()) } pub fn csv(year:i32) -> Result<String> { let luigi = try!(setup_luigi()); let mut projects = try!(luigi.open_projects(StorageDir::Year(year))); projects.sort_by(|pa,pb| pa.index().unwrap_or_else(||"zzzz".to_owned()).cmp( &pb.index().unwrap_or("zzzz".to_owned()))); projects_to_csv(&projects) } /// Produces a csv string from a list of `Project`s /// TODO this still contains german terms pub fn projects_to_csv(projects:&[Project]) -> Result<String>{ let mut string = String::new(); let splitter = ";"; try!(writeln!(&mut string, "{}", [ "Rnum", "Bezeichnung", "Datum", "Rechnungsdatum", "Betreuer", "Verantwortlich", "Bezahlt am", "Betrag", "Canceled"].join(splitter))); for project in projects{ try!(writeln!(&mut string, "{}", [ project.get("InvoiceNumber").unwrap_or_else(|| String::from(r#""""#)), project.get("Name").unwrap_or_else(|| String::from(r#""""#)), project.get("event/dates/0/begin").unwrap_or_else(|| String::from(r#""""#)), project.get("invoice/date").unwrap_or_else(|| String::from(r#""""#)), project.get("Caterers").unwrap_or_else(|| String::from(r#""""#)), project.get("Responsible").unwrap_or_else(|| String::from(r#""""#)), project.get("invoice/payed_date").unwrap_or_else(|| String::from(r#""""#)), project.get("Final").unwrap_or_else(|| String::from(r#""""#)), project.canceled_string().to_owned() ].join(splitter))); } Ok(string) } /// Creates the latex files within each projects directory, either for Invoice or Offer. #[cfg(feature="document_export")] pub fn project_to_doc(project: &Project, template_name:&str, bill_type:&Option<BillType>, dry_run:bool, force:bool) -> Result<()> { let template_ext = ::CONFIG.get_str("extensions/output_template").expect("Faulty default config"); let output_ext = ::CONFIG.get_str("extensions/output_file").expect("Faulty default config"); let convert_ext = ::CONFIG.get_str("convert/output_extension").expect("Faulty default config"); let trash_exts = ::CONFIG.get("convert/trash_extensions") .expect("Faulty default config") .as_vec().expect("Faulty default config") .into_iter() .map(|v|v.as_str()).collect::<Vec<_>>(); let mut template_path = PathBuf::new(); template_path.push(util::get_storage_path()); template_path.push(::CONFIG.get_str("dirs/templates").expect("Faulty config: dirs/templates does not contain a value")); template_path.push(template_name); template_path.set_extension(template_ext); debug!("template file={:?} exists={}", template_path, template_path.exists()); if !template_path.exists() { return Err(format!("Template not found at {}", template_path.display()).into()) } let convert_tool = ::CONFIG.get_str("convert/tool"); let output_folder = ::CONFIG.get_str("output_path").and_then(util::get_valid_path).expect("Faulty config \"output_path\""); let ready_for_offer = project.is_ready_for_offer(); let ready_for_invoice = project.is_ready_for_invoice(); let project_file = project.file(); // tiny little helper let to_local_file = |file:&Path, ext| { let mut _tmpfile = file.to_owned(); _tmpfile.set_extension(ext); Path::new(_tmpfile.file_name().unwrap().into()).to_owned() }; use BillType::*; let (dyn_bill_type, outfile_tex): (Option<BillType>, Option<PathBuf>) = match (bill_type, ready_for_offer, ready_for_invoice) { (&Some(Offer), Ok(_), _ ) | (&None, Ok(_), Err(_)) => (Some(Offer), Some(project.dir().join(project.offer_file_name(output_ext).expect("this should have been cought by ready_for_offer()")))), (&Some(Invoice), _, Ok(_)) | (&None, _, Ok(_)) => (Some(Invoice), Some(project.dir().join(project.invoice_file_name(output_ext).expect("this should have been cought by ready_for_invoice()")))), (&Some(Offer), Err(e), _ ) => {error!("cannot create an offer, check out:{:#?}",e);(None,None)}, (&Some(Invoice), _, Err(e)) => {error!("cannot create an invoice, check out:{:#?}",e);(None,None)}, (_, Err(e), Err(_)) => {error!("Neither an Offer nor an Invoice can be created from this project\n please check out {:#?}", e);(None,None)} }; //debug!("{:?} -> {:?}",(bill_type, project.is_ready_for_offer(), project.is_ready_for_invoice()), (dyn_bill_type, outfile_tex)); if let (Some(outfile), Some(dyn_bill)) = (outfile_tex, dyn_bill_type) { let filled = try!(fill_template(project, &dyn_bill, &template_path)); let pdffile = to_local_file(&outfile, convert_ext); let target = output_folder.join(&pdffile); // ok, so apparently we can create a tex file, so lets do it if !force && target.exists() && try!(file_age(&target)) < try!(file_age(&project_file)){ // no wait, nothing has changed, so lets save ourselves the work info!("nothing to be done, {} is younger than {}\n use -f if you don't agree", target.display(), project_file.display()); } else { // \o/ we created a tex file if dry_run{ warn!("Dry run! This does not produce any output:\n * {}\n * {}", outfile.display(), pdffile.display()); } else { let outfileb = try!(project.write_to_file(&filled,&dyn_bill,output_ext)); debug!("{} vs\n {}", outfile.display(), outfileb.display()); util::pass_to_command(&convert_tool, &[&outfileb]); } // clean up expected trash files for trash_ext in trash_exts.iter().filter_map(|x|*x){ let trash_file = to_local_file(&outfile, trash_ext); if trash_file.exists() { try!(fs::remove_file(&trash_file)); debug!("just deleted: {}", trash_file.display()) } else { debug!("I expected there to be a {}, but there wasn't any ?", trash_file.display()) } } if pdffile.exists(){ debug!("now there is be a {:?} -> {:?}", pdffile, target); try!(fs::rename(&pdffile, &target)); } } } Ok(()) } /// Creates the latex files within each projects directory, either for Invoice or Offer. #[cfg(feature="document_export")] pub fn projects_to_doc(dir:StorageDir, search_term:&str, template_name:&str, bill_type:&Option<BillType>, dry_run:bool, force:bool) -> Result<()> { with_projects(dir, &[search_term], |p| project_to_doc(p, template_name, bill_type, dry_run, force) ) } fn file_age(path:&Path) -> Result<time::Duration> { let metadata = try!(fs::metadata(path)); let accessed = try!(metadata.accessed()); Ok(try!(accessed.elapsed())) } /// Testing only, tries to run complete spec on all projects. /// TODO make this not panic :D /// TODO move this to `spec::all_the_things` pub fn spec() -> Result<()> { use project::spec::*; let luigi = try!(setup_luigi()); //let projects = super::execute(||luigi.open_projects(StorageDir::All)); let projects = try!(luigi.open_projects(StorageDir::Working)); for project in projects{ info!("{}", project.dir().display()); let yaml = project.yaml(); client::validate(&yaml).map_err(|errors|for error in errors{ println!(" error: {}", error); }).unwrap(); client::full_name(&yaml); client::first_name(&yaml); client::title(&yaml); client::email(&yaml); hours::caterers_string(&yaml); invoice::number_long_str(&yaml); invoice::number_str(&yaml); offer::number(&yaml); project.age().map(|a|format!("{} days", a)).unwrap(); project.date().map(|d|d.year().to_string()).unwrap(); project.sum_sold().map(|c|util::currency_to_string(&c)).unwrap(); project::manager(&yaml).map(|s|s.to_owned()).unwrap(); project::name(&yaml).map(|s|s.to_owned()).unwrap(); } Ok(()) } pub fn delete_project_confirmation(dir: StorageDir, search_terms:&[&str]) -> Result<()> { let luigi = try!(setup_luigi()); for project in try!(luigi.search_projects_any(dir, search_terms)) { try!(project.delete_project_dir_if( || util::really(&format!("you want me to delete {:?} [y/N]", project.dir())) && util::really("really? [y/N]") )) } Ok(()) } pub fn archive_projects(search_terms:&[&str], manual_year:Option<i32>, force:bool) -> Result<Vec<PathBuf>>{ trace!("archive_projects matching ({:?},{:?},{:?})", search_terms, manual_year,force); let luigi = try!(setup_luigi_with_git()); Ok(try!( luigi.archive_projects_if(search_terms, manual_year, || force) )) } /// Command UNARCHIVE <YEAR> <NAME> /// TODO: return a list of files that have to be updated in git pub fn unarchive_projects(year:i32, search_terms:&[&str]) -> Result<Vec<PathBuf>> { let luigi = try!(setup_luigi_with_git()); Ok(try!( luigi.unarchive_projects(year, search_terms) )) }
true
26801c3acd5afe03a2f81242e2d991bf6fc3b719
Rust
Strum355/lsif-lang-server
/src/reader/interner.rs
UTF-8
5,093
3.734375
4
[ "MIT" ]
permissive
use std::collections::HashMap; use std::marker::Sync; use std::sync::{Arc, Mutex}; /// Interner converts strings into unique identifers. Submitting the same byte value to /// the interner will result in the same identifier being produced. Each unique input is /// guaranteed to have a unique output (no two inputs share the same identifier). The /// identifier space of two distinct interner instances may overlap. /// /// Assumption: The output of LSIF indexers will not generally mix types of identifiers. /// If integers are used, they are used for all ids. If strings are used, they are used /// for all ids. #[derive(Clone)] pub struct Interner { map: Arc<Mutex<HashMap<String, u64>>>, } unsafe impl Sync for Interner {} impl Interner { pub fn new() -> Interner { Interner { map: Arc::new(Mutex::new(HashMap::new())), } } /// Intern returns the unique identifier for the given byte value. The byte value should /// be a raw LSIF input identifier, which should be a JSON-encoded number or quoted string. /// This method is safe to call from multiple goroutines. pub fn intern(&self, raw: &[u8]) -> Result<u64, std::num::ParseIntError> { if raw.is_empty() { return Ok(0); } if raw[0] != b'"' { unsafe { return String::from_utf8_unchecked(raw.to_vec()).parse::<u64>() } } let s = unsafe { String::from_utf8_unchecked(raw[1..raw.len() - 1].to_vec()) }; match s.parse::<u64>() { Ok(num) => return Ok(num), Err(_) => {} } let mut map = self.map.lock().unwrap(); if map.contains_key(&s) { return Ok(*map.get(&s).unwrap()); } let id: u64 = (map.len() + 1) as u64; map.insert(s, id); Ok(id) } } #[cfg(test)] mod tests { use super::*; use anyhow::{format_err, Result}; use std::collections::HashSet; fn compare_from_vec(input: &[Vec<u8>]) -> Result<HashSet<u64>> { let mut results = HashSet::with_capacity(input.len()); let interner = Interner::new(); for num in input { let x = interner.intern(num).unwrap(); results.insert(x); } for num in input { let x = interner.intern(num).unwrap(); results .get(&x) .ok_or(format_err!("result not found in previous set"))?; } Ok(results) } fn string_vec_to_bytes(values: Vec<&str>) -> Vec<Vec<u8>> { values.iter().map(|s| s.as_bytes().to_vec()).collect() } #[test] fn empty_data_doesnt_throw() { let interner = Interner::new(); assert_eq!(interner.intern(&Vec::new()).unwrap(), 0); } #[test] fn numbers_test() { let values = string_vec_to_bytes(vec!["1", "2", "3", "4", "100", "500"]); let results = compare_from_vec(&values).unwrap(); assert_eq!(results.len(), values.len()); } #[test] fn numbers_in_strings_test() { let values = string_vec_to_bytes(vec![ r#""1""#, r#""2""#, r#""3""#, r#""4""#, r#""100""#, r#""500""#, ]); let results = compare_from_vec(&values).unwrap(); assert_eq!(results.len(), values.len()); } #[test] fn normal_strings_test() { let values = string_vec_to_bytes(vec![ r#""assert_eq!(results.len(), values.len());""#, r#""sample text""#, r#""why must this be utf16. Curse you javascript""#, r#""I'd just like to interject for a moment. What you're referring to as Linux, is in fact, GNU/Linux, or as I've recently taken to calling it, GNU plus Linux. Linux is not an operating system unto itself, but rather another free component of a fully functioning GNU system made useful by the GNU corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX.""#, ]); let results = compare_from_vec(&values).unwrap(); assert_eq!(results.len(), values.len()); } #[test] fn duplicate_string() { let values = string_vec_to_bytes(vec![ r#""assert_eq!(results.len(), values.len());""#, r#""sample text""#, r#""why must this be utf16. Curse you javascript""#, r#""why must this be utf16. Curse you javascript""#, r#""why must this be utf16. Curse you javascript""#, r#""I'd just like to interject for a moment. What you're referring to as Linux, is in fact, GNU/Linux, or as I've recently taken to calling it, GNU plus Linux. Linux is not an operating system unto itself, but rather another free component of a fully functioning GNU system made useful by the GNU corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX.""#, ]); let results = compare_from_vec(&values).unwrap(); assert_eq!(results.len(), values.len() - 2); } }
true
d04135f099f39bfa1d16d4b9fd189ce9e97ad955
Rust
JesterOrNot/Rust-Playground
/functimer.rs
UTF-8
299
2.859375
3
[]
no_license
fn main() { timeFunction(&printer); } fn timeFunction(func: &dyn Fn()) { let time1 = std::time::Instant::now(); func(); let time2 = std::time::Instant::now().duration_since(time1); println!("{:?}", time2); } fn printer() { for i in 0..100 { println!("{}", i); } }
true
fdbfd5baeee2106b2b6fc3e9f75a672229b84644
Rust
IGBC/Cursive
/src/backend/mod.rs
UTF-8
1,176
2.71875
3
[ "MIT" ]
permissive
use event; use theme; #[cfg(feature = "termion")] mod termion; #[cfg(feature = "bear-lib-terminal")] mod blt; #[cfg(any(feature = "ncurses", feature = "pancurses"))] mod curses; #[cfg(feature = "bear-lib-terminal")] pub use self::blt::*; #[cfg(any(feature = "ncurses", feature = "pancurses"))] pub use self::curses::*; #[cfg(feature = "termion")] pub use self::termion::*; pub trait Backend { fn init() -> Box<Self> where Self: Sized; // TODO: take `self` by value? // Or implement Drop? fn finish(&mut self); fn refresh(&mut self); fn has_colors(&self) -> bool; fn screen_size(&self) -> (usize, usize); /// Main input method fn poll_event(&mut self) -> event::Event; /// Main method used for printing fn print_at(&self, (usize, usize), &str); fn clear(&self, color: theme::Color); fn set_refresh_rate(&mut self, fps: u32); // This sets the Colours and returns the previous colours // to allow you to set them back when you're done. fn set_color(&self, colors: theme::ColorPair) -> theme::ColorPair; fn set_effect(&self, effect: theme::Effect); fn unset_effect(&self, effect: theme::Effect); }
true
c7fc2c95c9f9f77f9516ad734f36661fd188d607
Rust
Agile-Llama/Ackermann
/ackermann.rs
UTF-8
1,727
3.453125
3
[]
no_license
use std::collections::HashMap; use std::cmp::max; // Naive approach fn ack(m: isize, n: isize) -> isize { if m == 0 { n + 1 } else if n == 0 { ack(m - 1, 1) } else { ack(m - 1, ack(m, n - 1)) } } // More optimzed approach using a cache fn ack_with_cache(m: u64, n: u64) -> u64 { let mut cache: HashMap<(u64, u64), u64> = HashMap::new(); _ack_with_cache(&mut cache, m, n) } fn _ack_with_cache(cache: &mut HashMap<(u64, u64), u64>, m: u64, n: u64) -> u64 { match (m, n) { (0, n) => n + 1, (1, n) => n + 2, (m, 0) => _ack_with_cache(cache, m - 1, 1), (m, 1) => { let n = _ack_with_cache(cache, m - 1, 1); _ack_with_cache(cache, m - 1, n) } (m, n) => { if cache.contains_key(&(m, n)) { *cache.get(&(m, n)).unwrap() } else { let s = _ack_with_cache(cache, m, n - 2); let t = _ack_with_cache(cache, m, n - 1); let res = (s..(t + 1)).fold(0, |acc, x| _ack_comparator(cache, m, acc, x)); cache.insert((m, n), res); res } } } } fn _ack_comparator(cache: &mut HashMap<(u64, u64), u64>, m: u64, acc: u64, x: u64) -> u64 { let c = _ack_with_cache(cache, m - 1, x); max(acc, c) } fn main() { use std::time::Instant; //let before_naive = Instant::now(); //let a = ack(4, 1); //println!("Naive Elapsed time: {:.2?}", before_naive.elapsed()); //println!("Answer: {}", a); let before = Instant::now(); let b = ack_with_cache(4, 2); println!("Optimzed Elapsed time: {:.2?}", before.elapsed()); println!("Answer: {}", b); }
true
8f476860cad08c7542d752279426b2b2e2708f58
Rust
mfarzamalam/Rust
/Rust_challenge/divisible/src/main.rs
UTF-8
587
3.171875
3
[]
no_license
use read_input::prelude::*; fn main() { let number = input::<u32>() .msg("Enter numerator : ") .err("Please input positive integer") .get(); let divisible = input::<u32>() .msg("Enter denominator : ") .err("Please input positive integer") .get(); if number % divisible == 0 { println!("Number {} is completely divisible by {} ! ",number,divisible); } else { println!("Number {} is not completely divisible by {} ! ",number,divisible); } }
true
a5320d31e9d5b7833e7236c58c84865f0c51b007
Rust
zhaoyao/rust-lab
/dns-server/src/packet/record_type.rs
UTF-8
1,199
2.890625
3
[]
no_license
use super::error::*; #[derive(Debug)] pub enum RecordType { A, NS, MD, MF, CNAME, SOA, MB, MG, MR, NULL, WKS, PTR, HINFO, MINFO, MX, TXT, AXFR, MAILB, MAILA, Any } impl RecordType { pub fn from_u16(i: u16) -> Result<RecordType> { match i { 1 => Ok(RecordType::A), 2 => Ok(RecordType::NS), 3 => Ok(RecordType::MD), 4 => Ok(RecordType::MF), 5 => Ok(RecordType::CNAME), 6 => Ok(RecordType::SOA), 7 => Ok(RecordType::MB), 8 => Ok(RecordType::MG), 9 => Ok(RecordType::MR), 10 => Ok(RecordType::NULL), 11 => Ok(RecordType::WKS), 12 => Ok(RecordType::PTR), 13 => Ok(RecordType::HINFO), 14 => Ok(RecordType::MINFO), 15 => Ok(RecordType::MX), 16 => Ok(RecordType::TXT), 252 => Ok(RecordType::AXFR), 253 => Ok(RecordType::MAILA), 255 => Ok(RecordType::Any), _ => Err(ErrorKind::InvalidRecordType(i).into()) } } }
true
0feafd9f6d9c3cad0a2254ecfa847e5ee4146f30
Rust
angelini/entity-query
/src/csv_parser.rs
UTF-8
5,337
2.6875
3
[]
no_license
use csv; use scoped_threadpool::Pool; use std::collections::HashMap; use ast::AstNode; use cli::Join; use data::{Datum, Db, Ref, Error}; use filter::Filter; #[derive(Debug)] pub struct CsvParser<'a> { filename: &'a str, entity: &'a str, time: &'a str, joins: &'a [Join], } impl<'a> CsvParser<'a> { pub fn new(filename: &'a str, entity: &'a str, time: &'a str, joins: &'a [Join]) -> CsvParser<'a> { CsvParser { filename: filename, entity: entity, time: time, joins: joins, } } pub fn parse(self, db: &Db, pool: &mut Pool) -> Result<(Vec<Datum>, Vec<Ref>, usize), Error> { let mut rdr = try!(csv::Reader::from_file(self.filename)); let headers = rdr.headers().expect("headers required to convert CSV"); let time_index = match headers.iter() .enumerate() .find(|&(_, h)| h == self.time) { Some((idx, _)) => idx, None => return Err(Error::MissingTimeHeader(self.time.to_owned())), }; let mut eid = db.offset; let datums_res = rdr.records() .map(|row_res| { let row = try!(row_res); eid += 1; let datums = try!(Self::parse_row(row, &headers, time_index, eid, self.entity)); Ok(datums) }) .collect::<Result<Vec<Vec<Datum>>, Error>>(); let datums = match datums_res { Ok(d) => d.into_iter().flat_map(|v| v).collect::<Vec<Datum>>(), Err(e) => return Err(e), }; let refs = self.find_refs(&datums, &db, pool); Ok((datums, refs, eid)) } fn find_refs(&self, datums: &[Datum], db: &Db, pool: &mut Pool) -> Vec<Ref> { self.joins .iter() .flat_map(|join| { let (column, query) = (&join.0, &join.1); let filter = Filter::new(&db, pool); self.find_refs_for_join(datums, column, query, filter) }) .collect::<Vec<Ref>>() } fn find_refs_for_join(&self, datums: &[Datum], column: &str, query: &str, filter: Filter) -> Vec<Ref> { let attribute = format!("{}/{}", self.entity, robotize(&column)); let ast = AstNode::parse(&query).unwrap(); let new_datums = datums.iter() .filter(|d| d.a == attribute) .cloned() .collect::<Vec<Datum>>(); let old_datums = filter.execute(&ast).datums; let index = index_by_value(old_datums); new_datums.iter() .flat_map(|new| Self::generate_refs(new, &index)) .filter(|o| o.is_some()) .map(|o| o.unwrap()) .collect() } fn generate_refs(new: &Datum, index: &HashMap<&str, Vec<&Datum>>) -> Vec<Option<Ref>> { let new_entity = new.a.split('/').next().unwrap(); match index.get(new.v.as_str()) { Some(old_matches) => { old_matches.iter() .map(|old| { let old_entity = old.a.split('/').next().unwrap(); Some(Ref::new(new.e, format!("{}/{}", new_entity, old_entity), old.e, new.t)) }) .collect() } None => vec![None], } } fn parse_row(row: Vec<String>, headers: &[String], time_index: usize, eid: usize, entity: &str) -> Result<Vec<Datum>, Error> { let time = match row[time_index].parse::<usize>() { Ok(t) => t, Err(_) => return Err(Error::TimeColumnTypeError(row[time_index].to_owned())), }; let datums = headers.iter() .enumerate() .filter(|&(i, _)| i != time_index) .map(|(_, h)| h) .zip(row) .map(|(header, val)| { Datum::new(eid, format!("{}/{}", entity, robotize(header)), val, time) }) .collect(); Ok(datums) } } fn robotize(string: &str) -> String { string.replace(" ", "_") .to_lowercase() } fn index_by_value(datums: Vec<&Datum>) -> HashMap<&str, Vec<&Datum>> { let mut index = HashMap::new(); for datum in datums { if let Some(mut foo) = index.insert(datum.v.as_str(), vec![datum]) { foo.push(datum) } } index }
true
032882d7e5d528a62e79500f5598b67488a2df6f
Rust
luqmana/cgmath-rs
/src/cgmath/vector.rs
UTF-8
11,652
2.59375
3
[ "Apache-2.0" ]
permissive
// Copyright 2013 The CGMath Developers. For a full listing of the authors, // refer to the AUTHORS file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fmt; use std::num::{Zero, zero, One, one}; use angle::{Rad, atan2, acos}; use approx::ApproxEq; use array::{Array, build}; use partial_ord::{PartOrdPrim, PartOrdFloat}; /// A trait that specifies a range of numeric operations for vectors. Not all /// of these make sense from a linear algebra point of view, but are included /// for pragmatic reasons. pub trait Vector < S: PartOrdPrim, Slice > : Array<S, Slice> + Neg<Self> + Zero + One { #[inline] fn add_s(&self, s: S) -> Self { build(|i| self.i(i).add(&s)) } #[inline] fn sub_s(&self, s: S) -> Self { build(|i| self.i(i).sub(&s)) } #[inline] fn mul_s(&self, s: S) -> Self { build(|i| self.i(i).mul(&s)) } #[inline] fn div_s(&self, s: S) -> Self { build(|i| self.i(i).div(&s)) } #[inline] fn rem_s(&self, s: S) -> Self { build(|i| self.i(i).rem(&s)) } #[inline] fn add_v(&self, other: &Self) -> Self { build(|i| self.i(i).add(other.i(i))) } #[inline] fn sub_v(&self, other: &Self) -> Self { build(|i| self.i(i).sub(other.i(i))) } #[inline] fn mul_v(&self, other: &Self) -> Self { build(|i| self.i(i).mul(other.i(i))) } #[inline] fn div_v(&self, other: &Self) -> Self { build(|i| self.i(i).div(other.i(i))) } #[inline] fn rem_v(&self, other: &Self) -> Self { build(|i| self.i(i).rem(other.i(i))) } #[inline] fn neg_self(&mut self) { self.each_mut(|_, x| *x = x.neg()) } #[inline] fn add_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.add(&s)) } #[inline] fn sub_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.sub(&s)) } #[inline] fn mul_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.mul(&s)) } #[inline] fn div_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.div(&s)) } #[inline] fn rem_self_s(&mut self, s: S) { self.each_mut(|_, x| *x = x.rem(&s)) } #[inline] fn add_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.add(other.i(i))) } #[inline] fn sub_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.sub(other.i(i))) } #[inline] fn mul_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.mul(other.i(i))) } #[inline] fn div_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.div(other.i(i))) } #[inline] fn rem_self_v(&mut self, other: &Self) { self.each_mut(|i, x| *x = x.rem(other.i(i))) } /// The sum of each component of the vector. #[inline] fn comp_add(&self) -> S { self.fold(|a, b| a.add(b)) } /// The product of each component of the vector. #[inline] fn comp_mul(&self) -> S { self.fold(|a, b| a.mul(b)) } /// Vector dot product. #[inline] fn dot(&self, other: &Self) -> S { self.mul_v(other).comp_add() } /// The minimum component of the vector. #[inline] fn comp_min(&self) -> S { self.fold(|a, b| if *a < *b { *a } else {*b }) } /// The maximum component of the vector. #[inline] fn comp_max(&self) -> S { self.fold(|a, b| if *a > *b { *a } else {*b }) } } #[inline] pub fn dot<S: PartOrdPrim, Slice, V: Vector<S, Slice>>(a: V, b: V) -> S { a.dot(&b) } // Utility macro for generating associated functions for the vectors macro_rules! vec( ($Self:ident <$S:ident> { $($field:ident),+ }, $n:expr) => ( #[deriving(Eq, TotalEq, Clone, Hash)] pub struct $Self<S> { $(pub $field: S),+ } impl<$S: Primitive> $Self<$S> { #[inline] pub fn new($($field: $S),+) -> $Self<$S> { $Self { $($field: $field),+ } } /// Construct a vector from a single value. #[inline] pub fn from_value(value: $S) -> $Self<$S> { $Self { $($field: value.clone()),+ } } /// The additive identity of the vector. #[inline] pub fn zero() -> $Self<$S> { $Self::from_value(zero()) } /// The multiplicative identity of the vector. #[inline] pub fn ident() -> $Self<$S> { $Self::from_value(one()) } } impl<S: PartOrdPrim> Add<$Self<S>, $Self<S>> for $Self<S> { #[inline] fn add(&self, other: &$Self<S>) -> $Self<S> { self.add_v(other) } } impl<S: PartOrdPrim> Sub<$Self<S>, $Self<S>> for $Self<S> { #[inline] fn sub(&self, other: &$Self<S>) -> $Self<S> { self.sub_v(other) } } impl<S: PartOrdPrim> Zero for $Self<S> { #[inline] fn zero() -> $Self<S> { $Self::from_value(zero()) } #[inline] fn is_zero(&self) -> bool { *self == zero() } } impl<S: PartOrdPrim> Neg<$Self<S>> for $Self<S> { #[inline] fn neg(&self) -> $Self<S> { build(|i| self.i(i).neg()) } } impl<S: PartOrdPrim> Mul<$Self<S>, $Self<S>> for $Self<S> { #[inline] fn mul(&self, other: &$Self<S>) -> $Self<S> { self.mul_v(other) } } impl<S: PartOrdPrim> One for $Self<S> { #[inline] fn one() -> $Self<S> { $Self::from_value(one()) } } impl<S: PartOrdPrim> Vector<S, [S, ..$n]> for $Self<S> {} ) ) vec!(Vector2<S> { x, y }, 2) vec!(Vector3<S> { x, y, z }, 3) vec!(Vector4<S> { x, y, z, w }, 4) array!(impl<S> Vector2<S> -> [S, ..2] _2) array!(impl<S> Vector3<S> -> [S, ..3] _3) array!(impl<S> Vector4<S> -> [S, ..4] _4) /// Operations specific to numeric two-dimensional vectors. impl<S: Primitive> Vector2<S> { #[inline] pub fn unit_x() -> Vector2<S> { Vector2::new(one(), zero()) } #[inline] pub fn unit_y() -> Vector2<S> { Vector2::new(zero(), one()) } /// The perpendicular dot product of the vector and `other`. #[inline] pub fn perp_dot(&self, other: &Vector2<S>) -> S { (self.x * other.y) - (self.y * other.x) } #[inline] pub fn extend(&self, z: S)-> Vector3<S> { Vector3::new(self.x.clone(), self.y.clone(), z) } } /// Operations specific to numeric three-dimensional vectors. impl<S: Primitive> Vector3<S> { #[inline] pub fn unit_x() -> Vector3<S> { Vector3::new(one(), zero(), zero()) } #[inline] pub fn unit_y() -> Vector3<S> { Vector3::new(zero(), one(), zero()) } #[inline] pub fn unit_z() -> Vector3<S> { Vector3::new(zero(), zero(), one()) } /// Returns the cross product of the vector and `other`. #[inline] pub fn cross(&self, other: &Vector3<S>) -> Vector3<S> { Vector3::new((self.y * other.z) - (self.z * other.y), (self.z * other.x) - (self.x * other.z), (self.x * other.y) - (self.y * other.x)) } /// Calculates the cross product of the vector and `other`, then stores the /// result in `self`. #[inline] pub fn cross_self(&mut self, other: &Vector3<S>) { *self = self.cross(other) } #[inline] pub fn extend(&self, w: S)-> Vector4<S> { Vector4::new(self.x.clone(), self.y.clone(), self.z.clone(), w) } #[inline] pub fn truncate(&self)-> Vector2<S> { Vector2::new(self.x.clone(), self.y.clone()) //ignore Z } } /// Operations specific to numeric four-dimensional vectors. impl<S: Primitive> Vector4<S> { #[inline] pub fn unit_x() -> Vector4<S> { Vector4::new(one(), zero(), zero(), zero()) } #[inline] pub fn unit_y() -> Vector4<S> { Vector4::new(zero(), one(), zero(), zero()) } #[inline] pub fn unit_z() -> Vector4<S> { Vector4::new(zero(), zero(), one(), zero()) } #[inline] pub fn unit_w() -> Vector4<S> { Vector4::new(zero(), zero(), zero(), one()) } #[inline] pub fn truncate(&self)-> Vector3<S> { Vector3::new(self.x.clone(), self.y.clone(), self.z.clone()) //ignore W } } /// Specifies geometric operations for vectors. This is only implemented for /// 2-dimensional and 3-dimensional vectors. pub trait EuclideanVector < S: PartOrdFloat<S>, Slice > : Vector<S, Slice> + ApproxEq<S> { /// Returns `true` if the vector is perpendicular (at right angles to) /// the other vector. fn is_perpendicular(&self, other: &Self) -> bool { self.dot(other).approx_eq(&zero()) } /// Returns the squared length of the vector. This does not perform an /// expensive square root operation like in the `length` method and can /// therefore be more efficient for comparing the lengths of two vectors. #[inline] fn length2(&self) -> S { self.dot(self) } /// The norm of the vector. #[inline] fn length(&self) -> S { self.dot(self).sqrt() } /// The angle between the vector and `other`. fn angle(&self, other: &Self) -> Rad<S>; /// Returns a vector with the same direction, but with a `length` (or /// `norm`) of `1`. #[inline] fn normalize(&self) -> Self { self.normalize_to(one::<S>()) } /// Returns a vector with the same direction and a given `length`. #[inline] fn normalize_to(&self, length: S) -> Self { self.mul_s(length / self.length()) } /// Returns the result of linarly interpolating the length of the vector /// towards the length of `other` by the specified amount. #[inline] fn lerp(&self, other: &Self, amount: S) -> Self { self.add_v(&other.sub_v(self).mul_s(amount)) } /// Normalises the vector to a length of `1`. #[inline] fn normalize_self(&mut self) { let rlen = self.length().recip(); self.mul_self_s(rlen); } /// Normalizes the vector to `length`. #[inline] fn normalize_self_to(&mut self, length: S) { let n = length / self.length(); self.mul_self_s(n); } /// Linearly interpolates the length of the vector towards the length of /// `other` by the specified amount. fn lerp_self(&mut self, other: &Self, amount: S) { let v = other.sub_v(self).mul_s(amount); self.add_self_v(&v); } } impl<S: PartOrdFloat<S>> EuclideanVector<S, [S, ..2]> for Vector2<S> { #[inline] fn angle(&self, other: &Vector2<S>) -> Rad<S> { atan2(self.perp_dot(other), self.dot(other)) } } impl<S: PartOrdFloat<S>> EuclideanVector<S, [S, ..3]> for Vector3<S> { #[inline] fn angle(&self, other: &Vector3<S>) -> Rad<S> { atan2(self.cross(other).length(), self.dot(other)) } } impl<S: PartOrdFloat<S>> EuclideanVector<S, [S, ..4]> for Vector4<S> { #[inline] fn angle(&self, other: &Vector4<S>) -> Rad<S> { acos(self.dot(other) / (self.length() * other.length())) } } impl<S: fmt::Show> fmt::Show for Vector2<S> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f.buf, "[{}, {}]", self.x, self.y) } } impl<S: fmt::Show> fmt::Show for Vector3<S> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f.buf, "[{}, {}, {}]", self.x, self.y, self.z) } } impl<S: fmt::Show> fmt::Show for Vector4<S> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f.buf, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w) } }
true
aa2133a0602ed220752e77bbc052bd17dd1913e8
Rust
mac-l1/RemarkableFramebuffer
/rust-implementation/librustpad/src/ev.rs
UTF-8
1,309
2.578125
3
[ "MIT" ]
permissive
use evdev; use epoll; use std; pub trait EvdevHandler { fn on_init(&mut self, name: String, device: &mut evdev::Device); fn on_event(&mut self, device: &String, event: evdev::raw::input_event); } pub fn start_evdev<H: EvdevHandler>(path: String, handler: &mut H) { let mut dev = evdev::Device::open(&path).unwrap(); let devn = unsafe { let mut ptr = std::mem::transmute(dev.name().as_ptr()); std::ffi::CString::from_raw(ptr).into_string().unwrap() }; let mut v = vec![ epoll::Event { events: (epoll::Events::EPOLLET | epoll::Events::EPOLLIN | epoll::Events::EPOLLPRI) .bits(), data: 0, }, ]; let epfd = epoll::create(false).unwrap(); epoll::ctl(epfd, epoll::ControlOptions::EPOLL_CTL_ADD, dev.fd(), v[0]).unwrap(); // init callback handler.on_init(devn.clone(), &mut dev); loop { // -1 indefinite wait but it is okay because our EPOLL FD is watching on ALL input devices at once let res = epoll::wait(epfd, -1, &mut v[0..1]).unwrap(); if res != 1 { println!("WARN: epoll_wait returned {0}", res); } for ev in dev.events_no_sync().unwrap() { // event callback handler.on_event(&devn, ev); } } }
true
3bde34b786d73b595b467dc049cf9385c9d19032
Rust
scottschroeder/storyestimate
/src/webapp/apikey.rs
UTF-8
2,398
3.25
3
[]
no_license
use hyper::header::Basic; use rocket::Outcome; use rocket::http::Status; use rocket::request::{self, FromRequest, Request}; use std::str::FromStr; #[derive(Serialize, Deserialize)] #[derive(Debug, PartialEq, Eq, Clone)] pub struct APIKey { pub user_id: String, pub user_key: Option<String>, } impl<'a, 'r> FromRequest<'a, 'r> for APIKey { type Error = (); fn from_request(request: &'a Request<'r>) -> request::Outcome<APIKey, ()> { let basic_auth = get_basic_auth(request); let token_auth = get_token_auth(request); match (basic_auth, token_auth) { (None, None) => Outcome::Failure((Status::Unauthorized, ())), (Some(_), Some(_)) => { warn!("User passed both a TOK header and HTTP Basic Auth"); Outcome::Failure((Status::Unauthorized, ())) }, (Some(auth), None) => Outcome::Success(auth), (None, Some(auth)) => Outcome::Success(auth), } } } fn get_basic_auth<'a, 'r>(request: &'a Request<'r>) -> Option<APIKey> { let user_auth: String = match request.headers().get_one("Authorization") { Some(auth_data) => auth_data.to_string(), None => return None, }; let base64_encoded_auth = user_auth.replace("Basic ", ""); let authdata: Basic = match Basic::from_str(&base64_encoded_auth) { Ok(authdata) => authdata, Err(_) => return None, }; Some(APIKey { user_id: authdata.username, user_key: authdata.password, }) } fn get_token_auth<'a, 'r>(request: &'a Request<'r>) -> Option<APIKey> { let user_token: String = match request.headers().get_one("X-API-Key") { Some(auth_data) => auth_data.to_string(), None => return None, }; let user_data: Vec<&str> = user_token.split(':').collect(); match user_data.len() { 0 => { warn!("User passed empty token"); None }, 1 => { Some(APIKey { user_id: user_data[0].to_string(), user_key: None, }) }, 2 => { Some(APIKey { user_id: user_data[0].to_string(), user_key: Some(user_data[1].to_string()), }) }, x => { warn!("User passed token with too many fields ({})", x); None }, } }
true
61759363a0b5888bd9ee9423e9cd5a7d9ebab4a3
Rust
lutostag/pincers
/src/read.rs
UTF-8
1,110
2.859375
3
[ "MIT" ]
permissive
use anyhow::Result; use reqwest; use std::collections::HashSet; use std::fs::File; use std::io::{self, Read}; lazy_static! { static ref REMOTE_SCHEMES: HashSet<&'static str> = hashset! { "https", "http", "ftps", "ftp" }; } pub fn is_remote(url: &str) -> bool { if let Ok(url) = reqwest::Url::parse(url) { return REMOTE_SCHEMES.contains(&url.scheme()); } false } pub fn download(url: &str) -> Result<Vec<u8>> { info!("Getting script: {}", url); let mut body = Vec::<u8>::new(); if url == "-" { debug!("Trying to read from stdin"); io::stdin().read_to_end(&mut body)?; } else if is_remote(&url) { debug!("Trying to read from remote {}", &url); reqwest::get(url)? .error_for_status()? .read_to_end(&mut body)?; } else { debug!("Trying to read from local {}", &url); File::open(url)?.read_to_end(&mut body)?; }; match std::str::from_utf8(&body) { Ok(val) => debug!("Read contents\n{}", val), Err(_) => debug!("Read content is binary"), } Ok(body) }
true
d5ad882aa012e47f2a4a629d9c9b00c41c9215b8
Rust
sdenel/tiny-static-web-server
/src/path_to_key.rs
UTF-8
1,707
3.40625
3
[]
no_license
use std::collections::HashSet; use std::sync::Mutex; // TODO: this function should return the nearest existing index.html, not root // TODO: Should the webapp behavior be activated with a flag? Currently, 404 requests are redirected to /index.html with no warning even for non webapps. pub fn path_to_key(path: &str, known_keys: &Mutex<HashSet<String>>) -> String { let key = path.to_string(); if key.ends_with("/") { let key_with_index = key.to_owned() + "index.html"; if known_keys.lock().unwrap().contains(&key_with_index) { return key_with_index; } } if !key.contains(".") { // We suppose that is the request is not for a file, and we can't find the associated /index.html, then the path is aimed for a webapp in index.html return "/index.html".to_string(); } return key; } #[cfg(test)] mod tests { use super::*; #[test] fn path_to_key1() { assert_eq!( "/hello.html", path_to_key("/hello.html", &Mutex::new(HashSet::new())) ); } #[test] fn path_to_key2() { assert_eq!( "/index.html", path_to_key("/", &Mutex::new(HashSet::new())) ); } #[test] fn path_to_key3() { assert_eq!( "/index.html", path_to_key("/stuart/", &Mutex::new(HashSet::new())) ); } #[test] fn path_to_key4() { assert_eq!( "/stuart/index.html", path_to_key( "/stuart/", &Mutex::new( vec!("/stuart/index.html".to_string()) .into_iter().collect()), ) ); } }
true
9bd150b9f60cc944de9853f6f305b8a9e3e2f106
Rust
iamparnab/rusty-tree
/src/main.rs
UTF-8
1,261
3.375
3
[]
no_license
fn main() { for i in 1..4 { draw_tree_segment(i); } draw_stem(); draw_base(); } const HEIGHT: i32 = 12; const WIDTH: i32 = 1 + (HEIGHT - 1) * 2; // AP const STEM_WIDTH: i32 = HEIGHT / 3; const STEM_HEIGHT: i32 = HEIGHT / 3; const BASE_WIDTH: i32 = WIDTH * 2; fn draw_tree_segment(level: i32) { let mut stars = 1; for i in 1..(HEIGHT + 1) { // Chop off the head if level is not 1 if !(level > 1 && i < HEIGHT * 10 / 15) { add_padding(); // i - 1, because, we need zero space at last row for _ in 1..((WIDTH / 2) - (i - 1) + 1) { print!(" "); } for _ in 1..(stars + 1) { print!("^"); } println!(); } stars += 2; } } fn draw_stem() { for _ in 1..(STEM_HEIGHT + 1) { add_padding(); for _ in 1..(WIDTH / 2 - STEM_WIDTH / 2 + 1) { print!(" ") } for _ in 1..(STEM_WIDTH + 1) { print!("|") } println!() } } fn draw_base() { for _ in 1..(BASE_WIDTH + 1) { print!("*") } println!() } fn add_padding() { for _ in 1..BASE_WIDTH / 2 - WIDTH / 2 + 1 { print!(" ") } }
true
1a7d103e7b9a678d8265489b1b92fb76d6a6420f
Rust
madskjeldgaard/nannou
/nannou_laser/src/ffi.rs
UTF-8
26,593
2.953125
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! Expose a C compatible interface. use std::collections::HashMap; use std::ffi::CString; use std::fmt; use std::io; use std::os::raw; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; /// Allows for detecting and enumerating laser DACs on a network and establishing new streams of /// communication with them. #[repr(C)] pub struct Api { inner: *mut ApiInner, } /// A handle to a non-blocking DAC detection thread. #[repr(C)] pub struct DetectDacsAsync { inner: *mut DetectDacsAsyncInner, } /// Represents a DAC that has been detected on the network along with any information collected /// about the DAC in the detection process. #[repr(C)] #[derive(Clone, Copy)] pub struct DetectedDac { pub kind: DetectedDacKind, } /// A union for distinguishing between the kind of LASER DAC that was detected. Currently, only /// EtherDream is supported, however this will gain more variants as more protocols are added (e.g. /// AVB). #[repr(C)] #[derive(Clone, Copy)] pub union DetectedDacKind { pub ether_dream: DacEtherDream, } /// An Ether Dream DAC that was detected on the network. #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct DacEtherDream { pub broadcast: ether_dream::protocol::DacBroadcast, pub source_addr: SocketAddr, } /// A set of stream configuration parameters applied to the initialisation of both `Raw` and /// `Frame` streams. #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct StreamConfig { /// A valid pointer to a `DetectedDac` that should be targeted. pub detected_dac: *const DetectedDac, /// The rate at which the DAC should process points per second. /// /// This value should be no greater than the detected DAC's `max_point_hz`. pub point_hz: raw::c_uint, /// The maximum latency specified as a number of points. /// /// Each time the laser indicates its "fullness", the raw stream will request enough points /// from the render function to fill the DAC buffer up to `latency_points`. /// /// This value should be no greaterthan the DAC's `buffer_capacity`. pub latency_points: raw::c_uint, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub enum IpAddrVersion { V4, V6, } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct IpAddr { pub version: IpAddrVersion, /// 4 bytes used for `V4`, 16 bytes used for `V6`. pub bytes: [raw::c_uchar; 16], } #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct SocketAddr { pub ip: IpAddr, pub port: raw::c_ushort, } /// A handle to a stream that requests frames of LASER data from the user. /// /// Each "frame" has an optimisation pass applied that optimises the path for inertia, minimal /// blanking, point de-duplication and segment order. #[repr(C)] pub struct FrameStream { inner: *mut FrameStreamInner, } /// A handle to a raw LASER stream that requests the exact number of points that the DAC is /// awaiting in each call to the user's callback. #[repr(C)] pub struct RawStream { inner: *mut RawStreamInner, } #[repr(C)] #[derive(Clone, Copy)] pub enum Result { Success = 0, DetectDacFailed, BuildStreamFailed, DetectDacsAsyncFailed, } /// A set of stream configuration parameters unique to `Frame` streams. #[repr(C)] #[derive(Clone, Debug)] pub struct FrameStreamConfig { pub stream_conf: StreamConfig, /// The rate at which the stream will attempt to present images via the DAC. This value is used /// in combination with the DAC's `point_hz` in order to determine how many points should be /// used to draw each frame. E.g. /// /// ```ignore /// let points_per_frame = point_hz / frame_hz; /// ``` /// /// This is simply used as a minimum value. E.g. if some very simple geometry is submitted, this /// allows the DAC to spend more time creating the path for the image. However, if complex geometry /// is submitted that would require more than the ideal `points_per_frame`, the DAC may not be able /// to achieve the desired `frame_hz` when drawing the path while also taking the /// `distance_per_point` and `radians_per_point` into consideration. pub frame_hz: u32, /// Configuration options for eulerian circuit interpolation. pub interpolation_conf: crate::stream::frame::opt::InterpolationConfig, } #[repr(C)] pub struct Frame { inner: *mut FrameInner, } #[repr(C)] pub struct Buffer { inner: *mut BufferInner, } struct FrameInner(*mut crate::stream::frame::Frame); struct BufferInner(*mut crate::stream::raw::Buffer); struct ApiInner { inner: crate::Api, last_error: Option<CString>, } struct DetectDacsAsyncInner { _inner: crate::DetectDacsAsync, dacs: Arc<Mutex<HashMap<crate::DacId, (Instant, crate::DetectedDac)>>>, last_error: Arc<Mutex<Option<CString>>>, } struct FrameStreamModel(*mut raw::c_void, FrameRenderCallback, RawRenderCallback); struct RawStreamModel(*mut raw::c_void, RawRenderCallback); unsafe impl Send for FrameStreamModel {} unsafe impl Send for RawStreamModel {} struct FrameStreamInner(crate::FrameStream<FrameStreamModel>); struct RawStreamInner(crate::RawStream<RawStreamModel>); /// Cast to `extern fn(*mut raw::c_void, *mut Frame)` internally. //pub type FrameRenderCallback = *const raw::c_void; pub type FrameRenderCallback = extern "C" fn(*mut raw::c_void, *mut Frame); /// Cast to `extern fn(*mut raw::c_void, *mut Buffer)` internally. //pub type RawRenderCallback = *const raw::c_void; pub type RawRenderCallback = extern "C" fn(*mut raw::c_void, *mut Buffer); /// Given some uninitialized pointer to an `Api` struct, fill it with a new Api instance. #[no_mangle] pub unsafe extern "C" fn api_new(api: *mut Api) { let inner = crate::Api::new(); let last_error = None; let boxed_inner = Box::new(ApiInner { inner, last_error }); (*api).inner = Box::into_raw(boxed_inner); } /// Given some uninitialised pointer to a `DetectDacsAsync` struct, fill it with a new instance. /// /// If the given `timeout_secs` is `0`, DAC detection will never timeout and detected DACs that no /// longer broadcast will remain accessible in the device map. #[no_mangle] pub unsafe extern "C" fn detect_dacs_async( api: *mut Api, timeout_secs: raw::c_float, detect_dacs: *mut DetectDacsAsync, ) -> Result { let api: &mut ApiInner = &mut (*(*api).inner); let duration = if timeout_secs == 0.0 { None } else { let secs = timeout_secs as u64; let nanos = ((timeout_secs - secs as raw::c_float) * 1_000_000_000.0) as u32; Some(std::time::Duration::new(secs, nanos)) }; let boxed_detect_dacs_inner = match detect_dacs_async_inner(&api.inner, duration) { Ok(detector) => Box::new(detector), Err(err) => { api.last_error = Some(err_to_cstring(&err)); return Result::DetectDacsAsyncFailed; } }; (*detect_dacs).inner = Box::into_raw(boxed_detect_dacs_inner); Result::Success } /// Retrieve a list of the currently available DACs. /// /// Calling this function should never block, and simply provide the list of DACs that have /// broadcast their availability within the last specified DAC timeout duration. #[no_mangle] pub unsafe extern "C" fn available_dacs( detect_dacs_async: *mut DetectDacsAsync, first_dac: *mut *mut DetectedDac, len: *mut raw::c_uint, ) { let detect_dacs_async: &mut DetectDacsAsyncInner = &mut (*(*detect_dacs_async).inner); *first_dac = std::ptr::null_mut(); *len = 0; if let Ok(dacs) = detect_dacs_async.dacs.lock() { if !dacs.is_empty() { let mut dacs: Box<[_]> = dacs .values() .map(|&(_, ref dac)| detected_dac_to_ffi(dac.clone())) .collect(); *len = dacs.len() as _; *first_dac = dacs.as_mut_ptr(); std::mem::forget(dacs); } } } /// Block the current thread until a new DAC is detected and return it. #[no_mangle] pub unsafe extern "C" fn detect_dac(api: *mut Api, detected_dac: *mut DetectedDac) -> Result { let api: &mut ApiInner = &mut (*(*api).inner); let mut iter = match api.inner.detect_dacs() { Err(err) => { api.last_error = Some(err_to_cstring(&err)); return Result::DetectDacFailed; } Ok(iter) => iter, }; match iter.next() { None => return Result::DetectDacFailed, Some(res) => match res { Ok(dac) => { *detected_dac = detected_dac_to_ffi(dac); return Result::Success; } Err(err) => { api.last_error = Some(err_to_cstring(&err)); return Result::DetectDacFailed; } }, } } /// Initialise the given frame stream configuration with default values. #[no_mangle] pub unsafe extern "C" fn frame_stream_config_default(conf: *mut FrameStreamConfig) { let stream_conf = default_stream_config(); let frame_hz = crate::stream::DEFAULT_FRAME_HZ; let interpolation_conf = crate::stream::frame::opt::InterpolationConfig::start().build(); *conf = FrameStreamConfig { stream_conf, frame_hz, interpolation_conf, }; } /// Initialise the given raw stream configuration with default values. #[no_mangle] pub unsafe extern "C" fn stream_config_default(conf: *mut StreamConfig) { *conf = default_stream_config(); } /// Spawn a new frame rendering stream. /// /// The `frame_render_callback` is called each time the stream is ready for a new `Frame` of laser /// points. Each "frame" has an optimisation pass applied that optimises the path for inertia, /// minimal blanking, point de-duplication and segment order. /// /// The `process_raw_callback` allows for optionally processing the raw points before submission to /// the DAC. This might be useful for: /// /// - applying post-processing effects onto the optimised, interpolated points. /// - monitoring the raw points resulting from the optimisation and interpolation processes. /// - tuning brightness of colours based on safety zones. /// /// The given function will get called right before submission of the optimised, interpolated /// buffer. #[no_mangle] pub unsafe extern "C" fn new_frame_stream( api: *mut Api, stream: *mut FrameStream, config: *const FrameStreamConfig, callback_data: *mut raw::c_void, frame_render_callback: FrameRenderCallback, process_raw_callback: RawRenderCallback, ) -> Result { let api: &mut ApiInner = &mut (*(*api).inner); let model = FrameStreamModel(callback_data, frame_render_callback, process_raw_callback); fn render_fn(model: &mut FrameStreamModel, frame: &mut crate::stream::frame::Frame) { let FrameStreamModel(callback_data_ptr, frame_render_callback, _) = *model; let mut inner = FrameInner(frame); let mut frame = Frame { inner: &mut inner }; frame_render_callback(callback_data_ptr, &mut frame); } let mut builder = api .inner .new_frame_stream(model, render_fn) .point_hz((*config).stream_conf.point_hz as _) .latency_points((*config).stream_conf.latency_points as _) .frame_hz((*config).frame_hz as _); fn process_raw_fn(model: &mut FrameStreamModel, buffer: &mut crate::stream::raw::Buffer) { let FrameStreamModel(callback_data_ptr, _, process_raw_callback) = *model; let mut inner = BufferInner(buffer); let mut buffer = Buffer { inner: &mut inner }; process_raw_callback(callback_data_ptr, &mut buffer); } builder = builder.process_raw(process_raw_fn); if (*config).stream_conf.detected_dac != std::ptr::null() { let ffi_dac = (*(*config).stream_conf.detected_dac).clone(); let detected_dac = detected_dac_from_ffi(ffi_dac); builder = builder.detected_dac(detected_dac); } let inner = match builder.build() { Err(err) => { api.last_error = Some(err_to_cstring(&err)); return Result::BuildStreamFailed; } Ok(stream) => Box::new(FrameStreamInner(stream)), }; (*stream).inner = Box::into_raw(inner); Result::Success } /// Spawn a new frame rendering stream. /// /// A raw LASER stream requests the exact number of points that the DAC is awaiting in each call to /// the user's `process_raw_callback`. Keep in mind that no optimisation passes are applied. When /// using a raw stream, this is the responsibility of the user. #[no_mangle] pub unsafe extern "C" fn new_raw_stream( api: *mut Api, stream: *mut RawStream, config: *const StreamConfig, callback_data: *mut raw::c_void, process_raw_callback: RawRenderCallback, ) -> Result { let api: &mut ApiInner = &mut (*(*api).inner); let model = RawStreamModel(callback_data, process_raw_callback); fn render_fn(model: &mut RawStreamModel, buffer: &mut crate::stream::raw::Buffer) { let RawStreamModel(callback_data_ptr, raw_render_callback) = *model; let mut inner = BufferInner(buffer); let mut buffer = Buffer { inner: &mut inner }; raw_render_callback(callback_data_ptr, &mut buffer); } let mut builder = api .inner .new_raw_stream(model, render_fn) .point_hz((*config).point_hz as _) .latency_points((*config).latency_points as _); if (*config).detected_dac != std::ptr::null() { let ffi_dac = (*(*config).detected_dac).clone(); let detected_dac = detected_dac_from_ffi(ffi_dac); builder = builder.detected_dac(detected_dac); } let inner = match builder.build() { Err(err) => { api.last_error = Some(err_to_cstring(&err)); return Result::BuildStreamFailed; } Ok(stream) => Box::new(RawStreamInner(stream)), }; (*stream).inner = Box::into_raw(inner); Result::Success } /// Update the rate at which the DAC should process points per second. /// /// This value should be no greater than the detected DAC's `max_point_hz`. /// /// By default this value is `stream::DEFAULT_POINT_HZ`. /// /// Returns `true` on success or `false` if the communication channel was closed. pub unsafe extern "C" fn frame_stream_set_point_hz( stream: *const FrameStream, point_hz: u32, ) -> bool { let stream: &FrameStream = &*stream; (*stream.inner).0.set_point_hz(point_hz).is_ok() } /// The maximum latency specified as a number of points. /// /// Each time the laser indicates its "fullness", the raw stream will request enough points /// from the render function to fill the DAC buffer up to `latency_points`. /// /// This value should be no greaterthan the DAC's `buffer_capacity`. /// /// Returns `true` on success or `false` if the communication channel was closed. pub unsafe extern "C" fn frame_stream_set_latency_points( stream: *const FrameStream, points: u32, ) -> bool { let stream: &FrameStream = &*stream; (*stream.inner).0.set_latency_points(points).is_ok() } /// Update the `distance_per_point` field of the interpolation configuration used within the /// optimisation pass for frames. This represents the minimum distance the interpolator can travel /// along an edge before a new point is required. /// /// The value will be updated on the laser thread prior to requesting the next frame. /// /// Returns `true` on success or `false` if the communication channel was closed. pub unsafe extern "C" fn frame_stream_set_distance_per_point( stream: *const FrameStream, distance_per_point: f32, ) -> bool { let stream: &FrameStream = &*stream; (*stream.inner) .0 .set_distance_per_point(distance_per_point) .is_ok() } /// Update the `blank_delay_points` field of the interpolation configuration. This represents the /// number of points to insert at the end of a blank to account for light modulator delay. /// /// The value will be updated on the laser thread prior to requesting the next frame. /// /// Returns `true` on success or `false` if the communication channel was closed. pub unsafe extern "C" fn frame_stream_set_blank_delay_points( stream: *const FrameStream, points: u32, ) -> bool { let stream: &FrameStream = &*stream; (*stream.inner).0.set_blank_delay_points(points).is_ok() } /// Update the `radians_per_point` field of the interpolation configuration. This represents the /// amount of delay to add based on the angle of the corner in radians. /// /// The value will be updated on the laser thread prior to requesting the next frame. /// /// Returns `true` on success or `false` if the communication channel was closed. pub unsafe extern "C" fn frame_stream_set_radians_per_point( stream: *const FrameStream, radians_per_point: f32, ) -> bool { let stream: &FrameStream = &*stream; (*stream.inner) .0 .set_radians_per_point(radians_per_point) .is_ok() } /// Update the rate at which the stream will attempt to present images via the DAC. This value is /// used in combination with the DAC's `point_hz` in order to determine how many points should be /// used to draw each frame. E.g. /// /// ```ignore /// let points_per_frame = point_hz / frame_hz; /// ``` /// /// This is simply used as a minimum value. E.g. if some very simple geometry is submitted, this /// allows the DAC to spend more time creating the path for the image. However, if complex geometry /// is submitted that would require more than the ideal `points_per_frame`, the DAC may not be able /// to achieve the desired `frame_hz` when drawing the path while also taking the /// `distance_per_point` and `radians_per_point` into consideration. /// /// The value will be updated on the laser thread prior to requesting the next frame. /// /// Returns `true` on success or `false` if the communication channel was closed. pub unsafe extern "C" fn frame_stream_set_frame_hz( stream: *const FrameStream, frame_hz: u32, ) -> bool { let stream: &FrameStream = &*stream; (*stream.inner).0.set_frame_hz(frame_hz).is_ok() } /// Update the rate at which the DAC should process points per second. /// /// This value should be no greater than the detected DAC's `max_point_hz`. /// /// By default this value is `stream::DEFAULT_POINT_HZ`. /// /// Returns `true` on success or `false` if the communication channel was closed. pub unsafe extern "C" fn raw_stream_set_point_hz(stream: *const RawStream, point_hz: u32) -> bool { let stream: &RawStream = &*stream; (*stream.inner).0.set_point_hz(point_hz).is_ok() } /// The maximum latency specified as a number of points. /// /// Each time the laser indicates its "fullness", the raw stream will request enough points /// from the render function to fill the DAC buffer up to `latency_points`. /// /// This value should be no greaterthan the DAC's `buffer_capacity`. /// /// Returns `true` on success or `false` if the communication channel was closed. pub unsafe extern "C" fn raw_stream_set_latency_points( stream: *const RawStream, points: u32, ) -> bool { let stream: &RawStream = &*stream; (*stream.inner).0.set_latency_points(points).is_ok() } /// Add a sequence of consecutive points separated by blank space. /// /// If some points already exist in the frame, this method will create a blank segment between the /// previous point and the first point before appending this sequence. #[no_mangle] pub unsafe extern "C" fn frame_add_points( frame: *mut Frame, points: *const crate::Point, len: usize, ) { let frame = &mut *frame; let points = std::slice::from_raw_parts(points, len); (*(*frame.inner).0).add_points(points.iter().cloned()); } /// Add a sequence of consecutive lines. /// /// If some points already exist in the frame, this method will create a blank segment between the /// previous point and the first point before appending this sequence. #[no_mangle] pub unsafe extern "C" fn frame_add_lines( frame: *mut Frame, points: *const crate::Point, len: usize, ) { let frame = &mut *frame; let points = std::slice::from_raw_parts(points, len); (*(*frame.inner).0).add_lines(points.iter().cloned()); } /// Retrieve the current `frame_hz` at the time of rendering this `Frame`. #[no_mangle] pub unsafe extern "C" fn frame_hz(frame: *const Frame) -> u32 { (*(*(*frame).inner).0).frame_hz() } /// Retrieve the current `point_hz` at the time of rendering this `Frame`. #[no_mangle] pub unsafe extern "C" fn frame_point_hz(frame: *const Frame) -> u32 { (*(*(*frame).inner).0).point_hz() } /// Retrieve the current `latency_points` at the time of rendering this `Frame`. #[no_mangle] pub unsafe extern "C" fn frame_latency_points(frame: *const Frame) -> u32 { (*(*(*frame).inner).0).latency_points() } /// Retrieve the current ideal `points_per_frame` at the time of rendering this `Frame`. #[no_mangle] pub unsafe extern "C" fn points_per_frame(frame: *const Frame) -> u32 { (*(*(*frame).inner).0).latency_points() } /// Must be called in order to correctly clean up the frame stream. #[no_mangle] pub unsafe extern "C" fn frame_stream_drop(stream: FrameStream) { if stream.inner != std::ptr::null_mut() { Box::from_raw(stream.inner); } } /// Must be called in order to correctly clean up the raw stream. #[no_mangle] pub unsafe extern "C" fn raw_stream_drop(stream: RawStream) { if stream.inner != std::ptr::null_mut() { Box::from_raw(stream.inner); } } /// Must be called in order to correctly clean up the `DetectDacsAsync` resources. #[no_mangle] pub unsafe extern "C" fn detect_dacs_async_drop(detect: DetectDacsAsync) { if detect.inner != std::ptr::null_mut() { Box::from_raw(detect.inner); } } /// Must be called in order to correctly clean up the API resources. #[no_mangle] pub unsafe extern "C" fn api_drop(api: Api) { if api.inner != std::ptr::null_mut() { Box::from_raw(api.inner); } } /// Used for retrieving the last error that occurred from the API. #[no_mangle] pub unsafe extern "C" fn api_last_error(api: *const Api) -> *const raw::c_char { let api: &ApiInner = &(*(*api).inner); match api.last_error { None => std::ptr::null(), Some(ref cstring) => cstring.as_ptr(), } } /// Used for retrieving the last error that occurred from the API. #[no_mangle] pub unsafe extern "C" fn detect_dacs_async_last_error( detect: *const DetectDacsAsync, ) -> *const raw::c_char { let detect_dacs_async: &DetectDacsAsyncInner = &(*(*detect).inner); let mut s = std::ptr::null(); if let Ok(last_error) = detect_dacs_async.last_error.lock() { if let Some(ref cstring) = *last_error { s = cstring.as_ptr(); } } s } /// Begin asynchronous DAC detection. /// /// The given timeout corresponds to the duration of time since the last DAC broadcast was received /// before a DAC will be considered to be unavailable again. fn detect_dacs_async_inner( api: &crate::Api, dac_timeout: Option<Duration>, ) -> io::Result<DetectDacsAsyncInner> { let dacs = Arc::new(Mutex::new(HashMap::new())); let last_error = Arc::new(Mutex::new(None)); let dacs2 = dacs.clone(); let last_error2 = last_error.clone(); let _inner = api.detect_dacs_async( dac_timeout, move |res: io::Result<crate::DetectedDac>| match res { Ok(dac) => { let now = Instant::now(); let mut dacs = dacs2.lock().unwrap(); dacs.insert(dac.id(), (now, dac)); if let Some(timeout) = dac_timeout { dacs.retain(|_, (ref last_bc, _)| now.duration_since(*last_bc) < timeout); } } Err(err) => match err.kind() { io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut => { dacs2.lock().unwrap().clear(); } _ => { *last_error2.lock().unwrap() = Some(err_to_cstring(&err)); } }, }, )?; Ok(DetectDacsAsyncInner { _inner, dacs, last_error, }) } fn err_to_cstring(err: &dyn fmt::Display) -> CString { string_to_cstring(format!("{}", err)) } fn string_to_cstring(string: String) -> CString { CString::new(string.into_bytes()).expect("`string` contained null bytes") } fn default_stream_config() -> StreamConfig { let detected_dac = std::ptr::null(); let point_hz = crate::stream::DEFAULT_POINT_HZ; let latency_points = crate::stream::raw::default_latency_points(point_hz); StreamConfig { detected_dac, point_hz, latency_points, } } fn socket_addr_to_ffi(addr: std::net::SocketAddr) -> SocketAddr { let port = addr.port(); let mut bytes = [0u8; 16]; let ip = match addr.ip() { std::net::IpAddr::V4(ref ip) => { for (byte, octet) in bytes.iter_mut().zip(&ip.octets()) { *byte = *octet; } let version = IpAddrVersion::V4; IpAddr { version, bytes } } std::net::IpAddr::V6(ref ip) => { for (byte, octet) in bytes.iter_mut().zip(&ip.octets()) { *byte = *octet; } let version = IpAddrVersion::V6; IpAddr { version, bytes } } }; SocketAddr { ip, port } } fn socket_addr_from_ffi(addr: SocketAddr) -> std::net::SocketAddr { let ip = match addr.ip.version { IpAddrVersion::V4 => { let b = &addr.ip.bytes; std::net::IpAddr::from([b[0], b[1], b[2], b[3]]) } IpAddrVersion::V6 => std::net::IpAddr::from(addr.ip.bytes), }; std::net::SocketAddr::new(ip, addr.port) } fn detected_dac_to_ffi(dac: crate::DetectedDac) -> DetectedDac { match dac { crate::DetectedDac::EtherDream { broadcast, source_addr, } => { let source_addr = socket_addr_to_ffi(source_addr); let ether_dream = DacEtherDream { broadcast, source_addr, }; let kind = DetectedDacKind { ether_dream }; DetectedDac { kind } } } } fn detected_dac_from_ffi(ffi_dac: DetectedDac) -> crate::DetectedDac { unsafe { let broadcast = ffi_dac.kind.ether_dream.broadcast.clone(); let source_addr = socket_addr_from_ffi(ffi_dac.kind.ether_dream.source_addr); crate::DetectedDac::EtherDream { broadcast, source_addr, } } }
true
38620374925e4827eca77667c9eb13b68879f167
Rust
colingluwa/Creditcoin-Consensus-Rust
/src/primitives/hash.rs
UTF-8
2,508
2.703125
3
[]
no_license
macro_rules! impl_hash { ($name:ident, $size:expr) => { #[derive(Clone, Copy)] #[repr(transparent)] pub struct $name { inner: [u8; $size], } impl $name { pub const SIZE: usize = $size; pub const MIN: Self = Self { inner: [u8::min_value(); $size], }; pub const MAX: Self = Self { inner: [u8::max_value(); $size], }; pub const fn new() -> Self { Self { inner: [0; $size] } } pub fn random() -> Self { let mut this: Self = Self::new(); ::rand::Rng::fill(&mut ::rand::thread_rng(), &mut this[..]); this } pub fn reversed(&self) -> Self { let mut this: Self = *self; this.reverse(); this } pub fn to_hex(&self) -> String { $crate::utils::to_hex(self) } } impl ::std::ops::Deref for $name { type Target = [u8]; fn deref(&self) -> &Self::Target { &self.inner } } impl ::std::ops::DerefMut for $name { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } impl AsRef<[u8]> for $name { fn as_ref(&self) -> &[u8] { &self.inner } } impl From<[u8; $size]> for $name { fn from(inner: [u8; $size]) -> Self { $name { inner } } } impl From<$name> for [u8; $size] { fn from(this: $name) -> Self { this.inner } } impl ::std::fmt::Debug for $name { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "{}", self.to_hex()) } } impl ::std::fmt::Display for $name { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "{}", self.to_hex()) } } impl Default for $name { fn default() -> Self { Self::new() } } impl PartialEq for $name { fn eq(&self, other: &Self) -> bool { (&**self).eq(&**other) } } impl Eq for $name {} impl PartialOrd for $name { fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> { (&**self).partial_cmp(&**other) } } impl Ord for $name { fn cmp(&self, other: &Self) -> ::std::cmp::Ordering { (&**self).cmp(&**other) } } impl ::std::hash::Hash for $name { fn hash<H: ::std::hash::Hasher>(&self, hasher: &mut H) { self.inner.hash(hasher) } } }; } impl_hash!(H256, 32);
true
1964af6946fc28cd363b40613e9e817d4617e63e
Rust
astral-sh/ruff
/crates/ruff_diagnostics/src/fix.rs
UTF-8
6,179
3.0625
3
[ "BSD-3-Clause", "0BSD", "LicenseRef-scancode-free-unknown", "GPL-1.0-or-later", "MIT", "Apache-2.0" ]
permissive
#[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use ruff_text_size::TextSize; use crate::edit::Edit; /// Indicates confidence in the correctness of a suggested fix. #[derive(Default, Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum Applicability { /// The fix is definitely what the user intended, or maintains the exact meaning of the code. /// This fix should be automatically applied. Automatic, /// The fix may be what the user intended, but it is uncertain. /// The fix should result in valid code if it is applied. /// The fix can be applied with user opt-in. Suggested, /// The fix has a good chance of being incorrect or the code be incomplete. /// The fix may result in invalid code if it is applied. /// The fix should only be manually applied by the user. Manual, /// The applicability of the fix is unknown. #[default] Unspecified, } /// Indicates the level of isolation required to apply a fix. #[derive(Default, Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum IsolationLevel { /// The fix should be applied as long as no other fixes in the same group have been applied. Group(u32), /// The fix should be applied as long as it does not overlap with any other fixes. #[default] NonOverlapping, } /// A collection of [`Edit`] elements to be applied to a source file. #[derive(Debug, PartialEq, Eq, Clone)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Fix { /// The [`Edit`] elements to be applied, sorted by [`Edit::start`] in ascending order. edits: Vec<Edit>, /// The [`Applicability`] of the fix. applicability: Applicability, /// The [`IsolationLevel`] of the fix. isolation_level: IsolationLevel, } impl Fix { /// Create a new [`Fix`] with an unspecified applicability from an [`Edit`] element. #[deprecated( note = "Use `Fix::automatic`, `Fix::suggested`, or `Fix::manual` instead to specify an applicability." )] pub fn unspecified(edit: Edit) -> Self { Self { edits: vec![edit], applicability: Applicability::Unspecified, isolation_level: IsolationLevel::default(), } } /// Create a new [`Fix`] with an unspecified applicability from multiple [`Edit`] elements. #[deprecated( note = "Use `Fix::automatic_edits`, `Fix::suggested_edits`, or `Fix::manual_edits` instead to specify an applicability." )] pub fn unspecified_edits(edit: Edit, rest: impl IntoIterator<Item = Edit>) -> Self { Self { edits: std::iter::once(edit).chain(rest).collect(), applicability: Applicability::Unspecified, isolation_level: IsolationLevel::default(), } } /// Create a new [`Fix`] with [automatic applicability](Applicability::Automatic) from an [`Edit`] element. pub fn automatic(edit: Edit) -> Self { Self { edits: vec![edit], applicability: Applicability::Automatic, isolation_level: IsolationLevel::default(), } } /// Create a new [`Fix`] with [automatic applicability](Applicability::Automatic) from multiple [`Edit`] elements. pub fn automatic_edits(edit: Edit, rest: impl IntoIterator<Item = Edit>) -> Self { let mut edits: Vec<Edit> = std::iter::once(edit).chain(rest).collect(); edits.sort_by_key(Edit::start); Self { edits, applicability: Applicability::Automatic, isolation_level: IsolationLevel::default(), } } /// Create a new [`Fix`] with [suggested applicability](Applicability::Suggested) from an [`Edit`] element. pub fn suggested(edit: Edit) -> Self { Self { edits: vec![edit], applicability: Applicability::Suggested, isolation_level: IsolationLevel::default(), } } /// Create a new [`Fix`] with [suggested applicability](Applicability::Suggested) from multiple [`Edit`] elements. pub fn suggested_edits(edit: Edit, rest: impl IntoIterator<Item = Edit>) -> Self { let mut edits: Vec<Edit> = std::iter::once(edit).chain(rest).collect(); edits.sort_by_key(Edit::start); Self { edits, applicability: Applicability::Suggested, isolation_level: IsolationLevel::default(), } } /// Create a new [`Fix`] with [manual applicability](Applicability::Manual) from an [`Edit`] element. pub fn manual(edit: Edit) -> Self { Self { edits: vec![edit], applicability: Applicability::Manual, isolation_level: IsolationLevel::default(), } } /// Create a new [`Fix`] with [manual applicability](Applicability::Manual) from multiple [`Edit`] elements. pub fn manual_edits(edit: Edit, rest: impl IntoIterator<Item = Edit>) -> Self { let mut edits: Vec<Edit> = std::iter::once(edit).chain(rest).collect(); edits.sort_by_key(Edit::start); Self { edits, applicability: Applicability::Manual, isolation_level: IsolationLevel::default(), } } /// Return the [`TextSize`] of the first [`Edit`] in the [`Fix`]. pub fn min_start(&self) -> Option<TextSize> { self.edits.first().map(Edit::start) } /// Return a slice of the [`Edit`] elements in the [`Fix`], sorted by [`Edit::start`] in ascending order. pub fn edits(&self) -> &[Edit] { &self.edits } /// Return the [`Applicability`] of the [`Fix`]. pub fn applicability(&self) -> Applicability { self.applicability } /// Return the [`IsolationLevel`] of the [`Fix`]. pub fn isolation(&self) -> IsolationLevel { self.isolation_level } /// Create a new [`Fix`] with the given [`IsolationLevel`]. #[must_use] pub fn isolate(mut self, isolation: IsolationLevel) -> Self { self.isolation_level = isolation; self } }
true
a1c5348ad2f062b5ba5bb6eace6e6851eaaa20eb
Rust
nbigaouette/advent_of_code_2018
/day03/src/preparsed_ndarray.rs
UTF-8
4,454
2.9375
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use std::cmp; use std::collections::HashSet; use crate::{parse_input, AoC, Day03SolutionPart1, Day03SolutionPart2, Input}; use ndarray::Array2; type Grid = Array2<Vec<usize>>; #[derive(Debug)] pub struct Day03PreparsedNdarray { input: Vec<Input>, grid_size_width: usize, grid_size_height: usize, } fn build_grid(input: &[Input], grid_size_width: usize, grid_size_height: usize) -> Grid { let mut grid = Array2::<Vec<usize>>::from_elem((grid_size_width, grid_size_height), Vec::new()); for claim in input { for i in claim.left..(claim.left + claim.wide) { for j in claim.top..(claim.top + claim.tall) { grid[[i, j]].push(claim.id); } } } grid } impl<'a> AoC<'a> for Day03PreparsedNdarray { type SolutionPart1 = Day03SolutionPart1; type SolutionPart2 = Day03SolutionPart2; fn description(&self) -> &'static str { "Pre-parsed string and ndarray" } fn new(input: &'a str) -> Day03PreparsedNdarray { let input: Vec<_> = parse_input(input).collect(); let grid_size_width = input.iter().fold(0, |acc, claim| { let width = claim.left + claim.wide; cmp::max(width, acc) }); let grid_size_height = input.iter().fold(0, |acc, claim| { let height = claim.top + claim.tall; cmp::max(height, acc) }); Day03PreparsedNdarray { input, grid_size_width, grid_size_height, } } fn solution_part1(&self) -> Self::SolutionPart1 { let grid = build_grid(&self.input, self.grid_size_width, self.grid_size_height); grid.iter() .filter_map(|p| if p.len() >= 2 { Some(1) } else { None }) .count() } fn solution_part2(&self) -> Self::SolutionPart2 { let grid = build_grid(&self.input, self.grid_size_width, self.grid_size_height); let mut claims: HashSet<usize> = self.input.iter().map(|claim| claim.id).collect(); for claim_ids in grid.iter() { if claim_ids.len() >= 2 { for claim_id in claim_ids { claims.remove(claim_id); } } } assert_eq!(claims.len(), 1); *claims.iter().next().unwrap() } } #[cfg(test)] mod tests { mod part1 { mod solution { use super::super::super::Day03PreparsedNdarray; use crate::{tests::init_logger, AoC, PUZZLE_INPUT}; #[test] fn solution() { init_logger(); let expected = 100595; let to_check = Day03PreparsedNdarray::new(PUZZLE_INPUT).solution_part1(); assert_eq!(expected, to_check); } } mod given { use super::super::super::Day03PreparsedNdarray; use crate::{tests::init_logger, AoC}; #[test] fn ex01() { init_logger(); let expected = 4; let input = "#1 @ 1,3: 4x4 #2 @ 3,1: 4x4 #3 @ 5,5: 2x2"; let to_check = Day03PreparsedNdarray::new(input).solution_part1(); assert_eq!(expected, to_check); } } /* mod extra { use ::*; } */ } mod part2 { mod solution { use super::super::super::Day03PreparsedNdarray; use crate::{tests::init_logger, AoC, PUZZLE_INPUT}; #[test] fn solution() { init_logger(); let expected = 415; let to_check = Day03PreparsedNdarray::new(PUZZLE_INPUT).solution_part2(); assert_eq!(expected, to_check); } } mod given { use super::super::super::Day03PreparsedNdarray; use crate::{tests::init_logger, AoC}; #[test] fn ex01() { init_logger(); let expected = 3; let input = "#1 @ 1,3: 4x4 #2 @ 3,1: 4x4 #3 @ 5,5: 2x2"; let to_check = Day03PreparsedNdarray::new(input).solution_part2(); assert_eq!(expected, to_check); } } /* mod extra { use ::*; } */ } }
true
2c09696fe56066e2f1721746d430a8ba43689692
Rust
kinseywk/dicey
/src/lib.rs
UTF-8
3,685
3.6875
4
[ "MIT" ]
permissive
#![allow(non_snake_case, non_upper_case_globals)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct DieRoll { //Number of dice in the roll pub quantity: usize, //Number of die faces (6 = standard cubic die) pub faces: usize, //Net bonus and malus applied to the roll (e.g., 1d4+1 adds 1 to each roll) pub adjustment: isize, } pub fn parse(diceRoll: &str) -> Option<Vec<DieRoll>> { let mut result: Vec<DieRoll> = Vec::new(); //1.) Split input string on each ',' let diceRoll: Vec<&str> = diceRoll.split(',').collect(); for dieRoll in diceRoll { let mut adjustmentChar: Option<char> = None; let mut adjustment: isize = 0; let mut dieString: &str = dieRoll; //2.) Split-off the '+' or '-' clause, if one exists //2a.) Test if '+' and '-' are in the string if let Some(_) = dieRoll.find('+') { adjustmentChar = Some('+'); } else if let Some(_) = dieRoll.find('-') { adjustmentChar = Some('-'); } //2b.) If either exists, break-off the front part and parse the latter part as an integer if let None = adjustmentChar { } else { if let Some((diePart, adjustmentPart)) = dieString.split_once(adjustmentChar.unwrap()) { dieString = diePart; if let Ok(adjustmentParsed) = adjustmentPart.parse::<isize>() { adjustment = adjustmentParsed; //2c.) Finally, if the prior test matched a '-', make the parsed number negative if adjustmentChar.unwrap() == '-' { adjustment = -adjustment; } } else { return None; } } } //3.) Split each dice string on 'd' if let Some((quantityPart, facesPart)) = dieString.split_once('d') { //4.) Parse each of _those_ strings as positive integers and create a DieRoll from each pair if let (Ok(quantity), Ok(faces)) = (quantityPart.parse::<usize>(), facesPart.parse::<usize>()) { if quantity == 0 || faces == 0 { return None; } else { result.push(DieRoll{quantity, faces, adjustment}); } } else { return None; } } else { return None; } } Some(result) } #[cfg(test)] mod tests { use super::*; #[test] fn parse_single() { { const test: &str = "5d6"; if let Some(result) = parse(test) { assert_eq!(result[0], DieRoll{quantity: 5, faces: 6, adjustment: 0}); } else { panic!("Failed to parse string \"{}\"", test); } } { const test: &str = "3d4+1"; if let Some(result) = parse(test) { assert_eq!(result[0], DieRoll{quantity: 3, faces: 4, adjustment: 1}); } else { panic!("Failed to parse string \"{}\"", test); } } { const test: &str = "1d2-1"; if let Some(result) = parse(test) { assert_eq!(result[0], DieRoll{quantity: 1, faces: 2, adjustment: -1}); } else { panic!("Failed to parse string \"{}\"", test); } } } #[test] fn parse_list() { const test: &str = "1d1,100d100,1000000d1000000,1d100+100,100d1-1"; if let Some(result) = parse(test) { assert_eq!(result.len(), 5, "Failed to parse all list entries"); assert_eq!(result[0], DieRoll{quantity: 1, faces: 1, adjustment: 0}); assert_eq!(result[1], DieRoll{quantity: 100, faces: 100, adjustment: 0}); assert_eq!(result[2], DieRoll{quantity: 1000000, faces: 1000000, adjustment: 0}); assert_eq!(result[3], DieRoll{quantity: 1, faces: 100, adjustment: 100}); assert_eq!(result[4], DieRoll{quantity: 100, faces: 1, adjustment: -1}); } else { panic!("Failed to parse string \"{}\"", test); } } #[test] fn parse_fail() { const tests: &'static [&'static str] = &["r2d2", "-3d3", "3d-3", "3d0", "0d3", "3d", "d3", "3d3,", ",", ""]; for test in tests { assert_eq!(parse(test), None, "Incorrectly parsed invalid string \"{}\"", test); } } }
true
1cb91910631be47d9fbc78821be91beeb4cc5743
Rust
Concordium/wasm-tools
/crates/wasm-encoder/src/code.rs
UTF-8
26,694
3.375
3
[ "LLVM-exception", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
use super::*; /// An encoder for the code section. /// /// # Example /// /// ``` /// use wasm_encoder::{ /// CodeSection, Function, FunctionSection, Instruction, Module, /// TypeSection, ValType /// }; /// /// let mut types = TypeSection::new(); /// types.function(vec![], vec![ValType::I32]); /// /// let mut functions = FunctionSection::new(); /// let type_index = 0; /// functions.function(type_index); /// /// let locals = vec![]; /// let mut func = Function::new(locals); /// func.instruction(Instruction::I32Const(42)); /// let mut code = CodeSection::new(); /// code.function(&func); /// /// let mut module = Module::new(); /// module /// .section(&types) /// .section(&functions) /// .section(&code); /// /// let wasm_bytes = module.finish(); /// ``` pub struct CodeSection { bytes: Vec<u8>, num_added: u32, } impl CodeSection { /// Create a new code section encoder. pub fn new() -> CodeSection { CodeSection { bytes: vec![], num_added: 0, } } /// Write a function body into this code section. pub fn function(&mut self, func: &Function) -> &mut Self { func.encode(&mut self.bytes); self.num_added += 1; self } } impl Section for CodeSection { fn id(&self) -> u8 { SectionId::Code.into() } fn encode<S>(&self, sink: &mut S) where S: Extend<u8>, { let num_added = encoders::u32(self.num_added); let n = num_added.len(); sink.extend( encoders::u32(u32::try_from(n + self.bytes.len()).unwrap()) .chain(num_added) .chain(self.bytes.iter().copied()), ); } } /// An encoder for a function body within the code section. /// /// # Example /// /// ``` /// use wasm_encoder::{CodeSection, Function, Instruction}; /// /// // Define the function body for: /// // /// // (func (param i32 i32) (result i32) /// // local.get 0 /// // local.get 1 /// // i32.add) /// let locals = vec![]; /// let mut func = Function::new(locals); /// func.instruction(Instruction::LocalGet(0)); /// func.instruction(Instruction::LocalGet(1)); /// func.instruction(Instruction::I32Add); /// /// // Add our function to the code section. /// let mut code = CodeSection::new(); /// code.function(&func); /// ``` pub struct Function { bytes: Vec<u8>, } impl Function { /// Create a new function body with the given locals. pub fn new<L>(locals: L) -> Self where L: IntoIterator<Item = (u32, ValType)>, L::IntoIter: ExactSizeIterator, { let locals = locals.into_iter(); let mut bytes = vec![]; bytes.extend(encoders::u32(u32::try_from(locals.len()).unwrap())); for (count, ty) in locals { bytes.extend(encoders::u32(count)); bytes.push(ty.into()); } Function { bytes } } /// Write an instruction into this function body. pub fn instruction(&mut self, instruction: Instruction) -> &mut Self { instruction.encode(&mut self.bytes); self } /// Add raw bytes to this function's body. pub fn raw<B>(&mut self, bytes: B) -> &mut Self where B: IntoIterator<Item = u8>, { self.bytes.extend(bytes); self } fn encode(&self, bytes: &mut Vec<u8>) { bytes.extend( encoders::u32(u32::try_from(self.bytes.len()).unwrap()) .chain(self.bytes.iter().copied()), ); } } /// The immediate for a memory instruction. #[derive(Clone, Copy, Debug)] pub struct MemArg { /// A static offset to add to the instruction's dynamic address operand. pub offset: u32, /// The expected alignment of the instruction's dynamic address operand /// (expressed the exponent of a power of two). pub align: u32, /// The index of the memory this instruction is operating upon. pub memory_index: u32, } impl MemArg { fn encode(&self, bytes: &mut Vec<u8>) { if self.memory_index == 0 { bytes.extend(encoders::u32(self.align)); bytes.extend(encoders::u32(self.offset)); } else { bytes.extend(encoders::u32(self.align | (1 << 6))); bytes.extend(encoders::u32(self.offset)); bytes.extend(encoders::u32(self.memory_index)); } } } /// The type for a `block`/`if`/`loop`. #[derive(Clone, Copy, Debug)] pub enum BlockType { /// `[] -> []` Empty, /// `[] -> [t]` Result(ValType), /// The `n`th function type. FunctionType(u32), } impl BlockType { fn encode(&self, bytes: &mut Vec<u8>) { match *self { BlockType::Empty => bytes.push(0x40), BlockType::Result(ty) => bytes.push(ty.into()), BlockType::FunctionType(f) => bytes.extend(encoders::s33(f.into())), } } } /// WebAssembly instructions. #[derive(Clone, Debug)] #[non_exhaustive] #[allow(missing_docs, non_camel_case_types)] pub enum Instruction<'a> { // Control instructions. Unreachable, Nop, Block(BlockType), Loop(BlockType), If(BlockType), Else, End, Br(u32), BrIf(u32), BrTable(&'a [u32], u32), Return, Call(u32), CallIndirect { ty: u32, table: u32 }, // Parametric instructions. Drop, Select, // Variable instructions. LocalGet(u32), LocalSet(u32), LocalTee(u32), GlobalGet(u32), GlobalSet(u32), // Memory instructions. I32Load(MemArg), I64Load(MemArg), F32Load(MemArg), F64Load(MemArg), I32Load8_S(MemArg), I32Load8_U(MemArg), I32Load16_S(MemArg), I32Load16_U(MemArg), I64Load8_S(MemArg), I64Load8_U(MemArg), I64Load16_S(MemArg), I64Load16_U(MemArg), I64Load32_S(MemArg), I64Load32_U(MemArg), I32Store(MemArg), I64Store(MemArg), F32Store(MemArg), F64Store(MemArg), I32Store8(MemArg), I32Store16(MemArg), I64Store8(MemArg), I64Store16(MemArg), I64Store32(MemArg), MemorySize(u32), MemoryGrow(u32), MemoryInit { mem: u32, data: u32 }, DataDrop(u32), MemoryCopy { src: u32, dst: u32 }, MemoryFill(u32), // Numeric instructions. I32Const(i32), I64Const(i64), F32Const(f32), F64Const(f64), I32Eqz, I32Eq, I32Neq, I32LtS, I32LtU, I32GtS, I32GtU, I32LeS, I32LeU, I32GeS, I32GeU, I64Eqz, I64Eq, I64Neq, I64LtS, I64LtU, I64GtS, I64GtU, I64LeS, I64LeU, I64GeS, I64GeU, F32Eq, F32Neq, F32Lt, F32Gt, F32Le, F32Ge, F64Eq, F64Neq, F64Lt, F64Gt, F64Le, F64Ge, I32Clz, I32Ctz, I32Popcnt, I32Add, I32Sub, I32Mul, I32DivS, I32DivU, I32RemS, I32RemU, I32And, I32Or, I32Xor, I32Shl, I32ShrS, I32ShrU, I32Rotl, I32Rotr, I64Clz, I64Ctz, I64Popcnt, I64Add, I64Sub, I64Mul, I64DivS, I64DivU, I64RemS, I64RemU, I64And, I64Or, I64Xor, I64Shl, I64ShrS, I64ShrU, I64Rotl, I64Rotr, F32Abs, F32Neg, F32Ceil, F32Floor, F32Trunc, F32Nearest, F32Sqrt, F32Add, F32Sub, F32Mul, F32Div, F32Min, F32Max, F32Copysign, F64Abs, F64Neg, F64Ceil, F64Floor, F64Trunc, F64Nearest, F64Sqrt, F64Add, F64Sub, F64Mul, F64Div, F64Min, F64Max, F64Copysign, I32WrapI64, I32TruncF32S, I32TruncF32U, I32TruncF64S, I32TruncF64U, I64ExtendI32S, I64ExtendI32U, I64TruncF32S, I64TruncF32U, I64TruncF64S, I64TruncF64U, F32ConvertI32S, F32ConvertI32U, F32ConvertI64S, F32ConvertI64U, F32DemoteF64, F64ConvertI32S, F64ConvertI32U, F64ConvertI64S, F64ConvertI64U, F64PromoteF32, I32ReinterpretF32, I64ReinterpretF64, F32ReinterpretI32, F64ReinterpretI64, I32Extend8S, I32Extend16S, I64Extend8S, I64Extend16S, I64Extend32S, I32TruncSatF32S, I32TruncSatF32U, I32TruncSatF64S, I32TruncSatF64U, I64TruncSatF32S, I64TruncSatF32U, I64TruncSatF64S, I64TruncSatF64U, // SIMD instructions. V128Const(i128), // Reference types instructions. TypedSelect(ValType), RefNull(ValType), RefIsNull, RefFunc(u32), // Bulk memory instructions. TableInit { segment: u32, table: u32 }, ElemDrop { segment: u32 }, TableFill { table: u32 }, TableSet { table: u32 }, TableGet { table: u32 }, TableGrow { table: u32 }, TableSize { table: u32 }, TableCopy { src: u32, dst: u32 }, } impl Instruction<'_> { pub(crate) fn encode(&self, bytes: &mut Vec<u8>) { match *self { // Control instructions. Instruction::Unreachable => bytes.push(0x00), Instruction::Nop => bytes.push(0x01), Instruction::Block(bt) => { bytes.push(0x02); bt.encode(bytes); } Instruction::Loop(bt) => { bytes.push(0x03); bt.encode(bytes); } Instruction::If(bt) => { bytes.push(0x04); bt.encode(bytes); } Instruction::Else => bytes.push(0x05), Instruction::End => bytes.push(0x0B), Instruction::Br(l) => { bytes.push(0x0C); bytes.extend(encoders::u32(l)); } Instruction::BrIf(l) => { bytes.push(0x0D); bytes.extend(encoders::u32(l)); } Instruction::BrTable(ls, l) => { bytes.push(0x0E); bytes.extend(encoders::u32(u32::try_from(ls.len()).unwrap())); for l in ls { bytes.extend(encoders::u32(*l)); } bytes.extend(encoders::u32(l)); } Instruction::Return => bytes.push(0x0F), Instruction::Call(f) => { bytes.push(0x10); bytes.extend(encoders::u32(f)); } Instruction::CallIndirect { ty, table } => { bytes.push(0x11); bytes.extend(encoders::u32(ty)); bytes.extend(encoders::u32(table)); } // Parametric instructions. Instruction::Drop => bytes.push(0x1A), Instruction::Select => bytes.push(0x1B), Instruction::TypedSelect(ty) => { bytes.push(0x1c); bytes.extend(encoders::u32(1)); bytes.push(ty.into()); } // Variable instructions. Instruction::LocalGet(l) => { bytes.push(0x20); bytes.extend(encoders::u32(l)); } Instruction::LocalSet(l) => { bytes.push(0x21); bytes.extend(encoders::u32(l)); } Instruction::LocalTee(l) => { bytes.push(0x22); bytes.extend(encoders::u32(l)); } Instruction::GlobalGet(g) => { bytes.push(0x23); bytes.extend(encoders::u32(g)); } Instruction::GlobalSet(g) => { bytes.push(0x24); bytes.extend(encoders::u32(g)); } Instruction::TableGet { table } => { bytes.push(0x25); bytes.extend(encoders::u32(table)); } Instruction::TableSet { table } => { bytes.push(0x26); bytes.extend(encoders::u32(table)); } // Memory instructions. Instruction::I32Load(m) => { bytes.push(0x28); m.encode(bytes); } Instruction::I64Load(m) => { bytes.push(0x29); m.encode(bytes); } Instruction::F32Load(m) => { bytes.push(0x2A); m.encode(bytes); } Instruction::F64Load(m) => { bytes.push(0x2B); m.encode(bytes); } Instruction::I32Load8_S(m) => { bytes.push(0x2C); m.encode(bytes); } Instruction::I32Load8_U(m) => { bytes.push(0x2D); m.encode(bytes); } Instruction::I32Load16_S(m) => { bytes.push(0x2E); m.encode(bytes); } Instruction::I32Load16_U(m) => { bytes.push(0x2F); m.encode(bytes); } Instruction::I64Load8_S(m) => { bytes.push(0x30); m.encode(bytes); } Instruction::I64Load8_U(m) => { bytes.push(0x31); m.encode(bytes); } Instruction::I64Load16_S(m) => { bytes.push(0x32); m.encode(bytes); } Instruction::I64Load16_U(m) => { bytes.push(0x33); m.encode(bytes); } Instruction::I64Load32_S(m) => { bytes.push(0x34); m.encode(bytes); } Instruction::I64Load32_U(m) => { bytes.push(0x35); m.encode(bytes); } Instruction::I32Store(m) => { bytes.push(0x36); m.encode(bytes); } Instruction::I64Store(m) => { bytes.push(0x37); m.encode(bytes); } Instruction::F32Store(m) => { bytes.push(0x38); m.encode(bytes); } Instruction::F64Store(m) => { bytes.push(0x39); m.encode(bytes); } Instruction::I32Store8(m) => { bytes.push(0x3A); m.encode(bytes); } Instruction::I32Store16(m) => { bytes.push(0x3B); m.encode(bytes); } Instruction::I64Store8(m) => { bytes.push(0x3C); m.encode(bytes); } Instruction::I64Store16(m) => { bytes.push(0x3D); m.encode(bytes); } Instruction::I64Store32(m) => { bytes.push(0x3E); m.encode(bytes); } Instruction::MemorySize(i) => { bytes.push(0x3F); bytes.extend(encoders::u32(i)); } Instruction::MemoryGrow(i) => { bytes.push(0x40); bytes.extend(encoders::u32(i)); } Instruction::MemoryInit { mem, data } => { bytes.push(0xfc); bytes.extend(encoders::u32(8)); bytes.extend(encoders::u32(data)); bytes.extend(encoders::u32(mem)); } Instruction::DataDrop(data) => { bytes.push(0xfc); bytes.extend(encoders::u32(9)); bytes.extend(encoders::u32(data)); } Instruction::MemoryCopy { src, dst } => { bytes.push(0xfc); bytes.extend(encoders::u32(10)); bytes.extend(encoders::u32(dst)); bytes.extend(encoders::u32(src)); } Instruction::MemoryFill(mem) => { bytes.push(0xfc); bytes.extend(encoders::u32(11)); bytes.extend(encoders::u32(mem)); } // Numeric instructions. Instruction::I32Const(x) => { bytes.push(0x41); bytes.extend(encoders::s32(x)); } Instruction::I64Const(x) => { bytes.push(0x42); bytes.extend(encoders::s64(x)); } Instruction::F32Const(x) => { bytes.push(0x43); let x = x.to_bits(); bytes.extend(x.to_le_bytes().iter().copied()); } Instruction::F64Const(x) => { bytes.push(0x44); let x = x.to_bits(); bytes.extend(x.to_le_bytes().iter().copied()); } Instruction::I32Eqz => bytes.push(0x45), Instruction::I32Eq => bytes.push(0x46), Instruction::I32Neq => bytes.push(0x47), Instruction::I32LtS => bytes.push(0x48), Instruction::I32LtU => bytes.push(0x49), Instruction::I32GtS => bytes.push(0x4A), Instruction::I32GtU => bytes.push(0x4B), Instruction::I32LeS => bytes.push(0x4C), Instruction::I32LeU => bytes.push(0x4D), Instruction::I32GeS => bytes.push(0x4E), Instruction::I32GeU => bytes.push(0x4F), Instruction::I64Eqz => bytes.push(0x50), Instruction::I64Eq => bytes.push(0x51), Instruction::I64Neq => bytes.push(0x52), Instruction::I64LtS => bytes.push(0x53), Instruction::I64LtU => bytes.push(0x54), Instruction::I64GtS => bytes.push(0x55), Instruction::I64GtU => bytes.push(0x56), Instruction::I64LeS => bytes.push(0x57), Instruction::I64LeU => bytes.push(0x58), Instruction::I64GeS => bytes.push(0x59), Instruction::I64GeU => bytes.push(0x5A), Instruction::F32Eq => bytes.push(0x5B), Instruction::F32Neq => bytes.push(0x5C), Instruction::F32Lt => bytes.push(0x5D), Instruction::F32Gt => bytes.push(0x5E), Instruction::F32Le => bytes.push(0x5F), Instruction::F32Ge => bytes.push(0x60), Instruction::F64Eq => bytes.push(0x61), Instruction::F64Neq => bytes.push(0x62), Instruction::F64Lt => bytes.push(0x63), Instruction::F64Gt => bytes.push(0x64), Instruction::F64Le => bytes.push(0x65), Instruction::F64Ge => bytes.push(0x66), Instruction::I32Clz => bytes.push(0x67), Instruction::I32Ctz => bytes.push(0x68), Instruction::I32Popcnt => bytes.push(0x69), Instruction::I32Add => bytes.push(0x6A), Instruction::I32Sub => bytes.push(0x6B), Instruction::I32Mul => bytes.push(0x6C), Instruction::I32DivS => bytes.push(0x6D), Instruction::I32DivU => bytes.push(0x6E), Instruction::I32RemS => bytes.push(0x6F), Instruction::I32RemU => bytes.push(0x70), Instruction::I32And => bytes.push(0x71), Instruction::I32Or => bytes.push(0x72), Instruction::I32Xor => bytes.push(0x73), Instruction::I32Shl => bytes.push(0x74), Instruction::I32ShrS => bytes.push(0x75), Instruction::I32ShrU => bytes.push(0x76), Instruction::I32Rotl => bytes.push(0x77), Instruction::I32Rotr => bytes.push(0x78), Instruction::I64Clz => bytes.push(0x79), Instruction::I64Ctz => bytes.push(0x7A), Instruction::I64Popcnt => bytes.push(0x7B), Instruction::I64Add => bytes.push(0x7C), Instruction::I64Sub => bytes.push(0x7D), Instruction::I64Mul => bytes.push(0x7E), Instruction::I64DivS => bytes.push(0x7F), Instruction::I64DivU => bytes.push(0x80), Instruction::I64RemS => bytes.push(0x81), Instruction::I64RemU => bytes.push(0x82), Instruction::I64And => bytes.push(0x83), Instruction::I64Or => bytes.push(0x84), Instruction::I64Xor => bytes.push(0x85), Instruction::I64Shl => bytes.push(0x86), Instruction::I64ShrS => bytes.push(0x87), Instruction::I64ShrU => bytes.push(0x88), Instruction::I64Rotl => bytes.push(0x89), Instruction::I64Rotr => bytes.push(0x8A), Instruction::F32Abs => bytes.push(0x8B), Instruction::F32Neg => bytes.push(0x8C), Instruction::F32Ceil => bytes.push(0x8D), Instruction::F32Floor => bytes.push(0x8E), Instruction::F32Trunc => bytes.push(0x8F), Instruction::F32Nearest => bytes.push(0x90), Instruction::F32Sqrt => bytes.push(0x91), Instruction::F32Add => bytes.push(0x92), Instruction::F32Sub => bytes.push(0x93), Instruction::F32Mul => bytes.push(0x94), Instruction::F32Div => bytes.push(0x95), Instruction::F32Min => bytes.push(0x96), Instruction::F32Max => bytes.push(0x97), Instruction::F32Copysign => bytes.push(0x98), Instruction::F64Abs => bytes.push(0x99), Instruction::F64Neg => bytes.push(0x9A), Instruction::F64Ceil => bytes.push(0x9B), Instruction::F64Floor => bytes.push(0x9C), Instruction::F64Trunc => bytes.push(0x9D), Instruction::F64Nearest => bytes.push(0x9E), Instruction::F64Sqrt => bytes.push(0x9F), Instruction::F64Add => bytes.push(0xA0), Instruction::F64Sub => bytes.push(0xA1), Instruction::F64Mul => bytes.push(0xA2), Instruction::F64Div => bytes.push(0xA3), Instruction::F64Min => bytes.push(0xA4), Instruction::F64Max => bytes.push(0xA5), Instruction::F64Copysign => bytes.push(0xA6), Instruction::I32WrapI64 => bytes.push(0xA7), Instruction::I32TruncF32S => bytes.push(0xA8), Instruction::I32TruncF32U => bytes.push(0xA9), Instruction::I32TruncF64S => bytes.push(0xAA), Instruction::I32TruncF64U => bytes.push(0xAB), Instruction::I64ExtendI32S => bytes.push(0xAC), Instruction::I64ExtendI32U => bytes.push(0xAD), Instruction::I64TruncF32S => bytes.push(0xAE), Instruction::I64TruncF32U => bytes.push(0xAF), Instruction::I64TruncF64S => bytes.push(0xB0), Instruction::I64TruncF64U => bytes.push(0xB1), Instruction::F32ConvertI32S => bytes.push(0xB2), Instruction::F32ConvertI32U => bytes.push(0xB3), Instruction::F32ConvertI64S => bytes.push(0xB4), Instruction::F32ConvertI64U => bytes.push(0xB5), Instruction::F32DemoteF64 => bytes.push(0xB6), Instruction::F64ConvertI32S => bytes.push(0xB7), Instruction::F64ConvertI32U => bytes.push(0xB8), Instruction::F64ConvertI64S => bytes.push(0xB9), Instruction::F64ConvertI64U => bytes.push(0xBA), Instruction::F64PromoteF32 => bytes.push(0xBB), Instruction::I32ReinterpretF32 => bytes.push(0xBC), Instruction::I64ReinterpretF64 => bytes.push(0xBD), Instruction::F32ReinterpretI32 => bytes.push(0xBE), Instruction::F64ReinterpretI64 => bytes.push(0xBF), Instruction::I32Extend8S => bytes.push(0xC0), Instruction::I32Extend16S => bytes.push(0xC1), Instruction::I64Extend8S => bytes.push(0xC2), Instruction::I64Extend16S => bytes.push(0xC3), Instruction::I64Extend32S => bytes.push(0xC4), Instruction::I32TruncSatF32S => { bytes.push(0xFC); bytes.extend(encoders::u32(0)); } Instruction::I32TruncSatF32U => { bytes.push(0xFC); bytes.extend(encoders::u32(1)); } Instruction::I32TruncSatF64S => { bytes.push(0xFC); bytes.extend(encoders::u32(2)); } Instruction::I32TruncSatF64U => { bytes.push(0xFC); bytes.extend(encoders::u32(3)); } Instruction::I64TruncSatF32S => { bytes.push(0xFC); bytes.extend(encoders::u32(4)); } Instruction::I64TruncSatF32U => { bytes.push(0xFC); bytes.extend(encoders::u32(5)); } Instruction::I64TruncSatF64S => { bytes.push(0xFC); bytes.extend(encoders::u32(6)); } Instruction::I64TruncSatF64U => { bytes.push(0xFC); bytes.extend(encoders::u32(7)); } // Reference types instructions. Instruction::RefNull(ty) => { bytes.push(0xd0); bytes.push(ty.into()); } Instruction::RefIsNull => bytes.push(0xd1), Instruction::RefFunc(f) => { bytes.push(0xd2); bytes.extend(encoders::u32(f)); } // Bulk memory instructions. Instruction::TableInit { segment, table } => { bytes.push(0xfc); bytes.extend(encoders::u32(0x0c)); bytes.extend(encoders::u32(segment)); bytes.extend(encoders::u32(table)); } Instruction::ElemDrop { segment } => { bytes.push(0xfc); bytes.extend(encoders::u32(0x0d)); bytes.extend(encoders::u32(segment)); } Instruction::TableCopy { src, dst } => { bytes.push(0xfc); bytes.extend(encoders::u32(0x0e)); bytes.extend(encoders::u32(dst)); bytes.extend(encoders::u32(src)); } Instruction::TableGrow { table } => { bytes.push(0xfc); bytes.extend(encoders::u32(0x0f)); bytes.extend(encoders::u32(table)); } Instruction::TableSize { table } => { bytes.push(0xfc); bytes.extend(encoders::u32(0x10)); bytes.extend(encoders::u32(table)); } Instruction::TableFill { table } => { bytes.push(0xfc); bytes.extend(encoders::u32(0x11)); bytes.extend(encoders::u32(table)); } // SIMD instructions. Instruction::V128Const(x) => { bytes.push(0xFD); bytes.extend(encoders::u32(12)); bytes.extend(x.to_le_bytes().iter().copied()); } } } }
true
e590f9cc3bc61658b15ea7fcfedc93c7cce091ad
Rust
StackCrash/kryptos
/src/common/mod.rs
UTF-8
748
3.65625
4
[ "MIT" ]
permissive
pub const ALPHABET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; pub fn binary_to_char(bin: &str) -> Result<char, String> { let binary = bin.as_bytes().iter().map(|b| b - 48).collect::<Vec<u8>>(); for bit in &binary { if *bit > 1 { return Err(String::from("Must be a valid binary number")); } } Ok((binary.iter().fold(0, |x, &b| x * 2 + b as u8) + 65) as char) } #[cfg(test)] mod tests { use super::binary_to_char; #[test] fn valid_binary() { assert!(binary_to_char("010").is_ok()); } #[test] fn invalid_binary() { assert!(binary_to_char("2010").is_err()); } #[test] fn number_to_char() { assert_eq!('C', binary_to_char("010").unwrap()); } }
true
e95dd4fc71955bf79eb1ebf030173d27eb981356
Rust
yuan-yuan-jia/Algorithms
/src/problems/backtracking/nqueens.rs
UTF-8
4,430
3.765625
4
[ "MIT" ]
permissive
//! The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. //! //! Given an integer n, return all distinct solutions to the n-queens puzzle. //! //! Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively. //! //! # See also //! //! - [Leetcode](https://leetcode.com/problems/n-queens/) use std::collections::HashSet; pub fn solve_n_queens(n: i32) -> Vec<Vec<String>> { Board::new(n as usize).solve() } struct Board { matrix: Vec<Vec<char>>, n: usize, solutions: HashSet<Vec<String>>, } impl Board { pub fn new(n: usize) -> Self { Self { matrix: vec![vec!['.'; n]; n], n, solutions: HashSet::new(), } } pub fn solve(mut self) -> Vec<Vec<String>> { self._solve(0, 0); self.solutions.into_iter().collect() } fn _solve(&mut self, i: usize, count: usize) { if count == self.n { self.add_solution(); } else if i == self.n { } else { for col in 0..self.n { if self.safe(i, col) { self.matrix[i][col] = 'Q'; self._solve(i + 1, count + 1); self.matrix[i][col] = '.'; } } } } fn add_solution(&mut self) { self.solutions.insert( self.matrix .iter() .map(|x| x.iter().copied().collect()) .collect(), ); } fn safe(&self, i: usize, j: usize) -> bool { for j_ in 0..self.n { if self.matrix[i][j_] == 'Q' { return false; } } for i_ in 0..self.n { if self.matrix[i_][j] == 'Q' { return false; } } let (mut i_, mut j_) = (i + 1, j + 1); while i_ > 0 && j_ > 0 { i_ -= 1; j_ -= 1; if self.matrix[i_][j_] == 'Q' { return false; } } let (mut i_, mut j_) = (i, j + 1); while i_ < self.n && j_ > 0 { j_ -= 1; if self.matrix[i_][j_] == 'Q' { return false; } i_ += 1; } let (mut i_, mut j_) = (i, j); while i_ < self.n && j_ < self.n { if self.matrix[i_][j_] == 'Q' { return false; } i_ += 1; j_ += 1; } let (mut i_, mut j_) = (i + 1, j); while i_ > 0 && j_ < self.n { i_ -= 1; if self.matrix[i_][j_] == 'Q' { return false; } j_ += 1; } true } } #[cfg(test)] mod tests { use super::*; #[test] fn test_n_queens() { let n1 = solve_n_queens(1); assert_eq!(n1, vec![vec!["Q".to_string()]]); let n2 = solve_n_queens(2); assert!(n2.is_empty()); let n3 = solve_n_queens(3); assert!(n3.is_empty()); let mut n4 = solve_n_queens(4); n4.sort(); assert_eq!( n4, make_solution(&[ &["..Q.", "Q...", "...Q", ".Q.."], &[".Q..", "...Q", "Q...", "..Q."], ]) ); let mut n5 = solve_n_queens(5); let mut n5_expected = make_solution(&[ &["..Q..", "....Q", ".Q...", "...Q.", "Q...."], &["...Q.", "Q....", "..Q..", "....Q", ".Q..."], &["....Q", ".Q...", "...Q.", "Q....", "..Q.."], &["Q....", "...Q.", ".Q...", "....Q", "..Q.."], &[".Q...", "....Q", "..Q..", "Q....", "...Q."], &["....Q", "..Q..", "Q....", "...Q.", ".Q..."], &[".Q...", "...Q.", "Q....", "..Q..", "....Q"], &["..Q..", "Q....", "...Q.", ".Q...", "....Q"], &["...Q.", ".Q...", "....Q", "..Q..", "Q...."], &["Q....", "..Q..", "....Q", ".Q...", "...Q."], ]); n5.sort(); n5_expected.sort(); assert_eq!(n5, n5_expected); let n8 = solve_n_queens(8); assert_eq!(n8.len(), 92); } fn make_solution(sol: &[&[&'static str]]) -> Vec<Vec<String>> { sol.iter() .map(|&x| x.iter().map(|&s| s.to_owned()).collect()) .collect() } }
true
efd3d047c44fa30c6f88b9de8f3cc4410a97acaf
Rust
arbanhossain/5dchess-tools
/lib/parse.rs
UTF-8
2,769
3.015625
3
[ "MIT" ]
permissive
use super::game; use serde::Deserialize; #[derive(Debug, Deserialize)] struct GameRaw { timelines: Vec<TimelineRaw>, width: u8, height: u8, active_player: bool, } /// Represents an in-game timeline #[derive(Debug, Deserialize)] struct TimelineRaw { index: f32, states: Vec<Vec<usize>>, width: u8, height: u8, begins_at: isize, emerges_from: Option<f32>, } pub fn parse(raw: &str) -> Option<game::Game> { let game_raw: GameRaw = serde_json::from_str(raw).ok()?; let even_initial_timelines = game_raw .timelines .iter() .any(|tl| tl.index == -0.5 || tl.index == 0.5); let min_timeline = game_raw.timelines .iter() .map(|tl| tl.index) .min_by_key(|x| (*x) as isize)?; let max_timeline = game_raw.timelines .iter() .map(|tl| tl.index) .max_by_key(|x| (*x) as isize)?; let timeline_width = ((-min_timeline).min(max_timeline) + 1.0).round(); let active_timelines = game_raw.timelines .iter() .filter(|tl| tl.index.abs() <= timeline_width); let present = active_timelines .map(|tl| tl.begins_at + (tl.states.len() as isize) - 1) .min()?; let mut res = game::Game::new(game_raw.width, game_raw.height); res.info.present = present; res.info.min_timeline = de_l(min_timeline, even_initial_timelines); res.info.max_timeline = de_l(max_timeline, even_initial_timelines); res.info.active_player = game_raw.active_player; res.info.even_initial_timelines = even_initial_timelines; for tl in game_raw.timelines.into_iter() { res.timelines.insert( de_l(tl.index, even_initial_timelines), de_timeline(tl, even_initial_timelines), ); } Some(res) } fn de_board(raw: Vec<usize>, t: isize, l: i32, width: u8, height: u8) -> game::Board { let mut res = game::Board::new(t, l, width, height); res.pieces = raw .into_iter() .map(|x| game::Piece::from(x)) .collect(); res } fn de_l(raw: f32, even: bool) -> i32 { if even && raw < 0.0 { (raw.ceil() - 1.0) as i32 } else { raw.floor() as i32 } } fn de_timeline(raw: TimelineRaw, even: bool) -> game::Timeline { let mut res = game::Timeline::new( de_l(raw.index, even), raw.width, raw.height, raw.begins_at, raw.emerges_from.map(|x| de_l(x, even)), ); let index = de_l(raw.index, even); let begins_at = raw.begins_at; let width = raw.width; let height = raw.height; res.states = raw .states .into_iter() .enumerate() .map(|(i, b)| de_board(b, begins_at + i as isize, index, width, height)) .collect(); res }
true
df05578e32242c25d9e7d2077794fc3a2da03bce
Rust
0000marcell/LearnRust
/RH/aoc1/src/main.rs
UTF-8
1,188
3.90625
4
[]
no_license
fn main() { let instruction: Vec<String> = std::env::args().collect(); let instruction: &String = &instruction[1]; println!("{}", santa(instruction)); } fn santa(instruction: &String) -> i32 { // if '(' up else if ')' down let mut floor: i32 = 0; for paren in instruction.chars() { println!("{}", paren); match paren { '(' => floor += 1, ')' => floor -= 1, _ => panic!(), } } floor } // #[cfg(test)] mod test { use super::santa; #[test] fn example() { assert!(santa(&"(())".to_string()) == 0); assert!(santa(&"()()".to_string()) == 0); assert!(santa(&"(((".to_string()) == 3); assert!(santa(&"(()(()(".to_string()) == 3); assert!(santa(&"))(((((".to_string()) == 3); assert!(santa(&"())".to_string()) == -1); assert!(santa(&"))(".to_string()) == -1); assert!(santa(&")))".to_string()) == -3); assert!(santa(&")())())".to_string()) == -3); } #[test] fn a() { assert!(santa(&"".to_string()) == 0); } #[test] #[should_panic] fn b() { santa(&"{}".to_string()); } }
true
6a343d704b724f4e3b3d2632e8240d84080c4f8f
Rust
Godofh3ell/el_monitorro-1
/src/db.rs
UTF-8
2,024
2.53125
3
[ "MIT" ]
permissive
use chrono::prelude::*; use chrono::{DateTime, Utc}; use diesel::pg::PgConnection; use diesel::r2d2::{ConnectionManager, Pool, PooledConnection}; use dotenv::dotenv; use once_cell::sync::OnceCell; use std::env; use tokio::sync::Semaphore; use tokio::sync::SemaphorePermit; pub mod feed_items; pub mod feeds; pub mod telegram; static POOL: OnceCell<Pool<ConnectionManager<PgConnection>>> = OnceCell::new(); static SEMAPHORE: OnceCell<Semaphore> = OnceCell::new(); static POOL_NUMBER: OnceCell<usize> = OnceCell::new(); pub struct SemaphoredDbConnection<'a> { _semaphore_permit: SemaphorePermit<'a>, pub connection: PooledConnection<ConnectionManager<PgConnection>>, } pub async fn get_semaphored_connection<'a>() -> SemaphoredDbConnection<'a> { let _semaphore_permit = semaphore().acquire().await.unwrap(); let connection = establish_connection(); SemaphoredDbConnection { _semaphore_permit, connection, } } pub fn current_time() -> DateTime<Utc> { Utc::now().round_subsecs(0) } pub fn establish_connection() -> PooledConnection<ConnectionManager<PgConnection>> { pool().get().unwrap() } pub fn semaphore() -> &'static Semaphore { SEMAPHORE.get_or_init(|| Semaphore::new(*pool_connection_number())) } pub fn pool_connection_number() -> &'static usize { POOL_NUMBER.get_or_init(|| { dotenv().ok(); let database_pool_size_str = env::var("DATABASE_POOL_SIZE").unwrap_or_else(|_| "10".to_string()); let database_pool_size: usize = database_pool_size_str.parse().unwrap(); database_pool_size }) } fn pool() -> &'static Pool<ConnectionManager<PgConnection>> { POOL.get_or_init(|| { dotenv().ok(); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); let manager = ConnectionManager::<PgConnection>::new(database_url); Pool::builder() .max_size(*pool_connection_number() as u32) .build(manager) .unwrap() }) }
true
916510d952a46ad8df39dc2a78aee51d1daedaac
Rust
potatosalad/leetcode
/src/n1122_relative_sort_array.rs
UTF-8
1,815
3.625
4
[ "Apache-2.0" ]
permissive
/** * [1122] Relative Sort Array * * Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. * Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order. * * Example 1: * Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] * Output: [2,2,2,1,4,3,3,9,6,7,19] * * Constraints: * * arr1.length, arr2.length <= 1000 * 0 <= arr1[i], arr2[i] <= 1000 * Each arr2[i] is distinct. * Each arr2[i] is in arr1. * */ pub struct Solution {} // submission codes start here use std::collections::HashMap; use std::collections::HashSet; impl Solution { pub fn relative_sort_array(arr1: Vec<i32>, arr2: Vec<i32>) -> Vec<i32> { let set: HashSet<i32> = arr2.iter().copied().collect(); let mut histogram: HashMap<i32, usize> = HashMap::new(); let mut tail: Vec<i32> = Vec::new(); for n in arr1 { if set.contains(&n) { *(histogram.entry(n).or_insert(0)) += 1; } else { tail.push(n); } } let mut head: Vec<i32> = Vec::new(); for n in arr2 { let x: usize = histogram.get(&n).copied().unwrap(); head.append(&mut vec![n; x]); } tail.sort_unstable(); head.append(&mut tail); head } } // submission codes end #[cfg(test)] mod tests { use super::*; #[test] fn test_1122() { assert_eq!( vec![2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19], Solution::relative_sort_array( vec![2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19], vec![2, 1, 4, 3, 9, 6] ) ); } }
true
22e8a01c9a2474f92601c744aaa918083d913c1b
Rust
TerminalStudio/nativeshell
/nativeshell/src/shell/platform/win32/window_base.rs
UTF-8
18,540
2.53125
3
[ "MIT", "Apache-2.0" ]
permissive
use std::{ cell::RefCell, rc::{Rc, Weak}, }; use crate::{ shell::{ api_model::{ WindowFrame, WindowGeometry, WindowGeometryFlags, WindowGeometryRequest, WindowStyle, }, IPoint, IRect, ISize, Point, Rect, Size, }, util::OkLog, }; use super::{ all_bindings::*, display::Displays, error::PlatformResult, flutter_sys::{FlutterDesktopGetDpiForHWND, FlutterDesktopGetDpiForMonitor}, util::{clamp, BoolResultExt, HRESULTExt, GET_X_LPARAM, GET_Y_LPARAM}, }; pub struct WindowBaseState { hwnd: HWND, min_frame_size: RefCell<Size>, max_frame_size: RefCell<Size>, min_content_size: RefCell<Size>, max_content_size: RefCell<Size>, delegate: Weak<dyn WindowDelegate>, style: RefCell<WindowStyle>, } const LARGE_SIZE: f64 = 64.0 * 1024.0; impl WindowBaseState { pub fn new(hwnd: HWND, delegate: Weak<dyn WindowDelegate>) -> Self { Self { hwnd, delegate, min_frame_size: RefCell::new(Size::wh(0.0, 0.0)), max_frame_size: RefCell::new(Size::wh(LARGE_SIZE, LARGE_SIZE)), min_content_size: RefCell::new(Size::wh(0.0, 0.0)), max_content_size: RefCell::new(Size::wh(LARGE_SIZE, LARGE_SIZE)), style: Default::default(), } } pub fn hide(&self) -> PlatformResult<()> { unsafe { ShowWindow(self.hwnd, SW_HIDE).as_platform_result() } } pub fn show<F>(&self, callback: F) -> PlatformResult<()> where F: FnOnce() + 'static, { unsafe { ShowWindow(self.hwnd, SW_SHOW); // false is not an error } callback(); Ok(()) } pub fn set_geometry( &self, geometry: WindowGeometryRequest, ) -> PlatformResult<WindowGeometryFlags> { let geometry = geometry.filtered_by_preference(); let mut res = WindowGeometryFlags { ..Default::default() }; if geometry.content_origin.is_some() || geometry.content_size.is_some() || geometry.frame_origin.is_some() || geometry.frame_size.is_some() { self.set_bounds_geometry(&geometry, &mut res)?; // There's no set_content_rect in winapi, so this is best effort implementation // that tries to deduce future content rect from current content rect and frame rect // in case it's wrong (i.e. display with different DPI or frame size change after reposition) // it will retry once again if res.content_origin || res.content_size { let content_rect = self.content_rect_for_frame_rect(&self.get_frame_rect()?)?; if (res.content_origin && content_rect.origin() != *geometry.content_origin.as_ref().unwrap()) || (res.content_size && content_rect.size() != *geometry.content_size.as_ref().unwrap()) { // retry self.set_bounds_geometry(&geometry, &mut res)?; } } } if let Some(size) = geometry.min_frame_size { self.min_frame_size.replace(size); res.min_frame_size = true; } if let Some(size) = geometry.max_frame_size { self.max_frame_size.replace(size); res.max_frame_size = true; } if let Some(size) = geometry.min_content_size { self.min_content_size.replace(size); res.min_content_size = true; } if let Some(size) = geometry.max_content_size { self.max_content_size.replace(size); res.max_content_size = true; } Ok(res) } fn set_bounds_geometry( &self, geometry: &WindowGeometry, flags: &mut WindowGeometryFlags, ) -> PlatformResult<()> { let current_frame_rect = self.get_frame_rect()?; let current_content_rect = self.content_rect_for_frame_rect(&current_frame_rect)?; let content_offset = current_content_rect.to_local(&current_frame_rect.origin()); let content_size_delta = current_frame_rect.size() - current_content_rect.size(); let mut origin: Option<Point> = None; let mut size: Option<Size> = None; if let Some(frame_origin) = &geometry.frame_origin { origin.replace(frame_origin.clone()); flags.frame_origin = true; } if let Some(frame_size) = &geometry.frame_size { size.replace(frame_size.clone()); flags.frame_size = true; } if let Some(content_origin) = &geometry.content_origin { origin.replace(content_origin.translated(&content_offset)); flags.content_origin = true; } if let Some(content_size) = &geometry.content_size { size.replace(content_size + &content_size_delta); flags.content_size = true; } let physical = IRect::origin_size( &self.to_physical(origin.as_ref().unwrap_or(&Point::xy(0.0, 0.0))), &size .as_ref() .unwrap_or(&Size::wh(0.0, 0.0)) .scaled(self.get_scaling_factor()) .into(), ); let mut flags = SWP_NOZORDER | SWP_NOACTIVATE; if origin.is_none() { flags |= SWP_NOMOVE; } if size.is_none() { flags |= SWP_NOSIZE; } unsafe { SetWindowPos( self.hwnd, HWND(0), physical.x, physical.y, physical.width, physical.height, flags, ) .as_platform_result() } } pub fn get_geometry(&self) -> PlatformResult<WindowGeometry> { let frame_rect = self.get_frame_rect()?; let content_rect = self.content_rect_for_frame_rect(&frame_rect)?; Ok(WindowGeometry { frame_origin: Some(frame_rect.origin()), frame_size: Some(frame_rect.size()), content_origin: Some(content_rect.origin()), content_size: Some(content_rect.size()), min_frame_size: Some(self.min_frame_size.borrow().clone()), max_frame_size: Some(self.max_frame_size.borrow().clone()), min_content_size: Some(self.min_content_size.borrow().clone()), max_content_size: Some(self.max_content_size.borrow().clone()), }) } pub fn supported_geometry(&self) -> PlatformResult<WindowGeometryFlags> { Ok(WindowGeometryFlags { frame_origin: true, frame_size: true, content_origin: true, content_size: true, min_frame_size: true, max_frame_size: true, min_content_size: true, max_content_size: true, }) } fn get_frame_rect(&self) -> PlatformResult<Rect> { let mut rect: RECT = Default::default(); unsafe { GetWindowRect(self.hwnd, &mut rect as *mut _).as_platform_result()?; } let size: Size = ISize::wh(rect.right - rect.left, rect.bottom - rect.top).into(); Ok(Rect::origin_size( &self.to_logical(&IPoint::xy(rect.left, rect.top)), &size.scaled(1.0 / self.get_scaling_factor()), )) } fn content_rect_for_frame_rect(&self, frame_rect: &Rect) -> PlatformResult<Rect> { let content_rect = IRect::origin_size( &self.to_physical(&frame_rect.top_left()), &frame_rect.size().scaled(self.get_scaling_factor()).into(), ); let rect = RECT { left: content_rect.x, top: content_rect.y, right: content_rect.x2(), bottom: content_rect.y2(), }; unsafe { SendMessageW( self.hwnd, WM_NCCALCSIZE as u32, WPARAM(0), LPARAM(&rect as *const _ as isize), ); } let size: Size = ISize::wh(rect.right - rect.left, rect.bottom - rect.top).into(); Ok(Rect::origin_size( &self.to_logical(&IPoint::xy(rect.left, rect.top)), &size.scaled(1.0 / self.get_scaling_factor()), )) } fn adjust_window_position(&self, position: &mut WINDOWPOS) -> PlatformResult<()> { let scale = self.get_scaling_factor(); let frame_rect = self.get_frame_rect()?; let content_rect = self.content_rect_for_frame_rect(&frame_rect)?; let size_delta = frame_rect.size() - content_rect.size(); let min_content = &*self.min_content_size.borrow() + &size_delta; let min_content: ISize = min_content.scaled(scale).into(); let min_frame = self.min_frame_size.borrow(); let min_frame: ISize = min_frame.scaled(scale).into(); let min_size = ISize::wh( std::cmp::max(min_content.width, min_frame.width), std::cmp::max(min_content.height, min_frame.height), ); let max_content = &*self.max_content_size.borrow() + &size_delta; let max_content: ISize = max_content.scaled(scale).into(); let max_frame = self.max_frame_size.borrow(); let max_frame: ISize = max_frame.scaled(scale).into(); let max_size = ISize::wh( std::cmp::min(max_content.width, max_frame.width), std::cmp::min(max_content.height, max_frame.height), ); position.cx = clamp(position.cx, min_size.width, max_size.width); position.cy = clamp(position.cy, min_size.height, max_size.height); Ok(()) } pub fn close(&self) -> PlatformResult<()> { unsafe { DestroyWindow(self.hwnd).as_platform_result() } } pub fn local_to_global(&self, offset: &Point) -> IPoint { let scaled: IPoint = offset.scaled(self.get_scaling_factor()).into(); self.local_to_global_physical(&scaled) } pub fn local_to_global_physical(&self, offset: &IPoint) -> IPoint { let mut point = POINT { x: offset.x, y: offset.y, }; unsafe { ClientToScreen(self.hwnd, &mut point as *mut _); } IPoint::xy(point.x, point.y) } pub fn global_to_local(&self, offset: &IPoint) -> Point { let local: Point = self.global_to_local_physical(&offset).into(); local.scaled(1.0 / self.get_scaling_factor()) } pub fn global_to_local_physical(&self, offset: &IPoint) -> IPoint { let mut point = POINT { x: offset.x, y: offset.y, }; unsafe { ScreenToClient(self.hwnd, &mut point as *mut _); } IPoint::xy(point.x, point.y) } fn to_physical(&self, offset: &Point) -> IPoint { Displays::get_displays() .convert_logical_to_physical(offset) .unwrap_or_else(|| offset.clone().into()) } fn to_logical(&self, offset: &IPoint) -> Point { Displays::get_displays() .convert_physical_to_logical(offset) .unwrap_or_else(|| offset.clone().into()) } pub fn is_rtl(&self) -> bool { let style = WINDOW_EX_STYLE(unsafe { GetWindowLongW(self.hwnd, GWL_EXSTYLE) } as u32); style & WS_EX_LAYOUTRTL == WS_EX_LAYOUTRTL } pub fn get_scaling_factor(&self) -> f64 { unsafe { FlutterDesktopGetDpiForHWND(self.hwnd) as f64 / 96.0 } } #[allow(unused)] fn get_scaling_factor_for_monitor(&self, monitor: isize) -> f64 { unsafe { FlutterDesktopGetDpiForMonitor(monitor) as f64 / 96.0 } } fn delegate(&self) -> Rc<dyn WindowDelegate> { // delegate owns us so unwrap is safe here self.delegate.upgrade().unwrap() } unsafe fn set_close_enabled(&self, enabled: bool) { let menu = GetSystemMenu(self.hwnd, false); if enabled { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem( menu, SC_CLOSE as u32, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED, ); } } pub fn update_dwm_frame(&self) -> PlatformResult<()> { let margin = match self.style.borrow().frame { WindowFrame::Regular => 0, // already has shadow WindowFrame::NoTitle => 1, // neede for window shadow WindowFrame::NoFrame => 0, // neede for transparency }; let margins = MARGINS { cxLeftWidth: 0, cxRightWidth: 0, cyTopHeight: margin, cyBottomHeight: 0, }; unsafe { DwmExtendFrameIntoClientArea(self.hwnd, &margins as *const _).as_platform_result() } } pub fn set_title(&self, title: String) -> PlatformResult<()> { unsafe { SetWindowTextW(self.hwnd, title); } Ok(()) } pub fn set_style(&self, style: WindowStyle) -> PlatformResult<()> { *self.style.borrow_mut() = style.clone(); unsafe { let mut s = WINDOW_STYLE(GetWindowLongW(self.hwnd, GWL_STYLE) as u32); s &= WINDOW_STYLE(!(WS_OVERLAPPEDWINDOW | WS_DLGFRAME).0); if style.frame == WindowFrame::Regular { s |= WS_CAPTION; if style.can_resize { s |= WS_THICKFRAME; } } if style.frame == WindowFrame::NoTitle { s |= WS_CAPTION; if style.can_resize { s |= WS_THICKFRAME; } else { s |= WS_BORDER; } } if style.frame == WindowFrame::NoFrame { s |= WS_POPUP } s |= WS_SYSMENU; self.set_close_enabled(style.can_close); if style.can_maximize && style.can_resize { s |= WS_MAXIMIZEBOX; } if style.can_minimize { s |= WS_MINIMIZEBOX; } SetWindowLongW(self.hwnd, GWL_STYLE, s.0 as i32); SetWindowPos( self.hwnd, HWND(0), 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER, ) .as_platform_result()?; self.update_dwm_frame()?; } Ok(()) } pub fn perform_window_drag(&self) -> PlatformResult<()> { unsafe { println!("Perform window drag!"); ReleaseCapture(); SendMessageW( self.hwnd, WM_NCLBUTTONDOWN as u32, WPARAM(HTCAPTION as usize), LPARAM(0), ); } Ok(()) } pub fn has_redirection_surface(&self) -> bool { let style = WINDOW_EX_STYLE(unsafe { GetWindowLongW(self.hwnd, GWL_EXSTYLE) } as u32); (style & WS_EX_NOREDIRECTIONBITMAP).0 == 0 } pub fn remove_border(&self) -> bool { self.style.borrow().frame == WindowFrame::NoTitle } fn do_hit_test(&self, x: i32, y: i32) -> u32 { let mut win_rect = RECT::default(); unsafe { GetWindowRect(self.hwnd, &mut win_rect as *mut _); } let border_width = (7.0 * self.get_scaling_factor()) as i32; if x < win_rect.left + border_width && y < win_rect.top + border_width { HTTOPLEFT } else if x > win_rect.right - border_width && y < win_rect.top + border_width { HTTOPRIGHT } else if y < win_rect.top + border_width { HTTOP } else if x < win_rect.left + border_width && y > win_rect.bottom - border_width { HTBOTTOMLEFT } else if x > win_rect.right - border_width && y > win_rect.bottom - border_width { HTBOTTOMRIGHT } else if y > win_rect.bottom - border_width { HTBOTTOM } else if x < win_rect.left + border_width { HTLEFT } else if x > win_rect.right - border_width { HTRIGHT } else { HTCLIENT } } pub fn handle_message( &self, _h_wnd: HWND, msg: u32, _w_param: WPARAM, l_param: LPARAM, ) -> Option<LRESULT> { match msg { WM_CLOSE => { self.delegate().should_close(); Some(LRESULT(0)) } WM_DESTROY => { self.delegate().will_close(); None } WM_DISPLAYCHANGE => { Displays::displays_changed(); self.delegate().displays_changed(); None } WM_WINDOWPOSCHANGING => { let position = unsafe { &mut *(l_param.0 as *mut WINDOWPOS) }; self.adjust_window_position(position).ok_log(); None } WM_DWMCOMPOSITIONCHANGED => { self.update_dwm_frame().ok_log(); None } WM_NCCALCSIZE => { if self.remove_border() { Some(LRESULT(1)) } else { None } } WM_NCHITTEST => { if self.remove_border() { let res = self.do_hit_test(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param)); Some(LRESULT(res as i32)) } else { None } } _ => None, } } pub fn handle_child_message( &self, _h_wnd: HWND, msg: u32, _w_param: WPARAM, l_param: LPARAM, ) -> Option<LRESULT> { match msg { WM_NCHITTEST => { if self.remove_border() { let res = self.do_hit_test(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param)); if res != HTCLIENT { Some(LRESULT(HTTRANSPARENT)) } else { Some(LRESULT(res as i32)) } } else { None } } _ => None, } } } pub trait WindowDelegate { fn should_close(&self); fn will_close(&self); fn displays_changed(&self); }
true
8e91db882281095b6715f97f1a64202981b013ce
Rust
DrewKestell/ForayRust
/src/game_timer.rs
UTF-8
3,022
2.625
3
[]
no_license
use winapi::um::profileapi::QueryPerformanceCounter; use winapi::shared::ntdef::LARGE_INTEGER; use std::mem::zeroed; pub struct GameTimer { seconds_per_count: f64, delta_time: f64, base_time: i64, paused_time: i64, stop_time: i64, previous_time: i64, current_time: i64, stopped: bool } impl GameTimer { pub fn new() -> GameTimer { unsafe { let mut counts_per_second: LARGE_INTEGER = zeroed(); QueryPerformanceCounter(&mut counts_per_second); let seconds_per_count = 1.0 / *counts_per_second.QuadPart() as f64; GameTimer { seconds_per_count: seconds_per_count, delta_time: -1.0, base_time: 0, paused_time: 0, stop_time: 0, previous_time: 0, current_time: 0, stopped: false } } } pub fn tick(&mut self) { if self.stopped { self.delta_time = 0.0; return; } unsafe { let mut current_time: LARGE_INTEGER = zeroed(); QueryPerformanceCounter(&mut current_time); self.current_time = *current_time.QuadPart(); } self.delta_time = (self.current_time - self.previous_time) as f64 * self.seconds_per_count; self.previous_time = self.current_time; if self.delta_time < 0.0 { self.delta_time = 0.0; } } pub fn reset(&mut self) { unsafe { let mut current_time: LARGE_INTEGER = zeroed(); QueryPerformanceCounter(&mut current_time); self.base_time = *current_time.QuadPart(); self.previous_time = *current_time.QuadPart(); self.stop_time = *current_time.QuadPart(); self.stopped = false; } } pub fn stop(&mut self) { if !self.stopped { unsafe { let mut current_time: LARGE_INTEGER = zeroed(); QueryPerformanceCounter(&mut current_time); self.stop_time = *current_time.QuadPart(); self.stopped = true; } } } pub fn start(&mut self) { if self.stopped { unsafe { let mut start_time: LARGE_INTEGER = zeroed(); QueryPerformanceCounter(&mut start_time); self.paused_time += *start_time.QuadPart() - self.stop_time; self.previous_time = *start_time.QuadPart(); self.stop_time = 0; self.stopped = false; } } } pub fn total_time(&self) -> f64 { if self.stopped { ((self.stop_time - self.paused_time) - self.base_time) as f64 * self.seconds_per_count } else { ((self.current_time - self.paused_time) - self.base_time) as f64 * self.seconds_per_count } } pub fn delta_time(&self) -> f64 { self.delta_time } }
true
c3337f1f1473accd16e0a194ec276ef69b78cc85
Rust
gloriousfutureio/hermitdb
/src/memory_log.rs
UTF-8
2,578
2.796875
3
[]
no_license
use std::collections::BTreeMap; use std::fmt::Debug; use crdts::{CmRDT, Actor}; use log::{TaggedOp, LogReplicable}; use error::Result; #[derive(Debug, Clone)] pub struct Log<A: Actor, C: Debug + CmRDT> { actor: A, logs: BTreeMap<A, (u64, Vec<C::Op>)> } #[derive(Debug, Clone)] pub struct Op<A: Actor, C: Debug + CmRDT> { actor: A, index: u64, op: C::Op } impl<A: Actor, C: Debug + CmRDT> TaggedOp<C> for Op<A, C> { type ID = (A, u64); fn id(&self) -> Self::ID { (self.actor.clone(), self.index) } fn op(&self) -> &C::Op { &self.op } } impl<A: Actor, C: Debug + CmRDT> LogReplicable<A, C> for Log<A, C> { type Op = Op<A, C>; fn next(&self) -> Result<Option<Self::Op>> { let largest_lag = self.logs.iter() .max_by_key(|(_, (index, log))| (log.len() as u64) - *index); if let Some((actor, (index, log))) = largest_lag { if *index >= log.len() as u64 { Ok(None) } else { Ok(Some(Op { actor: actor.clone(), index: *index, op: log[*index as usize].clone() })) } } else { Ok(None) } } fn ack(&mut self, op: &Self::Op) -> Result<()> { // We can ack ops that are not present in the log let (actor, index) = op.id(); let log = self.logs.entry(actor) .or_insert_with(|| (0, Vec::new())); log.0 = index + 1; Ok(()) } fn commit(&mut self, op: C::Op) -> Result<Self::Op> { let log = self.logs.entry(self.actor.clone()) .or_insert_with(|| (0, Vec::new())); log.1.push(op.clone()); Ok(Op { actor: self.actor.clone(), index: log.0, op: op }) } fn pull(&mut self, other: &Self) -> Result<()> { for (actor, (_, log)) in other.logs.iter() { let entry = self.logs.entry(actor.clone()) .or_insert_with(|| (0, vec![])); if log.len() > entry.1.len() { for i in (entry.1.len())..log.len() { entry.1.push(log[i as usize].clone()); } } } Ok(()) } fn push(&self, other: &mut Self) -> Result<()> { other.pull(self) } } impl<A: Actor, C: Debug + CmRDT> Log<A, C> { pub fn new(actor: A) -> Self { Log { actor: actor, logs: BTreeMap::new() } } }
true
3b6a8bd239de8e214574da7f3d0eb3faedfd1d68
Rust
AlberErre/rust-experiments
/fizz-buzz/src/main.rs
UTF-8
573
4.15625
4
[]
no_license
fn main() { println!("Hello, Fizz Buzz!"); const NUMBER: i32 = 35; let fizz_buzz_result = fizz_buzz(NUMBER); println!("Fizz Buzz for number {} is: {:?}", NUMBER, fizz_buzz_result); } fn fizz_buzz(number: i32) -> Vec<String> { //NOTE: we start at 1 to avoid handling another case with 0 let numbers = 1..=number; numbers .map(|n| match n { n if (n % 3 == 0 && n % 5 == 0) => String::from("FizzBuzz"), n if n % 3 == 0 => String::from("Fizz"), n if n % 5 == 0 => String::from("Buzz"), _ => n.to_string(), }) .collect() }
true
00813770f2c8333ff4b3a5282971ad36f1644f50
Rust
Dongitestil/PL_2_Rust
/server/src/main.rs
UTF-8
1,569
2.8125
3
[]
no_license
use std::thread; use std::net::{TcpListener, TcpStream, Shutdown}; use std::io::{Read, Write}; use std::str::from_utf8; mod protector; use protector::*; fn handle_client(mut stream: TcpStream) { let mut hash = [0 as u8; 5]; let mut key = [0 as u8; 10]; let mut mes = [0 as u8;50]; while match stream.read(&mut hash) { Ok(_) => { stream.read(&mut key); stream.read(&mut mes); let text1 = from_utf8(&hash).unwrap(); let text2 = from_utf8(&key).unwrap(); let new_key = next_session_key(&text1,&text2); let result = new_key.clone().into_bytes(); //отправка данных stream.write(&result).unwrap(); stream.write(&mes).unwrap(); true }, Err(_) => { println!("Ошибка при подключении к {}", stream.peer_addr().unwrap()); stream.shutdown(Shutdown::Both).unwrap(); false } } {} } fn main() { let listener = TcpListener::bind("0.0.0.0:3333").unwrap(); println!("Сервер запустился..."); for stream in listener.incoming() { match stream { Ok(stream) => { println!("Новое подключение: {}", stream.peer_addr().unwrap()); thread::spawn(move|| { handle_client(stream) }); } Err(e) => { println!("Ошибка: {}", e); } } } drop(listener); }
true
ce1070567ee74acc90f0f31ff337228e172fe016
Rust
evelynmitchell/stateright.github.io
/rs-src/getting-started/src/main.rs
UTF-8
3,202
2.53125
3
[]
no_license
/* ANCHOR: all */ use stateright::actor::{*, register::*}; use std::borrow::Cow; // COW == clone-on-write use std::net::{SocketAddrV4, Ipv4Addr}; // ANCHOR: actor type RequestId = u64; #[derive(Clone)] struct ServerActor; impl Actor for ServerActor { type Msg = RegisterMsg<RequestId, char, ()>; type State = char; fn on_start(&self, _id: Id, _o: &mut Out<Self>) -> Self::State { '?' // default value for the register } fn on_msg(&self, _id: Id, state: &mut Cow<Self::State>, src: Id, msg: Self::Msg, o: &mut Out<Self>) { match msg { RegisterMsg::Put(req_id, value) => { *state.to_mut() = value; o.send(src, RegisterMsg::PutOk(req_id)); } RegisterMsg::Get(req_id) => { o.send(src, RegisterMsg::GetOk(req_id, **state)); } _ => {} } } } // ANCHOR_END: actor #[cfg(test)] mod test { use super::*; use stateright::{*, semantics::*, semantics::register::*}; use ActorModelAction::Deliver; use RegisterMsg::{Get, GetOk, Put, PutOk}; // ANCHOR: test #[test] fn is_unfortunately_not_linearizable() { let checker = ActorModel::new( (), LinearizabilityTester::new(Register('?')) ) .actor(RegisterActor::Server(ServerActor)) .actor(RegisterActor::Client { put_count: 2, server_count: 1 }) .property(Expectation::Always, "linearizable", |_, state| { state.history.serialized_history().is_some() }) .property(Expectation::Sometimes, "get succeeds", |_, state| { state.network.iter().any(|e| matches!(e.msg, RegisterMsg::GetOk(_, _))) }) .property(Expectation::Sometimes, "put succeeds", |_, state| { state.network.iter().any(|e| matches!(e.msg, RegisterMsg::PutOk(_))) }) .record_msg_in(RegisterMsg::record_returns) .record_msg_out(RegisterMsg::record_invocations) .checker().spawn_dfs().join(); //checker.assert_properties(); // TRY IT: Uncomment this line, and the test will fail. checker.assert_discovery("linearizable", vec![ Deliver { src: Id::from(1), dst: Id::from(0), msg: Put(1, 'A') }, Deliver { src: Id::from(0), dst: Id::from(1), msg: PutOk(1) }, Deliver { src: Id::from(1), dst: Id::from(0), msg: Put(2, 'Z') }, Deliver { src: Id::from(0), dst: Id::from(1), msg: PutOk(2) }, Deliver { src: Id::from(1), dst: Id::from(0), msg: Put(1, 'A') }, Deliver { src: Id::from(1), dst: Id::from(0), msg: Get(3) }, Deliver { src: Id::from(0), dst: Id::from(1), msg: GetOk(3, 'A') }, ]); } // ANCHOR_END: test } // ANCHOR: main fn main() { env_logger::init_from_env(env_logger::Env::default().default_filter_or("info")); spawn( serde_json::to_vec, |bytes| serde_json::from_slice(bytes), vec![ (SocketAddrV4::new(Ipv4Addr::LOCALHOST, 3000), ServerActor) ]).unwrap(); } // ANCHOR_END: main /* ANCHOR_END: all */
true
539a574f3851eefc209d9506b0cbe9999a5ed8f8
Rust
unpluggedcoder/memory-profiler
/integration-tests/test-programs/return-opt-u128.rs
UTF-8
401
2.640625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
const CONSTANT: u128 = 0xaaaaaaaaaaaaaaaa5555555555555555; extern { fn malloc( size: usize ) -> *const u8; fn abort() -> !; } #[inline(never)] #[no_mangle] fn func_1() -> Option< u128 > { unsafe { malloc( 123456 ); } Some( CONSTANT ) } #[inline(never)] #[no_mangle] fn func_2() { if func_1() != Some( CONSTANT ) { unsafe { abort(); } } } fn main() { func_2(); }
true
d24d4db001063f5d1473e134935fe0021b6b5b70
Rust
kavirajk/pgroup
/src/lib.rs
UTF-8
2,373
2.734375
3
[]
no_license
use bincode; use crossbeam_channel::Receiver; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::net::{SocketAddr, ToSocketAddrs, UdpSocket}; #[derive(Debug)] struct Group { me: Node, peers: HashMap<String, Node>, // ack for specific ping's seq_no. ack_handlers: HashMap<u32, Receiver<Packet>>, } impl Group { fn members(&self) -> Vec<Node> { unimplemented!() } fn new(me: Node, seed_peers: &[Node]) -> Self { unimplemented!() } fn probe_peers(&self) { unimplemented!() } fn probe(&self, node: &Node) { unimplemented!() } fn packet_listener(&self) -> Result<(), String> { let mut buf: Vec<u8> = vec![0; 1024]; self.me.sock.recv(&mut buf).unwrap(); let pkt = decode_packet(&buf).unwrap(); match pkt { Packet::Ping { from, seq_no } => if self.ack_handlers.contains_key(&seq_no) {}, Packet::Ack { from, seq_no } => {} Packet::PingReq => {} Packet::IndirectAck => {} _ => {} } Ok(()) } fn send<T: ToSocketAddrs>(sock: &UdpSocket, msg: Vec<u8>, to: T) -> std::io::Result<usize> { sock.send_to(&msg, to) } fn encode_and_send() {} } #[derive(Debug)] struct Node { name: String, seq_no: u64, incar_no: u64, addr: SocketAddr, sock: UdpSocket, state: NodeState, } impl Node { fn next_seq_no(&self) { unimplemented!() } fn next_incar_no(&self) { unimplemented!() } } #[derive(Debug)] enum NodeState { Alive, Dead, Suspect, } #[derive(Serialize, Deserialize, Debug, PartialEq)] enum Packet { Ping { from: String, seq_no: u32 }, Ack { from: String, seq_no: u32 }, PingReq, IndirectAck, Alive, Joined, Left, Failed, } fn encode_packet(pkt: &Packet) -> Result<Vec<u8>, String> { let buf = bincode::serialize(pkt).unwrap(); Ok(buf) } fn decode_packet(buf: &[u8]) -> Result<Packet, String> { let pkt: Packet = bincode::deserialize(buf).unwrap(); Ok(pkt) } #[test] fn test_encode_decode() { let before = Packet::Ping { from: "me".to_owned(), seq_no: 1234, }; let buf = encode_packet(&before).unwrap(); let after = decode_packet(&buf).unwrap(); assert_eq!(before, after); }
true
f9a2594077419e7a188555f362be2af0e36c6b1a
Rust
quinnnned/rust-mancala
/src/main.rs
UTF-8
9,671
3.09375
3
[]
no_license
use std::fmt; #[derive(Copy, Clone, PartialEq, Debug)] struct Player { pits: [i8; 6], score: i8, } impl Player { fn get_moves(&self) -> Vec<usize> { (0..6) .into_iter() .filter(|&i| self.pits[i] != 0) .collect::<Vec<_>>() } } #[derive(Copy, Clone, PartialEq, Debug)] enum GameMode { WhiteTurn, BlackTurn, GameOver, } #[derive(Copy, Clone, PartialEq, Debug)] struct GameState { mode: GameMode, white: Player, black: Player, } struct GameSkeuomorph { b: [i8; 8], w: [i8; 8], } impl fmt::Display for GameState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, " |{: >2}|{: >2}|{: >2}|{: >2}|{: >2}|{: >2}| {: >2} |--{}--| {} |{: >2}|{: >2}|{: >2}|{: >2}|{: >2}|{: >2}| ", // Top Row: Black Pits (reverse order) self.black.pits[5], self.black.pits[4], self.black.pits[3], self.black.pits[2], self.black.pits[1], self.black.pits[0], // Middle Row: Score and Status self.black.score, match self.mode { GameMode::WhiteTurn => "WHITE TO MOVE", GameMode::BlackTurn => "BLACK TO MOVE", GameMode::GameOver => "--GAME OVER--", }, self.white.score, // Bottom Row: White Pits self.white.pits[0], self.white.pits[1], self.white.pits[2], self.white.pits[3], self.white.pits[4], self.white.pits[5], ) } } impl GameState { fn get_valid_moves(&self) -> Vec<usize> { match self.mode { GameMode::WhiteTurn => self.white.get_moves(), GameMode::BlackTurn => self.black.get_moves(), GameMode::GameOver => vec![], } } fn from(s: GameSkeuomorph) -> GameState { GameState { mode: if s.b[7] == 0 { if s.w[0] == 0 { GameMode::GameOver } else { GameMode::WhiteTurn } } else { GameMode::BlackTurn }, white: Player { pits: [s.w[1], s.w[2], s.w[3], s.w[4], s.w[5], s.w[6]], score: s.w[7], }, black: Player { pits: [s.b[6], s.b[5], s.b[4], s.b[3], s.b[2], s.b[1]], score: s.b[0], }, } } fn new() -> GameState { GameState::from(GameSkeuomorph { b: [0, 4, 4, 4, 4, 4, 4, 0], w: [1, 4, 4, 4, 4, 4, 4, 0], }) } fn get_next_state(&self, pit_index: usize) -> GameState { // Ignore moves after Game Over if self.mode == GameMode::GameOver { return GameState { ..*self }; } // Set up active/inactive semantics let (mut active_player, mut inactive_player) = match self.mode { GameMode::WhiteTurn => (self.white, self.black), _ => (self.black, self.white), }; let mut last_stone_was_score = false; let mut stones_to_move = active_player.pits[pit_index]; let mut pit_pointer = pit_index; const MAX_PIT_INDEX: usize = 5; active_player.pits[pit_pointer] = 0; pit_pointer += 1; while stones_to_move > 0 { // Active Pits while stones_to_move > 0 && pit_pointer <= MAX_PIT_INDEX { stones_to_move -= 1; // Detect Steal let is_last_stone = stones_to_move == 0; let last_pit_is_empty = active_player.pits[pit_pointer] == 0; if is_last_stone && last_pit_is_empty { let opposite_pit = 5 - pit_pointer; let stolen_stones = inactive_player.pits[opposite_pit]; inactive_player.pits[opposite_pit] = 0; active_player.score += stolen_stones + 1; } else { active_player.pits[pit_pointer] += 1; pit_pointer += 1; } } // Active Scoring Pit if stones_to_move > 0 { stones_to_move -= 1; let is_last_stone = stones_to_move == 0; if is_last_stone { last_stone_was_score = true; } active_player.score += 1; pit_pointer = 0; } // Inactive Pits while stones_to_move > 0 && pit_pointer <= MAX_PIT_INDEX { stones_to_move -= 1; inactive_player.pits[pit_pointer] += 1; pit_pointer += 1; } pit_pointer = 0; } // Undo active/inactive semantics let (white, black) = match self.mode { GameMode::WhiteTurn => (active_player, inactive_player), _ => (inactive_player, active_player), }; let is_game_over = true && active_player.pits[0] == 0 && active_player.pits[1] == 0 && active_player.pits[2] == 0 && active_player.pits[3] == 0 && active_player.pits[4] == 0 && active_player.pits[5] == 0; let mode = if is_game_over { GameMode::GameOver } else { if last_stone_was_score { self.mode } else { if self.mode == GameMode::WhiteTurn { GameMode::BlackTurn } else { GameMode::WhiteTurn } } }; return GameState { mode, white, black }; } } #[test] fn game_over_is_permanent() { let game_over = GameState::from(GameSkeuomorph { b: [0, 4, 4, 4, 4, 4, 4, 0], w: [0, 4, 4, 4, 4, 4, 4, 0], }); assert_eq!(game_over.get_next_state(0), game_over); } #[test] fn white_basic_move() { assert_eq!( GameState::new().get_next_state(0), GameState::from(GameSkeuomorph { b: [0, 4, 4, 4, 4, 4, 4, 1], w: [0, 0, 5, 5, 5, 5, 4, 0], }) ); } #[test] fn black_basic_move() { assert_eq!( GameState::new().get_next_state(0).get_next_state(0), GameState::from(GameSkeuomorph { b: [0, 4, 5, 5, 5, 5, 0, 0], w: [1, 0, 5, 5, 5, 5, 4, 0], }) ); } #[test] fn white_overflow_move() { assert_eq!( GameState::new().get_next_state(5), GameState::from(GameSkeuomorph { b: [0, 4, 4, 4, 5, 5, 5, 1], w: [0, 4, 4, 4, 4, 4, 0, 1], }) ); } #[test] fn black_overflow_move() { assert_eq!( GameState::from(GameSkeuomorph { b: [0, 4, 4, 4, 5, 5, 5, 1], w: [0, 4, 4, 4, 4, 4, 0, 1], }).get_next_state(5), GameState::from(GameSkeuomorph { b: [1, 0, 4, 4, 5, 5, 5, 0], w: [1, 5, 5, 5, 4, 4, 0, 1], }) ); } #[test] fn white_free_turn() { assert_eq!( GameState::new().get_next_state(2), GameState::from(GameSkeuomorph { b: [0, 4, 4, 4, 4, 4, 4, 0], w: [1, 4, 4, 0, 5, 5, 5, 1], }) ); } #[test] fn black_free_turn() { assert_eq!( GameState::new().get_next_state(0).get_next_state(2), GameState::from(GameSkeuomorph { b: [1, 5, 5, 5, 0, 4, 4, 1], w: [0, 0, 5, 5, 5, 5, 4, 0], }) ); } #[test] fn white_long_wrap() { assert_eq!( GameState::from(GameSkeuomorph { b: [0, 0, 0, 0, 0, 0, 0, 0], w: [1, 0, 0, 0, 0, 0, 48, 0], }).get_next_state(5), GameState::from(GameSkeuomorph { b: [0, 4, 4, 4, 4, 4, 4, 1], w: [0, 4, 4, 3, 3, 3, 3, 4], }) ); } #[test] fn black_long_wrap() { assert_eq!( GameState::from(GameSkeuomorph { b: [0, 48, 0, 0, 0, 0, 0, 1], w: [0, 0, 0, 0, 0, 0, 0, 0], }).get_next_state(5), GameState::from(GameSkeuomorph { b: [4, 3, 3, 3, 3, 4, 4, 0], w: [1, 4, 4, 4, 4, 4, 4, 0], }) ); } #[test] fn white_steal() { assert_eq!( GameState::from(GameSkeuomorph { b: [0, 4, 4, 4, 4, 4, 4, 0], w: [1, 8, 4, 4, 4, 4, 0, 0], }).get_next_state(1), GameState::from(GameSkeuomorph { b: [0, 4, 4, 4, 4, 4, 0, 1], w: [0, 8, 0, 5, 5, 5, 0, 5], }) ); } #[test] fn black_steal() { assert_eq!( GameState::from(GameSkeuomorph { b: [0, 0, 4, 4, 4, 4, 8, 1], w: [0, 4, 4, 4, 4, 4, 4, 0], }).get_next_state(1), GameState::from(GameSkeuomorph { b: [5, 0, 5, 5, 5, 0, 8, 0], w: [1, 0, 4, 4, 4, 4, 4, 0], }) ); } #[test] fn game_over_if_white_empty() { assert_eq!( GameState::from(GameSkeuomorph { b: [0, 8, 8, 8, 8, 8, 6, 0], w: [1, 0, 0, 0, 0, 0, 2, 0], }).get_next_state(5), GameState::from(GameSkeuomorph { b: [0, 8, 8, 8, 8, 8, 7, 0], w: [0, 0, 0, 0, 0, 0, 0, 1], }) ); } #[test] fn game_over_if_black_empty() { assert_eq!( GameState::from(GameSkeuomorph { b: [0, 2, 0, 0, 0, 0, 0, 1], w: [0, 6, 8, 8, 8, 8, 8, 0], }).get_next_state(5), GameState::from(GameSkeuomorph { b: [1, 0, 0, 0, 0, 0, 0, 0], w: [0, 7, 8, 8, 8, 8, 8, 0], }) ); } fn main() {}
true
ca8df953a610e9ef5696a063e7b52596cd83288f
Rust
blackjack/algorithms_pt1
/rust/week01_quickmerge/src/percolation.rs
UTF-8
3,263
3.3125
3
[]
no_license
use std::fmt::{Display, Formatter, Error}; use quickmerge::QuickMerge; #[allow(dead_code)] pub struct Percolation { x: usize, y: usize, pub last: usize, data: QuickMerge, } impl Percolation { pub fn new(x: usize, y: usize) -> Percolation { let mut p = Percolation { x: x, y: y, last: x * y + 1, data: QuickMerge::new(x * y + 2), }; for i in p.data.id.iter_mut() { *i = x * y + 2; } p.data.id[0] = 0; p.data.id[p.last] = p.last; p } pub fn index(&self, row: usize, column: usize) -> usize { if row == 0 { return 0; } if row > self.y { return self.last; } self.y * (row - 1) + column } pub fn open(&mut self, row: usize, column: usize) { let index = self.index(row, column); if !self.is_open(row, column) { self.data.id[index] = index; } let neighbors = [(row + 1, column), (row - 1, column), (row, column + 1), (row, column - 1)]; let x = self.x; for &(nrow, ncol) in neighbors.iter() .filter(|c| c.1 > 0 && c.1 <= x) { if self.is_open(nrow, ncol) { let neighbor = self.index(nrow, ncol); self.data.union(index, neighbor); } } } pub fn is_open(&self, row: usize, column: usize) -> bool { let index = self.index(row, column); self.data.id[index] <= self.last } pub fn is_full(&mut self, row: usize, column: usize) -> bool { let index = self.index(row, column); self.data.connected(index, 0) } pub fn number_of_open_sites(&self) -> usize { let max = self.last; let id = &self.data.id[1..max]; id.iter().filter(|&&i| i < max).count() } pub fn percolates(&mut self) -> bool { let row = self.y + 1; self.is_full(row, 1) } } impl Display for Percolation { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { write!(f, "{}\n", self.data.id[0])?; let print = |row, column| { if self.is_open(row, column) { let index = self.index(row, column); self.data.id[index].to_string() } else { "X".to_string() } }; for row in 1..self.x + 1 { for column in 1..self.y + 1 { write!(f, "{}", print(row, column))?; } write!(f, "\n")?; } write!(f, "{}\n", print(self.y + 1, self.x)) } } #[test] fn test_open() { let mut p = Percolation::new(3, 3); p.open(1, 3); p.open(2, 2); p.open(2, 3); p.open(3, 3); assert!(p.is_open(4, 3)); assert!(p.is_open(4, 1)); } #[test] fn test_count() { let mut p = Percolation::new(3, 3); p.open(1, 3); p.open(2, 2); p.open(2, 3); p.open(3, 3); assert_eq!(4, p.number_of_open_sites()); } #[test] fn test_percolates() { let mut p = Percolation::new(3, 3); p.open(1, 1); p.open(2, 1); p.open(2, 2); p.open(2, 3); assert!(!p.percolates()); p.open(3, 3); assert!(p.percolates()); }
true
fe45abe02d8c82057cab67c3d57a52c0db4ac9a4
Rust
KaiseiYokoyama/iiif_awesome_sample_viewer
/src/iif_manifest.rs
UTF-8
1,711
2.75
3
[]
no_license
#[derive(Deserialize, Debug, Serialize)] pub struct Manifest { #[serde(rename = "@context")] context: String, #[serde(rename = "@id")] id: String, #[serde(rename = "@type")] type_: String, license: String, attribution: String, description: String, label: String, sequences: Vec<Sequence>, } impl Manifest { pub fn get_images(&self) -> Vec<String> { let mut images = Vec::new(); for sequence in &self.sequences { for canvas in &sequence.canvases { for image in &canvas.images { images.push(image.resource.id.clone()); } } } return images; } } #[derive(Deserialize, Debug, Serialize)] struct Sequence { #[serde(rename = "@id")] id: String, #[serde(rename = "@type")] type_: String, canvases: Vec<Canvas>, } #[derive(Deserialize, Debug, Serialize)] struct Canvas { #[serde(rename = "@id")] id: String, #[serde(rename = "@type")] type_: String, width: u32, height: u32, label: String, images: Vec<Image>, } #[derive(Deserialize, Debug, Serialize)] struct Image { #[serde(rename = "@id")] id: String, #[serde(rename = "@type")] type_: String, resource: Resource, } #[derive(Deserialize, Debug, Serialize)] struct Resource { #[serde(rename = "@id")] id: String, #[serde(rename = "@type")] type_: String, format: String, width: u32, height: u32, service: Service, } #[derive(Deserialize, Debug, Serialize)] struct Service { #[serde(rename = "@context")] context: String, #[serde(rename = "@id")] id: String, profile: String, }
true
157578cc19a1950de93f8033afdf0c4e222d9af6
Rust
KallDrexx/r8
/r8-core/src/execution.rs
UTF-8
51,703
2.90625
3
[]
no_license
use custom_error::custom_error; use crate::{Hardware, Instruction, Register}; use crate::hardware::{STACK_SIZE, MEMORY_SIZE, FRAMEBUFFER_HEIGHT, FRAMEBUFFER_WIDTH}; custom_error!{pub ExecutionError InvalidRegisterForInstruction {instruction:Instruction} = "Invalid register was used for instruction: {instruction}", UnhandleableInstruction {instruction:Instruction} = "The instruction '{instruction}' is not known", StackOverflow = "Call exceeded maximum stack size", InvalidCallOrJumpAddress {address:u16} = "Call performed to invalid address {address}", EmptyStack = "Return was called with an empty stack", InvalidFontDigit {digit: u8} = "Font digit of {digit} is invalid, only 0-f is allowed", } pub fn execute_instruction(instruction: Instruction, hardware: &mut Hardware) -> Result<(), ExecutionError> { match instruction { Instruction::AddFromRegister {register1: Register::General(reg1_num), register2: Register::General(reg2_num)} => { let reg1_value = hardware.gen_registers[reg1_num as usize]; let reg2_value = hardware.gen_registers[reg2_num as usize]; let will_wrap = reg1_value > 0 && std::u8::MAX - reg1_value < reg2_value;; hardware.gen_registers[reg1_num as usize] = reg1_value.wrapping_add(reg2_value); hardware.gen_registers[0xf] = if will_wrap { 1 } else { 0}; hardware.program_counter += 2; } Instruction::AddFromRegister {register1: Register::I, register2: Register::General(reg2_num)} => { hardware.i_register = hardware.i_register.wrapping_add(hardware.gen_registers[reg2_num as usize] as u16); hardware.program_counter += 2; } Instruction::AddFromValue {register: Register::General(reg_num), value} => { hardware.gen_registers[reg_num as usize] = hardware.gen_registers[reg_num as usize].wrapping_add(value); hardware.program_counter += 2; } Instruction::And {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => { hardware.gen_registers[reg_num1 as usize] = hardware.gen_registers[reg_num1 as usize] & hardware.gen_registers[reg_num2 as usize]; hardware.program_counter += 2; } Instruction::Call {address} => { if hardware.stack_pointer >= STACK_SIZE { return Err(ExecutionError::StackOverflow); } hardware.stack[hardware.stack_pointer] = hardware.program_counter; hardware.stack_pointer = hardware.stack_pointer + 1; hardware.program_counter = address; } Instruction::ClearDisplay => { for x in 0..hardware.framebuffer.len() { for y in 0..hardware.framebuffer[x].len() { hardware.framebuffer[x][y] = 0; } } hardware.program_counter += 2; } Instruction::DrawSprite {x_register: Register::General(x_reg_num), y_register: Register::General(y_reg_num), height} => { let first_row = hardware.gen_registers[y_reg_num as usize] as usize; let first_pixel = hardware.gen_registers[x_reg_num as usize] as usize; let shift_amount = first_pixel % 8; let left_column_set = first_pixel / 8; // According to the Cowgod spec, if the right column set would be out of bounds it // wraps to the other side on the same row let right_column_set = (left_column_set + 1) % (FRAMEBUFFER_WIDTH / 8); let mut collisions_found = false; for x in 0..height as usize { let sprite_byte = hardware.memory[hardware.i_register as usize + x]; let left_byte = sprite_byte >> shift_amount; // According to Cowgod spec, if we've gone past the screen in height then wrap to the top let row = (first_row + x) % FRAMEBUFFER_HEIGHT; // Detect if the xor will reset any already on pixels if hardware.framebuffer[row][left_column_set] & left_byte > 0 { collisions_found = true; } // Update framebuffer hardware.framebuffer[row][left_column_set] ^= left_byte; // If we are affecting pixels across column set boundaries, repeat for the next byte if shift_amount > 0 { let right_byte = sprite_byte << 8 - shift_amount; if hardware.framebuffer[row][right_column_set] & right_byte > 0 { collisions_found = true; } hardware.framebuffer[row][right_column_set] ^= right_byte; } } hardware.program_counter += 2; hardware.gen_registers[0xf] = if collisions_found { 1 } else { 0 }; } Instruction::JumpToAddress {address, add_register_0} => { let final_address = match add_register_0 { true => address + hardware.gen_registers[0] as u16, false => address }; if final_address < 512 || final_address > MEMORY_SIZE as u16 { return Err(ExecutionError::InvalidCallOrJumpAddress {address: final_address}); } hardware.program_counter = final_address; } Instruction::LoadAddressIntoIRegister {address} => { hardware.i_register = address; hardware.program_counter += 2; } Instruction::LoadBcdValue {source: Register::General(reg_num)} => { let start_address = hardware.i_register as usize; let source_value = hardware.gen_registers[reg_num as usize]; hardware.memory[start_address] = (source_value / 100) % 10; hardware.memory[start_address + 1] = (source_value / 10) % 10; hardware.memory[start_address + 2] = source_value % 10; hardware.program_counter += 2; } Instruction::LoadFromKeyPress {destination: Register::General(reg_num)} => { // According to specs I have found this instruction does not recognize a key if it's // currently down. So it will wait (stay on the same program counter for our purposes) // until the user releases the key, at which point for one execution // `hardware.key_released_since_last_instruction` should have the key that was just released. if let Some(key_num) = hardware.key_released_since_last_instruction { hardware.gen_registers[reg_num as usize] = key_num; hardware.program_counter += 2; } } Instruction::LoadFromMemory {last_register: Register::General(reg_num)} => { for index in 0..=reg_num { hardware.gen_registers[index as usize] = hardware.memory[hardware.i_register as usize + index as usize]; } hardware.i_register = hardware.i_register + reg_num as u16 + 1; hardware.program_counter += 2; } Instruction::LoadFromRegister {destination, source} => { let source_value = match source { Register::General(num) => hardware.gen_registers[num as usize], Register::SoundTimer => hardware.sound_timer, Register::DelayTimer => hardware.delay_timer, _ => return Err(ExecutionError::InvalidRegisterForInstruction {instruction: Instruction::LoadFromRegister {destination, source}}), }; match destination { Register::General(num) => hardware.gen_registers[num as usize] = source_value, Register::SoundTimer => hardware.sound_timer = source_value, Register::DelayTimer => hardware.delay_timer = source_value, _ => return Err(ExecutionError::InvalidRegisterForInstruction {instruction: Instruction::LoadFromRegister {destination, source}}), } hardware.program_counter += 2; } Instruction::LoadFromValue {destination: Register::General(reg_num), value} => { hardware.gen_registers[reg_num as usize] = value; hardware.program_counter += 2; } Instruction::LoadIntoMemory {last_register: Register::General(reg_num)} => { for index in 0..=reg_num { hardware.memory[hardware.i_register as usize + index as usize] = hardware.gen_registers[index as usize]; } hardware.i_register = hardware.i_register + reg_num as u16 + 1; hardware.program_counter += 2; } Instruction::LoadSpriteLocation {sprite_digit: Register::General(reg_num)} => { let digit = hardware.gen_registers[reg_num as usize]; if digit > 0xf { return Err(ExecutionError::InvalidFontDigit {digit}); } hardware.i_register = hardware.font_addresses[&digit]; hardware.program_counter += 2; } Instruction::Or {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => { hardware.gen_registers[reg_num1 as usize] = hardware.gen_registers[reg_num1 as usize] | hardware.gen_registers[reg_num2 as usize]; hardware.program_counter += 2; } Instruction::Return => { if hardware.stack_pointer == 0 { return Err(ExecutionError::EmptyStack); } hardware.program_counter = hardware.stack[hardware.stack_pointer - 1] + 2; hardware.stack_pointer = hardware.stack_pointer - 1; } Instruction::SetRandom {register: Register::General(reg_num), and_value} => { hardware.gen_registers[reg_num as usize] = rand::random::<u8>() & and_value; hardware.program_counter += 2; } Instruction::ShiftLeft {register: Register::General(reg_num)} => { hardware.gen_registers[reg_num as usize] = hardware.gen_registers[reg_num as usize] << 1; hardware.program_counter += 2; } Instruction::ShiftRight {register: Register::General(reg_num)} => { hardware.gen_registers[reg_num as usize] = hardware.gen_registers[reg_num as usize] >> 1; hardware.program_counter += 2; } Instruction::SkipIfEqual {register: Register::General(reg_num), value} => { let increment = match hardware.gen_registers[reg_num as usize] == value { true => 4, false => 2, }; hardware.program_counter += increment; } Instruction::SkipIfKeyPressed {register: Register::General(reg_num)} => { let increment = match hardware.current_key_down { Some(x) if x == hardware.gen_registers[reg_num as usize] => 4, _ => 2, }; hardware.program_counter += increment; } Instruction::SkipIfKeyNotPressed {register: Register::General(reg_num)} => { let increment = match hardware.current_key_down { Some(x) if x == hardware.gen_registers[reg_num as usize] => 2, _ => 4, }; hardware.program_counter += increment; } Instruction::SkipIfNotEqual {register: Register::General(reg_num), value} => { let increment = match hardware.gen_registers[reg_num as usize] == value { true => 2, false => 4, }; hardware.program_counter += increment; } Instruction::SkipIfRegistersEqual {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => { let increment = match hardware.gen_registers[reg_num1 as usize] == hardware.gen_registers[reg_num2 as usize] { true => 4, false => 2, }; hardware.program_counter += increment; } Instruction::SkipIfRegistersNotEqual {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => { let increment = match hardware.gen_registers[reg_num1 as usize] == hardware.gen_registers[reg_num2 as usize] { true => 2, false => 4, }; hardware.program_counter += increment; } Instruction::Subtract {minuend: Register::General(minuend_reg), subtrahend: Register::General(subtrahend_reg), stored_in: Register::General(stored_in_reg)} => { let will_underflow = hardware.gen_registers[minuend_reg as usize] < hardware.gen_registers[subtrahend_reg as usize]; let difference = hardware.gen_registers[minuend_reg as usize].wrapping_sub(hardware.gen_registers[subtrahend_reg as usize]); hardware.gen_registers[stored_in_reg as usize] = difference; hardware.gen_registers[0xf] = if will_underflow { 0 } else { 1 }; hardware.program_counter += 2; } Instruction::Xor {register1: Register::General(reg_num1), register2: Register::General(reg_num2)} => { hardware.gen_registers[reg_num1 as usize] = hardware.gen_registers[reg_num1 as usize] ^ hardware.gen_registers[reg_num2 as usize]; hardware.program_counter += 2; } _ => return Err(ExecutionError::UnhandleableInstruction{instruction}) } Ok(()) } #[cfg(test)] mod tests { use super::*; use ::{Hardware, Register}; #[test] fn can_add_value_to_general_register() { const REGISTER_NUMBER: u8 = 3; let mut hardware = Hardware::new(); hardware.gen_registers[REGISTER_NUMBER as usize] = 100; hardware.program_counter = 1000; let instruction = Instruction::AddFromValue { register: Register::General(REGISTER_NUMBER), value: 12, }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.gen_registers[REGISTER_NUMBER as usize], 112, "Invalid register value"); assert_eq!(hardware.program_counter, 1002, "Invalid resulting program counter"); } #[test] fn can_add_value_to_general_register_that_overflows() { const REGISTER_NUMBER: u8 = 3; let mut hardware = Hardware::new(); hardware.gen_registers[REGISTER_NUMBER as usize] = 100; hardware.program_counter = 1000; let instruction = Instruction::AddFromValue { register: Register::General(REGISTER_NUMBER), value: 165, }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.gen_registers[REGISTER_NUMBER as usize], 9, "Invalid register value"); assert_eq!(hardware.program_counter, 1002, "Invalid resulting program counter"); assert_eq!(hardware.gen_registers[0xf], 0, "Add by value should not have caused carry mark"); } #[test] fn can_add_value_from_general_register_without_carry() { const REGISTER1_NUMBER: u8 = 4; const REGISTER2_NUMBER: u8 = 6; let mut hardware = Hardware::new(); hardware.gen_registers[REGISTER1_NUMBER as usize] = 100; hardware.gen_registers[REGISTER2_NUMBER as usize] = 55; hardware.program_counter = 1000; let instruction = Instruction::AddFromRegister { register1: Register::General(REGISTER1_NUMBER), register2: Register::General(REGISTER2_NUMBER), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.gen_registers[REGISTER1_NUMBER as usize], 155, "Invalid register value"); assert_eq!(hardware.gen_registers[0xf], 0, "Invalid VF register value"); assert_eq!(hardware.program_counter, 1002, "Invalid resulting program counter"); } #[test] fn can_add_value_from_general_register_with_carry() { const REGISTER1_NUMBER: u8 = 4; const REGISTER2_NUMBER: u8 = 6; let mut hardware = Hardware::new(); hardware.gen_registers[REGISTER1_NUMBER as usize] = 200; hardware.gen_registers[REGISTER2_NUMBER as usize] = 65; hardware.program_counter = 1000; let instruction = Instruction::AddFromRegister { register1: Register::General(REGISTER1_NUMBER), register2: Register::General(REGISTER2_NUMBER), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.gen_registers[REGISTER1_NUMBER as usize], 9, "Invalid register value"); assert_eq!(hardware.gen_registers[0xf], 1, "Invalid VF register value"); assert_eq!(hardware.program_counter, 1002, "Invalid resulting program counter"); } #[test] fn can_add_value_from_general_register_to_i_register() { let mut hardware = Hardware::new(); hardware.i_register = 100; hardware.gen_registers[3] = 12; hardware.program_counter = 1000; let instruction = Instruction::AddFromRegister { register1: Register::I, register2: Register::General(3), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.i_register, 112, "Invalid register value"); assert_eq!(hardware.program_counter, 1002, "Invalid resulting program counter"); } #[test] fn can_execute_call_instruction() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.stack[0] = 567; hardware.stack[1] = 599; hardware.stack_pointer = 2; let instruction = Instruction::Call {address: 1654}; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.stack_pointer, 3, "Incorrect stack pointer"); assert_eq!(hardware.stack[0], 567, "Incorrect address at stack 0"); assert_eq!(hardware.stack[1], 599, "Incorrect address at stack 1"); assert_eq!(hardware.stack[2], 1000, "Incorrect address at stack 2"); assert_eq!(hardware.program_counter, 1654, "Incorrect program counter value"); } #[test] fn stack_overflow_error_when_call_performed_at_max_stack() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.stack_pointer = 16; let instruction = Instruction::Call {address: 1654}; match execute_instruction(instruction, &mut hardware).unwrap_err() { ExecutionError::StackOverflow => (), x => panic!("Expected StackOverflow, instead got {:?}", x), } } #[test] fn can_call_jump_to_address_without_add() { let mut hardware = Hardware::new(); hardware.program_counter = 1002; hardware.gen_registers[0] = 10; hardware.stack_pointer = 1; hardware.stack[0] = 533; let instruction = Instruction::JumpToAddress {address: 2330, add_register_0: false}; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 2330, "Incorrect program counter value"); assert_eq!(hardware.stack_pointer, 1, "Incorrect stack pointer value"); // Make sure stack wasn't messed with assert_eq!(hardware.stack[0], 533, "Incorrect stack[0] value"); } #[test] fn can_call_jump_address_with_add() { let mut hardware = Hardware::new(); hardware.program_counter = 1002; hardware.gen_registers[0] = 10; hardware.stack_pointer = 1; hardware.stack[0] = 533; let instruction = Instruction::JumpToAddress {address: 2330, add_register_0: true}; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 2340, "Incorrect program counter value"); assert_eq!(hardware.stack_pointer, 1, "Incorrect stack pointer value"); // Make sure stack wasn't messed with assert_eq!(hardware.stack[0], 533, "Incorrect stack[0] value"); } #[test] fn cannot_jump_to_address_below_512() { let mut hardware = Hardware::new(); hardware.program_counter = 1002; hardware.gen_registers[0] = 10; hardware.stack_pointer = 1; hardware.stack[0] = 533; let instruction = Instruction::JumpToAddress {address: 511, add_register_0: false}; match execute_instruction(instruction, &mut hardware).unwrap_err() { ExecutionError::InvalidCallOrJumpAddress {address: 511} => (), x => panic!("Expected InvalidCallOrJumpAddress {{address: 2331}}, instead got {:?}", x), } } #[test] fn cannot_jump_to_address_above_memory_size() { let mut hardware = Hardware::new(); hardware.program_counter = 1002; hardware.gen_registers[0] = 10; hardware.stack_pointer = 1; hardware.stack[0] = 533; let address = MEMORY_SIZE as u16 + 1; let instruction = Instruction::JumpToAddress {address, add_register_0: false}; match execute_instruction(instruction, &mut hardware).unwrap_err() { ExecutionError::InvalidCallOrJumpAddress {address: _} => (), x => panic!("Expected InvalidCallOrJumpAddress {{address: {}}}, instead got {:?}", address, x), } } #[test] fn jump_to_machine_code_is_unhandled() { // According to specs, SYS instructions are ignored by modern interpreters. let mut hardware = Hardware::new(); let instruction = Instruction::JumpToMachineCode {address: 123}; match execute_instruction(instruction, &mut hardware).unwrap_err() { ExecutionError::UnhandleableInstruction {instruction: _} => (), x => panic!("Expected UnhandleableInstruction, instead got {:?}", x), } } #[test] fn can_load_from_value_into_general_register() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[4] = 10; let instruction = Instruction::LoadFromValue { destination: Register::General(4), value: 123, }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.gen_registers[4], 123, "Incorrect value in register"); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); } #[test] fn can_load_from_register_into_general_register() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[4] = 10; hardware.gen_registers[5] = 122; let instruction = Instruction::LoadFromRegister { destination: Register::General(4), source: Register::General(5), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.gen_registers[4], 122, "Incorrect value in register"); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); } #[test] fn load_from_key_press_does_not_progress_if_no_key_released() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[4] = 10; hardware.current_key_down = Some(0x4); hardware.key_released_since_last_instruction = None; let instruction = Instruction::LoadFromKeyPress {destination: Register::General(4)}; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1000, "Incorrect program counter"); assert_eq!(hardware.gen_registers[4], 10, "Register 4 value should not have changed"); } #[test] fn load_from_key_press_proceeds_if_key_was_released() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[4] = 10; hardware.current_key_down = None; hardware.key_released_since_last_instruction = Some(0x5); let instruction = Instruction::LoadFromKeyPress {destination: Register::General(4)}; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[4], 5, "Incorrect value in register"); } #[test] fn can_load_bcd_value_into_memory() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[5] = 235; hardware.i_register = 1500; let instruction = Instruction::LoadBcdValue {source: Register::General(5)}; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.memory[1500], 2, "Incorrect bcd value #1"); assert_eq!(hardware.memory[1501], 3, "Incorrect bcd value #2"); assert_eq!(hardware.memory[1502], 5, "Incorrect bcd value #3"); } #[test] fn can_load_register_values_into_memory() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[0] = 100; hardware.gen_registers[1] = 101; hardware.gen_registers[2] = 102; hardware.gen_registers[3] = 103; hardware.gen_registers[4] = 104; hardware.gen_registers[5] = 105; hardware.i_register = 933; let instruction = Instruction::LoadIntoMemory {last_register: Register::General(4)}; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.memory[933], 100, "Incorrect value in memory location 0"); assert_eq!(hardware.memory[934], 101, "Incorrect value in memory location 1"); assert_eq!(hardware.memory[935], 102, "Incorrect value in memory location 2"); assert_eq!(hardware.memory[936], 103, "Incorrect value in memory location 3"); assert_eq!(hardware.memory[937], 104, "Incorrect value in memory location 4"); assert_eq!(hardware.memory[938], 0, "Incorrect value in memory location 5"); assert_eq!(hardware.i_register, 938, "Incorrect resulting I register"); } #[test] fn can_load_memory_into_multiple_register_values() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.i_register = 933; hardware.memory[933] = 100; hardware.memory[934] = 101; hardware.memory[935] = 102; hardware.memory[936] = 103; hardware.memory[937] = 104; hardware.memory[938] = 105; let instruction = Instruction::LoadFromMemory {last_register: Register::General(4)}; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[0], 100, "Incorrect value in register V0"); assert_eq!(hardware.gen_registers[1], 101, "Incorrect value in register V1"); assert_eq!(hardware.gen_registers[2], 102, "Incorrect value in register V2"); assert_eq!(hardware.gen_registers[3], 103, "Incorrect value in register V3"); assert_eq!(hardware.gen_registers[4], 104, "Incorrect value in register V4"); assert_eq!(hardware.gen_registers[5], 0, "Incorrect value in register V5"); assert_eq!(hardware.i_register, 938, "Incorrect resulting I register"); } #[test] fn can_execute_return_instruction() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.stack_pointer = 2; hardware.stack[0] = 1500; hardware.stack[1] = 938; hardware.stack[2] = 1700; // residual from previous call let instruction = Instruction::Return; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 938 + 2, "Incorrect program pointer"); assert_eq!(hardware.stack_pointer, 1, "Incorrect stack pointer"); } #[test] fn cannot_execute_return_with_empty_stack() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.stack_pointer = 0; hardware.stack[0] = 1500; hardware.stack[1] = 938; let instruction = Instruction::Return; match execute_instruction(instruction, &mut hardware).unwrap_err() { ExecutionError::EmptyStack => (), x => panic!("Expected EmptyStack instead got {:?}", x), } } #[test] fn skip_occurs_when_skip_if_equal_passes() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[5] = 23; let instruction = Instruction::SkipIfEqual { register: Register::General(5), value: 23, }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1004, "Incorrect program counter"); } #[test] fn does_not_skip_when_skip_if_equal_fails() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[5] = 23; let instruction = Instruction::SkipIfEqual { register: Register::General(5), value: 24, }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); } #[test] fn skip_occurs_when_skip_if_not_equal_passes() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[5] = 23; let instruction = Instruction::SkipIfNotEqual { register: Register::General(5), value: 25, }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1004, "Incorrect program counter"); } #[test] fn does_not_skip_occurs_when_skip_if_not_equal_fails() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[5] = 23; let instruction = Instruction::SkipIfNotEqual { register: Register::General(5), value: 23, }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); } #[test] fn skip_occurs_when_skip_if_register_equals_passes() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[4] = 23; hardware.gen_registers[5] = 23; let instruction = Instruction::SkipIfRegistersEqual { register1: Register::General(5), register2: Register::General(4), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1004, "Incorrect program counter"); } #[test] fn does_not_skip_occurs_when_skip_if_register_equals_fails() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[4] = 25; hardware.gen_registers[5] = 23; let instruction = Instruction::SkipIfRegistersEqual { register1: Register::General(5), register2: Register::General(4), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); } #[test] fn skip_occurs_when_skip_if_register_not_equals_passes() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[4] = 25; hardware.gen_registers[5] = 23; let instruction = Instruction::SkipIfRegistersNotEqual { register1: Register::General(5), register2: Register::General(4), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1004, "Incorrect program counter"); } #[test] fn does_not_skip_occurs_when_skip_if_register_not_equals_fails() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[4] = 23; hardware.gen_registers[5] = 23; let instruction = Instruction::SkipIfRegistersNotEqual { register1: Register::General(5), register2: Register::General(4), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); } #[test] fn skip_occurs_when_skip_if_key_pressed_passes() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[5] = 10; hardware.current_key_down = Some(10); let instruction = Instruction::SkipIfKeyPressed { register: Register::General(5), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1004, "Incorrect program counter"); } #[test] fn does_not_skip_occurs_when_skip_if_key_pressed_fails() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[5] = 10; hardware.current_key_down = Some(11); let instruction = Instruction::SkipIfKeyPressed { register: Register::General(5), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); } #[test] fn skip_occurs_when_skip_if_key_not_pressed_passes() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[5] = 10; hardware.current_key_down = Some(11); let instruction = Instruction::SkipIfKeyNotPressed { register: Register::General(5), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1004, "Incorrect program counter"); } #[test] fn does_not_skip_occurs_when_skip_if_key_not_pressed_fails() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[5] = 10; hardware.current_key_down = Some(10); let instruction = Instruction::SkipIfKeyNotPressed { register: Register::General(5), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); } #[test] fn can_or_register_values_together() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[2] = 123; hardware.gen_registers[3] = 203; let instruction = Instruction::Or { register1: Register::General(3), register2: Register::General(2), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[2], 123, "Incorrect V2 value"); assert_eq!(hardware.gen_registers[3], 203 | 123, "Incorrect v3 value"); } #[test] fn can_and_register_values_together() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[2] = 123; hardware.gen_registers[3] = 203; let instruction = Instruction::And { register1: Register::General(3), register2: Register::General(2), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[2], 123, "Incorrect V2 value"); assert_eq!(hardware.gen_registers[3], 203 & 123, "Incorrect v3 value"); } #[test] fn can_xor_register_values_together() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[2] = 123; hardware.gen_registers[3] = 203; let instruction = Instruction::Xor { register1: Register::General(3), register2: Register::General(2), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[2], 123, "Incorrect V2 value"); assert_eq!(hardware.gen_registers[3], 203 ^ 123, "Incorrect v3 value"); } #[test] fn can_shift_register_value_right() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[3] = 203; let instruction = Instruction::ShiftRight { register: Register::General(3), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[3], 203 >> 1, "Incorrect v3 value"); } #[test] fn can_shift_register_value_left() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[3] = 203; let instruction = Instruction::ShiftLeft { register: Register::General(3), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[3], 203 << 1, "Incorrect v3 value"); } #[test] fn can_get_random_number() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[3] = 100; let instruction = Instruction::SetRandom { register: Register::General(3), and_value: 23, }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); let value1 = hardware.gen_registers[3]; let instruction = Instruction::SetRandom { register: Register::General(3), and_value: 23, }; execute_instruction(instruction, &mut hardware).unwrap(); let value2 = hardware.gen_registers[3]; assert_ne!(value1, value2, "Values 1 and 2 were the same (possibly not random??)"); } #[test] fn can_subtract_register_without_underflow() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[4] = 100; hardware.gen_registers[5] = 25; let instruction = Instruction::Subtract { minuend: Register::General(4), subtrahend: Register::General(5), stored_in: Register::General(4), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[4], 75, "Incorrect V4 register"); assert_eq!(hardware.gen_registers[5], 25, "Incorrect V5 register"); assert_eq!(hardware.gen_registers[0xf], 1, "Incorrect VF register"); } #[test] fn can_subtract_register_with_underflow() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[4] = 100; hardware.gen_registers[5] = 25; let instruction = Instruction::Subtract { minuend: Register::General(5), subtrahend: Register::General(4), stored_in: Register::General(5), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[4], 100, "Incorrect V4 register"); assert_eq!(hardware.gen_registers[5], 181, "Incorrect V5 register"); assert_eq!(hardware.gen_registers[0xf], 0, "Incorrect VF register"); } #[test] fn can_clear_display() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; for x in 0..hardware.framebuffer.len() { for y in 0..hardware.framebuffer[x].len() { hardware.framebuffer[x][y] = 0xFF; } } let instruction = Instruction::ClearDisplay; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); for x in 0..hardware.framebuffer.len() { for y in 0..hardware.framebuffer[x].len() { if hardware.framebuffer[x][y] != 0 { panic!("Expected frame buffer by {}x{} to be 0", x, y); } } } } #[test] fn can_load_digit_sprite_location() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[4] = 0xa; let instruction = Instruction::LoadSpriteLocation {sprite_digit: Register::General(4)}; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.i_register, hardware.font_addresses[&0xa], "Incorrect sprite address"); } #[test] fn can_load_address_into_i_register() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; let instruction = Instruction::LoadAddressIntoIRegister {address: 0x123}; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.i_register, 0x123, "Incorrect I register value"); } #[test] fn visible_8_x_3_sprite_to_screen_on_x_multiple_of_8_can_be_drawn() { const SPRITE_START_ADDRESS: usize = 1046; const X_POS: u8 = 16; const Y_POS: u8 = 2; let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.i_register = SPRITE_START_ADDRESS as u16; hardware.gen_registers[4] = X_POS; hardware.gen_registers[3] = Y_POS; hardware.memory[SPRITE_START_ADDRESS] = 0b10101010; hardware.memory[SPRITE_START_ADDRESS + 1] = 0b01010101; hardware.memory[SPRITE_START_ADDRESS + 2] = 0b11001101; hardware.memory[SPRITE_START_ADDRESS + 3] = 0b11111111; let instruction = Instruction::DrawSprite { x_register: Register::General(4), y_register: Register::General(3), height: 3, }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[0xf], 0, "Incorrect VF value"); assert_eq!(hardware.framebuffer[2][2], 0b10101010, "Incorrect framebuffer value at row 2 column byte 2"); assert_eq!(hardware.framebuffer[3][2], 0b01010101, "Incorrect framebuffer value at row 3 column byte 2"); assert_eq!(hardware.framebuffer[4][2], 0b11001101, "Incorrect framebuffer value at row 4 column byte 2"); assert_eq!(hardware.framebuffer[5][2], 0, "Incorrect framebuffer value at row 5 column byte 2"); } #[test] fn visible_8_x_3_sprite_to_screen_on_x_non_multiple_of_8_can_be_drawn() { const SPRITE_START_ADDRESS: usize = 1046; const X_POS: u8 = 18; const Y_POS: u8 = 2; let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.i_register = SPRITE_START_ADDRESS as u16; hardware.gen_registers[4] = X_POS; hardware.gen_registers[3] = Y_POS; hardware.memory[SPRITE_START_ADDRESS] = 0b10101010; hardware.memory[SPRITE_START_ADDRESS + 1] = 0b01010101; hardware.memory[SPRITE_START_ADDRESS + 2] = 0b11001101; hardware.memory[SPRITE_START_ADDRESS + 3] = 0b11111111; let instruction = Instruction::DrawSprite { x_register: Register::General(4), y_register: Register::General(3), height: 3, }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[0xf], 0, "Incorrect VF value"); assert_eq!(hardware.framebuffer[2][2], 0b00101010, "Incorrect framebuffer value at row 2 column byte 2"); assert_eq!(hardware.framebuffer[2][3], 0b10000000, "Incorrect framebuffer value at row 2 column byte 3"); assert_eq!(hardware.framebuffer[3][2], 0b00010101, "Incorrect framebuffer value at row 3 column byte 2"); assert_eq!(hardware.framebuffer[3][3], 0b01000000, "Incorrect framebuffer value at row 3 column byte 3"); assert_eq!(hardware.framebuffer[4][2], 0b00110011, "Incorrect framebuffer value at row 4 column byte 2"); assert_eq!(hardware.framebuffer[4][3], 0b01000000, "Incorrect framebuffer value at row 4 column byte 3"); assert_eq!(hardware.framebuffer[5][2], 0, "Incorrect framebuffer value at row 5 column byte 2"); assert_eq!(hardware.framebuffer[5][3], 0, "Incorrect framebuffer value at row 5 column byte 3"); } #[test] fn sprites_xor_existing_framebuffer_values() { const SPRITE_START_ADDRESS: usize = 1046; const X_POS: u8 = 18; const Y_POS: u8 = 2; let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.i_register = SPRITE_START_ADDRESS as u16; hardware.gen_registers[4] = X_POS; hardware.gen_registers[3] = Y_POS; hardware.memory[SPRITE_START_ADDRESS] = 0b10101010; hardware.memory[SPRITE_START_ADDRESS + 1] = 0b01010101; hardware.memory[SPRITE_START_ADDRESS + 2] = 0b11001101; hardware.framebuffer[2][2] = 0xFF; hardware.framebuffer[2][3] = 0xFF; let instruction = Instruction::DrawSprite { x_register: Register::General(4), y_register: Register::General(3), height: 3, }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[0xf], 1, "Incorrect VF value"); assert_eq!(hardware.framebuffer[2][2], 0b00101010 ^ 0xFF, "Incorrect framebuffer value at row 2 column byte 2"); assert_eq!(hardware.framebuffer[2][3], 0b10000000 ^ 0xFF, "Incorrect framebuffer value at row 2 column byte 3"); assert_eq!(hardware.framebuffer[3][2], 0b00010101, "Incorrect framebuffer value at row 3 column byte 2"); assert_eq!(hardware.framebuffer[3][3], 0b01000000, "Incorrect framebuffer value at row 3 column byte 3"); assert_eq!(hardware.framebuffer[4][2], 0b00110011, "Incorrect framebuffer value at row 4 column byte 2"); assert_eq!(hardware.framebuffer[4][3], 0b01000000, "Incorrect framebuffer value at row 4 column byte 3"); assert_eq!(hardware.framebuffer[5][2], 0, "Incorrect framebuffer value at row 5 column byte 2"); assert_eq!(hardware.framebuffer[5][3], 0, "Incorrect framebuffer value at row 5 column byte 3"); } #[test] fn partially_visible_sprite_wraps_across_both_axis() { const SPRITE_START_ADDRESS: usize = 1046; const X_POS: u8 = 58; const Y_POS: u8 = 30; let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.i_register = SPRITE_START_ADDRESS as u16; hardware.gen_registers[4] = X_POS; hardware.gen_registers[3] = Y_POS; hardware.memory[SPRITE_START_ADDRESS] = 0b10101010; hardware.memory[SPRITE_START_ADDRESS + 1] = 0b01010101; hardware.memory[SPRITE_START_ADDRESS + 2] = 0b11001101; hardware.memory[SPRITE_START_ADDRESS + 3] = 0b11111111; let instruction = Instruction::DrawSprite { x_register: Register::General(4), y_register: Register::General(3), height: 3, }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[0xf], 0, "Incorrect VF value"); assert_eq!(hardware.framebuffer[30][7], 0b00101010, "Incorrect framebuffer value at row 30 column byte 7"); assert_eq!(hardware.framebuffer[30][0], 0b10000000, "Incorrect framebuffer value at row 30 column byte 0"); assert_eq!(hardware.framebuffer[31][7], 0b00010101, "Incorrect framebuffer value at row 31 column byte 7"); assert_eq!(hardware.framebuffer[31][0], 0b01000000, "Incorrect framebuffer value at row 31 column byte 0"); assert_eq!(hardware.framebuffer[0][7], 0b00110011, "Incorrect framebuffer value at row 0 column byte 7"); assert_eq!(hardware.framebuffer[0][0], 0b01000000, "Incorrect framebuffer value at row 0 column byte 0"); assert_eq!(hardware.framebuffer[1][7], 0, "Incorrect framebuffer value at row 1 column byte 7"); assert_eq!(hardware.framebuffer[1][0], 0, "Incorrect framebuffer value at row 1 column byte 0"); } #[test] fn can_set_gen_register_to_delay_timer_value() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[3] = 25; hardware.delay_timer = 50; let instruction = Instruction::LoadFromRegister { source: Register::DelayTimer, destination: Register::General(3), }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[3], 50, "Incorrect VX value"); assert_eq!(hardware.delay_timer, 50, "Incorrect delay timer value"); } #[test] fn can_set_delay_timer_to_value_in_general_register() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[3] = 25; hardware.delay_timer = 50; let instruction = Instruction::LoadFromRegister { source: Register::General(3), destination: Register::DelayTimer, }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[3], 25, "Incorrect VX value"); assert_eq!(hardware.delay_timer, 25, "Incorrect delay timer value"); } #[test] fn can_set_sound_timer_to_value_in_general_register() { let mut hardware = Hardware::new(); hardware.program_counter = 1000; hardware.gen_registers[3] = 25; hardware.sound_timer = 50; let instruction = Instruction::LoadFromRegister { source: Register::General(3), destination: Register::SoundTimer, }; execute_instruction(instruction, &mut hardware).unwrap(); assert_eq!(hardware.program_counter, 1002, "Incorrect program counter"); assert_eq!(hardware.gen_registers[3], 25, "Incorrect VX value"); assert_eq!(hardware.sound_timer, 25, "Incorrect delay timer value"); } }
true
b02f18df40f0853593c61d4e526fd341a4b168d3
Rust
kalaninja/data-structures
/week2_priority_queues_and_disjoint_sets/2_job_queue/rust/src/main.rs
UTF-8
3,274
3.5
4
[]
no_license
use std::io::stdin; use std::fmt::{self, Display, Formatter}; type ThreadId = u32; type ThreadTime = u64; #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] struct Thread { time_idle: ThreadTime, thread_id: ThreadId, } impl Thread { fn new(thread_id: ThreadId, time_idle: ThreadTime) -> Self { Thread { thread_id, time_idle } } } impl Display for Thread { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{} {}", self.thread_id, self.time_idle) } } #[derive(Debug)] struct ThreadQueue { data: Vec<Thread> } impl ThreadQueue { fn new(n: usize) -> Self { ThreadQueue { data: (0..n as ThreadId) .fold(Vec::with_capacity(n), |mut acc, i| { acc.push(Thread::new(i, 0)); acc }) } } fn peak(&self) -> &Thread { &self.data[0] } fn exec_task(&mut self, time: u32) { self.data[0].time_idle += time as u64; self.sift_down(0); } fn sift_down(&mut self, i: usize) { let mut cur_i = i; loop { let left = 2 * cur_i + 1; if left >= self.data.len() { break; } let right = 2 * cur_i + 2; let min = if right < self.data.len() && self.data[right] < self.data[left] { right } else { left }; if self.data[min] < self.data[cur_i] { self.data.swap(cur_i, min); cur_i = min; } else { break; } } } } fn main() { let n = read_line() .split_whitespace() .nth(0).unwrap() .parse().unwrap(); let t = read_line().trim() .split_whitespace() .map(|x| x.parse().unwrap()) .collect(); solve(n, t).iter().for_each(|x| println!("{}", x)); } fn solve(n: usize, tasks: Vec<u32>) -> Vec<Thread> { let mut threads = ThreadQueue::new(n); let mut result = Vec::with_capacity(tasks.len()); for time in tasks { result.push(*threads.peak()); threads.exec_task(time); } result } #[test] fn test_case_1() { let e = vec![ Thread::new(0, 0), Thread::new(1, 0), Thread::new(0, 1), Thread::new(1, 2), Thread::new(0, 4), ]; assert_eq!(solve(2, vec![1, 2, 3, 4, 5]), e); } #[test] fn test_case_2() { let e = vec![ Thread::new(0, 0), Thread::new(1, 0), Thread::new(2, 0), Thread::new(3, 0), Thread::new(0, 1), Thread::new(1, 1), Thread::new(2, 1), Thread::new(3, 1), Thread::new(0, 2), Thread::new(1, 2), Thread::new(2, 2), Thread::new(3, 2), Thread::new(0, 3), Thread::new(1, 3), Thread::new(2, 3), Thread::new(3, 3), Thread::new(0, 4), Thread::new(1, 4), Thread::new(2, 4), Thread::new(3, 4), ]; assert_eq!(solve(4, vec![1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), e); } fn read_line() -> String { let mut input = String::new(); stdin().read_line(&mut input).unwrap(); input }
true
ef1331be181b9020769930de3c4dcfc1ff3f1abd
Rust
MwlLj/rust-p2p
/exchange_service/src/enums/nat.rs
UTF-8
555
3.46875
3
[]
no_license
use std::cmp::PartialEq; #[derive(PartialEq, Debug, Clone)] pub enum Nat { Nat1 = 1, Nat2 = 2, Nat3 = 3, Nat4 = 4, NotNat4 = 5 } impl std::convert::From<u8> for Nat { fn from(item: u8) -> Self { match item { 1 => Nat::Nat1, 2 => Nat::Nat2, 3 => Nat::Nat3, 4 => Nat::Nat4, 5 => Nat::NotNat4, _ => Nat::Nat1 } } } // impl PartialEq for Nat { // fn eq(&self, other: &Nat) -> bool { // *self as u8 == *other as u8 // } // }
true
c18e0eec7aa060fe97fdb6dc292259a5da9e8088
Rust
leon2k2k2k/xi_pl
/xi-backends/py_backend/py_prim.rs
UTF-8
4,355
2.515625
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
use std::collections::BTreeMap; use xi_core::judgment::{Judgment, Primitive}; use xi_uuid::VarUuid; use crate::py_backend::py_output::{ make_var_name, promise_resolve, to_py_ident, to_py_num, to_py_str, Expr, }; use super::py_output::{to_py_app, to_py_ident1}; #[derive(Clone, PartialEq, Eq, Debug)] pub enum PyPrim { StringType, NumberType, StringElem(String), NumberElem(String), Ffi(String, String), Remote(String, String), Var(VarUuid), } impl Primitive for PyPrim { fn maybe_prim_type(&self) -> Option<Judgment<Self>> { use PyPrim::*; match self { StringType => Some(Judgment::u(None)), NumberType => Some(Judgment::u(None)), StringElem(_) => Some(Judgment::prim_wo_prim_type(StringType, None)), NumberElem(_) => Some(Judgment::prim_wo_prim_type(NumberType, None)), Ffi(_, _) => None, Var(_) => None, Remote(_, _) => None, } } } impl PyPrim { pub fn to_py_prim( &self, ffi: &mut BTreeMap<(String, String), VarUuid>, remote: &mut BTreeMap<(String, String), VarUuid>, ) -> Expr { match self { PyPrim::StringType => { promise_resolve(to_py_app(to_py_ident("prim"), vec![to_py_str("Str")])) } PyPrim::NumberType => { promise_resolve(to_py_app(to_py_ident("prim"), vec![to_py_str("Int")])) } PyPrim::StringElem(str) => promise_resolve(to_py_str(str.clone())), PyPrim::NumberElem(num) => promise_resolve(to_py_num(num.clone())), PyPrim::Ffi(filename, ffi_name) => { let var = match ffi.get(&(filename.clone(), ffi_name.clone())) { Some(var) => *var, None => { let var = VarUuid::new(); ffi.insert((filename.clone(), ffi_name.clone()), var); var } }; to_py_ident(format!("ffi{}", var.index())) } PyPrim::Remote(remote_address, remote_name) => { let var = match remote.get(&(remote_address.clone(), remote_name.clone())) { Some(var) => *var, None => { let var = VarUuid::new(); remote.insert((remote_address.clone(), remote_address.clone()), var); var } }; to_py_ident(format!("remote{}", var.index())) } PyPrim::Var(index) => to_py_ident1(make_var_name(index)), } } } #[derive(Clone, Debug)] pub struct PyModule { pub str_to_index: BTreeMap<String, VarUuid>, pub module_items: BTreeMap<VarUuid, PyModuleItem>, } #[derive(Clone, Debug)] pub struct PyModuleAndImports { pub module: PyModule, pub imports: BTreeMap<VarUuid, PyModuleAndImports>, } #[derive(Clone, Debug)] pub enum PyModuleItem { Define(PyDefineItem), // Import(JsImportItem), } impl PyModuleItem { pub fn type_(&self) -> Judgment<PyPrim> { match self { PyModuleItem::Define(define_item) => define_item.type_.clone(), // JsModuleItem::Import(import_item) => import_item.type_.clone(), } } pub fn transport_info(&self) -> TransportInfo { match self { PyModuleItem::Define(define_item) => define_item.transport_info.clone(), } } } #[derive(Clone, Debug)] pub struct PyDefineItem { pub name: String, pub transport_info: TransportInfo, pub type_: Judgment<PyPrim>, pub impl_: Judgment<PyPrim>, } #[derive(Clone, Debug)] pub struct TransportInfo { pub origin: Option<String>, pub transport: Option<String>, } impl TransportInfo { pub fn none() -> TransportInfo { TransportInfo { origin: None, transport: None, } } pub fn only_origin(origin: String) -> TransportInfo { TransportInfo { origin: Some(origin), transport: None, } } pub fn origin_and_transport(origin: String, tranport: String) -> TransportInfo { TransportInfo { origin: Some(origin), transport: Some(tranport), } } }
true
8be91f8a6314d1ee36682bf93fca8b5573a1dafd
Rust
SuperiorJT/mr-cd-projekt-red
/src/audio/receiver.rs
UTF-8
3,352
2.578125
3
[ "MIT" ]
permissive
use std::{ collections::HashMap, sync::Arc, sync::RwLock, time::{Instant, SystemTime, UNIX_EPOCH}, }; use config::{Config, File}; use serde::Deserialize; use serenity::model::id::UserId; use serenity::voice::AudioReceiver; use super::buffer::DiscordAudioBuffer; use super::DiscordAudioPacket; #[derive(Deserialize)] struct UserMixConfig { volume: f32, mute: bool, } impl Default for UserMixConfig { fn default() -> Self { Self { volume: 1.0, mute: false, } } } pub struct Receiver { buffer: Arc<RwLock<DiscordAudioBuffer>>, mix_config: HashMap<u64, UserMixConfig>, instant: Instant, } impl Receiver { pub fn new(buffer: Arc<RwLock<DiscordAudioBuffer>>) -> Self { let mut config = Config::new(); if let Err(err) = config.merge(File::with_name("config/mixer.json")) { error!("{} - Using empty config", err); } let mix_config = match config.try_into::<HashMap<u64, UserMixConfig>>() { Ok(c) => c, Err(_) => HashMap::new(), }; Self { buffer, mix_config, instant: Instant::now(), } } } impl AudioReceiver for Receiver { fn speaking_update(&mut self, ssrc: u32, user_id: u64, speaking: bool) { let mut buffer = match self.buffer.write() { Ok(buffer) => buffer, Err(why) => { error!("Could not get audio buffer lock: {:?}", why); return; } }; let volume = self.mix_config.entry(user_id).or_default().volume; buffer.update_track_mix(ssrc, (volume * f32::from(u8::max_value())) as u8); info!("Speaking Update: {}, {}, {}", user_id, ssrc, speaking); } fn voice_packet( &mut self, ssrc: u32, sequence: u16, _timestamp: u32, stereo: bool, data: &[i16], _compressed_size: usize, ) { // info!( // "Audio packet sequence {:05} has {:04} bytes, SSRC {}, is_stereo: {}", // sequence, // data.len() * 2, // ssrc, // stereo // ); // let since_the_epoch = SystemTime::now() // .duration_since(UNIX_EPOCH) // .expect("Time went backwards"); // let since_start = self.instant.elapsed().as_secs() // * u64::from(1000 + self.instant.elapsed().subsec_millis()); // let timestamp = since_the_epoch.as_secs() * 1000 + since_the_epoch.subsec_millis() as u64; // info!( // "Time: {}, Sequence: {}, ssrc: {}", // since_start, sequence, ssrc // ); // let mut buffer = match self.buffer.write() { // Ok(buffer) => buffer, // Err(why) => { // error!("Could not get audio buffer lock: {:?}", why); // return; // } // }; // buffer.insert_item(DiscordAudioPacket::new( // ssrc, // sequence, // timestamp, // stereo, // data.to_owned(), // )); // info!( // "Data Size: {}, Buffer Length: {}, Buffer Cap: {}", // data.len(), // buffer.size(), // buffer.capacity() // ); } }
true
e1257f2999b0a1a7a626edd92e68b001cded0b65
Rust
tonmanna/RustLearningFollowBookBeginer
/chapter2/src/tuples_sample3.rs
UTF-8
159
2.796875
3
[]
no_license
#[derive(Debug)] struct Matrix(f32, f32, f32, f32); pub fn tuples_sample_struct() { let matrix = Matrix(1.1,1.2,2.1,2.2); println!("{:?}", matrix); }
true
515021a225e189e61d7eab324be1137cab06e59b
Rust
shunty-gh/AdventOfCode2017
/day12/aoc2017-day12.rs
UTF-8
2,689
3.203125
3
[]
no_license
use std::io::prelude::*; use std::fmt; use std::io::BufReader; use std::fs::File; use std::path::Path; use std::env; /// Advent of Code 2017 /// Day 12 // compile with, for example: // $> rustc -g --out-dir ./bin aoc2017-day12.rs // or (providing the 'path' is set correctly in Cargo.toml): // $> cargo build fn main() { let args: Vec<String> = env::args().collect(); let inputname: &str; if args.len() > 1 { inputname = &args[1]; } else { inputname = "./aoc2017-day12.txt"; } let input = lines_from_file(inputname); let programs: Vec<Program> = input.iter() .map(|line| { let splits: Vec<&str> = line.split(" <-> ").collect(); Program { id: splits[0].to_string().parse::<usize>().unwrap(), connections: splits[1].to_string() .split(", ") .map(|s| s.parse::<usize>().unwrap()) .collect(), } }) .collect(); //println!("Programs: {:?}", programs); let mut visited: Vec<usize> = vec![]; let mut group_count = 0; let mut group_zero_count = 0; for program in &programs { let key = &program.id; if visited.contains(key) { continue; } group_count += 1; let mut to_visit: Vec<usize> = vec![*key]; while to_visit.len() > 0 { let current = to_visit.pop().unwrap(); if !visited.contains(&current) { visited.push(current); for conn in &programs[current].connections { if !visited.contains(conn) { to_visit.push(*conn); } } } } if *key == 0 { group_zero_count = visited.len(); } } assert!(programs.len() == visited.len(), "Number visited should equal total number of programs"); println!("Using {} as input", &inputname); println!("Num programs: {}", programs.len()); println!("Programs connected to P0 (part 1): {}", group_zero_count); println!("Number of groups (part 2): {}", group_count); } fn lines_from_file<P>(filename: P) -> Vec<String> where P: AsRef<Path>, { let file = File::open(filename).expect("no such file"); let buf = BufReader::new(file); buf.lines() .map(|l| l.expect("Could not parse line")) .collect() } struct Program { id: usize, connections: Vec<usize>, } impl fmt::Debug for Program { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Prog id: {}; Connections: {:?}", self.id, self.connections) } }
true
f5dff23875161835aebdb3f0e6a7dc725d3facee
Rust
KwinnerChen/rust_repo
/workspace_learning/complex/src/lib.rs
UTF-8
1,850
3.921875
4
[]
no_license
#![allow(dead_code)] use std::{fmt::{Display, Formatter, Result}, ops::Add, write}; /// 表示复数结构 #[derive(Debug, Default, PartialEq, Clone, Copy)] struct Complex<T> { re: T, im: T, } impl<T: Add<Output=T>> Complex<T> { /// 创建一个复数结构 /// # Example /// ``` /// use complex::Complex; /// let com = Complex::new(0, 0); /// assert_eq!(Complex{re:0, im:0}, com); ///``` /// # Panic! /// 只能由实现了Add trait的类型创建 fn new(re: T, im: T) -> Self { Self { re, im, } } } impl<T: Add<Output=T>> Add for Complex<T> { type Output = Self; fn add(self, other:Self) -> Self::Output { Self { re: self.re + other.re, im: self.im + other.im, } } } impl<T: Display> Display for Complex<T> { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{}+{}i", self.re, self.im) } } fn show_me(item: impl Display) { println!("{}", item); } #[cfg(test)] mod tests { #[derive(Debug, Clone)] struct Foo; use super::*; #[test] fn it_works() { let complex1 = Complex::new(3, 5); let complex2 = Complex::<i32>::default(); assert_eq!(complex1, complex1 + complex2); assert_eq!(complex1, Complex {re:3, im:5}); println!("{}", complex1); } #[test] fn do_work() { show_me("hello rust!"); } #[test] fn do_work_2() { let mut s1 = String::from("hello"); let s2 = &mut s1; s2.push_str("rust"); println!("{:?}", s2); } #[test] fn test_work_3() { let mut s = String::from("Hello Rust"); let a_mut_ref = &mut s; let a_mut_ref_2 = a_mut_ref; a_mut_ref_2.push_str("!"); println!("{}", &s); } }
true
c2115a876151368aae7cb2232eb1b815a0990de5
Rust
peterhj/libcpu_topo
/src/lib.rs
UTF-8
2,874
2.921875
3
[]
no_license
extern crate libc; use libc::*; //use std::collections::{HashSet}; use std::fs::{File}; use std::io::{BufRead, BufReader}; use std::mem::{size_of_val, uninitialized}; use std::path::{PathBuf}; //use std::process::{Command}; /*pub enum CpuLevel { Processor, Core, Thread, }*/ #[cfg(target_os = "linux")] pub fn set_affinity(thr_idxs: &[usize]) -> Result<(), ()> { unsafe { let mut cpuset = uninitialized(); CPU_ZERO(&mut cpuset); for &thr_idx in thr_idxs { CPU_SET(thr_idx, &mut cpuset); } let thread = pthread_self(); match pthread_setaffinity_np(thread, size_of_val(&cpuset), &cpuset as *const _) { 0 => Ok(()), _ => Err(()), } } } pub enum CpuTopologySource { Auto, LinuxProcCpuinfo, } #[derive(Debug)] pub struct CpuThreadInfo { pub thr_idx: usize, pub core_idx: usize, pub proc_idx: usize, } #[derive(Debug)] pub struct CpuTopology { pub threads: Vec<CpuThreadInfo>, } impl CpuTopology { pub fn query(source: CpuTopologySource) -> CpuTopology { match source { CpuTopologySource::Auto => { unimplemented!(); } CpuTopologySource::LinuxProcCpuinfo => { Self::query_proc_cpuinfo() } } } fn query_proc_cpuinfo() -> CpuTopology { let file = File::open(&PathBuf::from("/proc/cpuinfo")) .unwrap(); let reader = BufReader::new(file); //let mut thread_set = HashSet::new(); let mut threads = vec![]; let mut curr_thread = None; for line in reader.lines() { let line = line.unwrap(); if line.len() >= 9 && &line[ .. 9] == "processor" { let toks: Vec<_> = line.splitn(2, ":").collect(); // Not assuming processor numbers are consecutive. let thread_idx: usize = toks[1].trim().parse().unwrap(); //thread_set.insert(thread_idx); if let Some(info) = curr_thread { threads.push(info); } curr_thread = Some(CpuThreadInfo{ thr_idx: thread_idx, core_idx: 0, proc_idx: 0, }); } else if line.len() >= 7 && &line[ .. 7] == "core id" { let toks: Vec<_> = line.splitn(2, ":").collect(); let core_idx: usize = toks[1].trim().parse().unwrap(); if let Some(ref mut info) = curr_thread { info.core_idx = core_idx; } } else if line.len() >= 11 && &line[ .. 11] == "physical id" { let toks: Vec<_> = line.splitn(2, ":").collect(); let proc_idx: usize = toks[1].trim().parse().unwrap(); if let Some(ref mut info) = curr_thread { info.proc_idx = proc_idx; } } } if let Some(info) = curr_thread { threads.push(info); } //let num_threads = processor_set.len(); CpuTopology{ threads: threads, } } pub fn num_threads(&self) -> usize { self.threads.len() } }
true
fb51b6683054c4122e05bd60fe5ede509a3d103b
Rust
sbeckeriv/dex
/src/app/mod.rs
UTF-8
3,149
3.3125
3
[ "Apache-2.0", "MIT" ]
permissive
mod error; mod pokemon; mod style; use error::Error; use iced::{ button, Alignment, Application, Button, Column, Command, Container, Element, Length, Text, }; use pokemon::Pokemon; #[derive(Debug)] pub enum Pokedex { Loading, Loaded { pokemon: Pokemon, search: button::State, }, Errored { error: Error, try_again: button::State, }, } #[derive(Debug, Clone)] pub enum Message { PokémonFound(Result<Pokemon, Error>), Search, } impl Application for Pokedex { type Executor = iced::executor::Default; type Message = Message; type Flags = (); fn new(_flags: ()) -> (Self, Command<Message>) { ( Self::Loading, Command::perform(Pokemon::search(), Message::PokémonFound), ) } fn title(&self) -> String { let subtitle = match self { Self::Loading => "Loading", Self::Loaded { pokemon, .. } => &pokemon.name, Self::Errored { .. } => "Whoops!", }; format!("Pok\u{e9}dex - {}", subtitle) } fn update(&mut self, message: Message) -> Command<Message> { match message { Message::PokémonFound(Ok(pokemon)) => { *self = Self::Loaded { pokemon, search: button::State::new(), }; Command::none() } Message::PokémonFound(Err(error)) => { *self = Self::Errored { error, try_again: button::State::new(), }; Command::none() } Message::Search => { if let Self::Loading = self { Command::none() } else { *self = Self::Loading; Command::perform(Pokemon::search(), Message::PokémonFound) } } } } fn view(&mut self) -> Element<Message> { let content = match self { Self::Loading => Column::new() .width(Length::Shrink) .push(Text::new("Searching for Pok\u{e9}mon...").size(40)), Self::Loaded { pokemon, search } => Column::new() .max_width(500) .spacing(20) .align_items(Alignment::End) .push(pokemon.view()) .push(button(search, "Keep searching!").on_press(Message::Search)), Self::Errored { try_again, .. } => Column::new() .spacing(20) .align_items(Alignment::End) .push(Text::new("Whoops! Something went wrong...").size(40)) .push(button(try_again, "Try again").on_press(Message::Search)), }; Container::new(content) .width(Length::Fill) .height(Length::Fill) .center_x() .center_y() .into() } } fn button<'a>(state: &'a mut button::State, text: &str) -> Button<'a, Message> { Button::new(state, Text::new(text)) .padding(10) .style(style::Button::Primary) }
true
4f2ae26f3aacf1d4e12313867cd19177ef29110b
Rust
pitcer/brucket
/c-generator/src/syntax/c_struct.rs
UTF-8
3,141
3.140625
3
[ "MIT" ]
permissive
use crate::generator::{GeneratorError, GeneratorResult, GeneratorState, IndentedGenerator}; use crate::syntax::instruction::VariableDeclaration; use derive_more::Constructor; #[derive(Debug, PartialEq, Constructor)] pub struct CStruct { name: String, fields: Fields, } impl IndentedGenerator for CStruct { #[inline] fn generate_indented(self, state: &GeneratorState) -> GeneratorResult { let indentation = &state.indentation; let incremented_indentation = state.indentation.to_incremented(); let state = GeneratorState::new(incremented_indentation); Ok(format!( "{}struct {} {{\n{}\n{}}};", indentation, self.name, self.fields.generate_indented(&state)?, indentation )) } } pub type Fields = Vec<VariableDeclaration>; impl IndentedGenerator for Fields { #[inline] fn generate_indented(self, state: &GeneratorState) -> GeneratorResult { Ok(self .into_iter() .map(|field| field.generate_indented(state)) .collect::<Result<Vec<String>, GeneratorError>>()? .join("\n")) } } #[cfg(test)] mod test { use crate::syntax::c_type::{CPrimitiveType, CType}; use crate::syntax::modifiers::Modifier; use crate::syntax::TestResult; use super::*; #[test] fn test_generate_fields() -> TestResult { assert_eq!( "const int a;\nint b;\nint c;", vec![ VariableDeclaration::new( vec![Modifier::Const], CType::Primitive(CPrimitiveType::Int), "a".to_owned() ), VariableDeclaration::new( vec![], CType::Primitive(CPrimitiveType::Int), "b".to_owned() ), VariableDeclaration::new( vec![], CType::Primitive(CPrimitiveType::Int), "c".to_owned() ) ] .generate_indented(&GeneratorState::default())? ); Ok(()) } #[test] fn test_generate_struct() -> TestResult { assert_eq!( "struct foobar {\n const int a;\n int b;\n int c;\n};", CStruct::new( "foobar".to_owned(), vec![ VariableDeclaration::new( vec![Modifier::Const], CType::Primitive(CPrimitiveType::Int), "a".to_owned() ), VariableDeclaration::new( vec![], CType::Primitive(CPrimitiveType::Int), "b".to_owned() ), VariableDeclaration::new( vec![], CType::Primitive(CPrimitiveType::Int), "c".to_owned() ) ] ) .generate_indented(&GeneratorState::default())? ); Ok(()) } }
true
3ccef59cbe0cd896e9356a4fcf1d782c11ab34c2
Rust
naamancurtis/rust_data_structures_and_algorithms
/sorting/src/insertion_sort.rs
UTF-8
2,439
4.28125
4
[ "MIT" ]
permissive
//! # Insertion Sort //! //! Is a simple sorting algorithm that builds the sorted array one element at a time by maintaining a sorted //! sub-array into which elements are inserted. //! //! - Time Complexity: **O**(n<sup>2</sup>) //! - Space Complexity: **O**( _log_(n) ) use std::cmp::Ordering; /// Shorthand helper function which carries out sorting of a slice of `T` _where_ `T: Ord` /// /// # Examples /// ```rust /// use sorting::insertion_sort::insertion_sort; /// /// let mut arr = vec![37, 45, 29, 8]; /// insertion_sort(&mut arr); /// assert_eq!(arr, [8, 29, 37, 45]); /// ``` pub fn insertion_sort<T>(arr: &mut [T]) where T: Ord, { insertion_sort_by(arr, &|x, y| x.cmp(y)) } /// Carries out sorting of a slice of `T` using the provided comparator function `F` /// /// # Examples /// ```rust /// use sorting::insertion_sort::insertion_sort_by; /// /// let mut arr = vec![37, 45, 29, 8 ,10]; /// insertion_sort_by(&mut arr, &|x, y| x.cmp(y)); /// assert_eq!(arr, [8, 10, 29, 37, 45]); /// ``` pub fn insertion_sort_by<T, F>(arr: &mut [T], cmp: &F) where F: Fn(&T, &T) -> Ordering, { if arr.is_empty() { return; } for i in 1..arr.len() { for j in (1..=i).rev() { if cmp(&arr[j], &arr[j - 1]) == Ordering::Less { arr.swap(j, j - 1); } else { break; } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_semi_sorted() { let mut arr = vec![1, 23, 2, 32, 29, 33]; insertion_sort(&mut arr); assert_eq!(arr, [1, 2, 23, 29, 32, 33]); } #[test] fn test_backwards() { let mut arr = vec![50, 25, 10, 5, 1]; insertion_sort(&mut arr); assert_eq!(arr, [1, 5, 10, 25, 50]); } #[test] fn test_sorted() { let mut arr = vec![1, 5, 10, 25, 50]; insertion_sort(&mut arr); assert_eq!(arr, [1, 5, 10, 25, 50]); } #[test] fn test_empty() { let mut arr: Vec<u32> = vec![]; insertion_sort(&mut arr); assert_eq!(arr, []); } #[test] fn test_len_two() { let mut arr = vec![5, 1]; insertion_sort(&mut arr); assert_eq!(arr, [1, 5]); } #[test] fn test_partially_sorted() { let mut arr = vec![50, 75, 1, 1, 3, 4, 5, 6, 50]; insertion_sort(&mut arr); assert_eq!(arr, [1, 1, 3, 4, 5, 6, 50, 50, 75]); } }
true
75e6ec41d57b2b916e9b24178f790cd732015af3
Rust
Iwancof/SECR
/riscv-rust/src/terminal.rs
UTF-8
747
3.265625
3
[ "MIT" ]
permissive
/// Emulates terminal. It holds input/output data in buffer /// transferred to/from `Emulator`. pub trait Terminal { /// Puts an output ascii byte data to output buffer. /// The data is expected to be read by user program via `get_output()` /// and be displayed to user. fn put_byte(&mut self, value: u8); /// Gets an output ascii byte data from output buffer. /// This method returns zero if the buffer is empty. fn get_output(&mut self) -> u8; /// Puts an input ascii byte data to input buffer. /// The data is expected to be read by `Emulator` via `get_input()` /// and be handled. fn put_input(&mut self, data: u8); /// Gets an input ascii byte data from input buffer. /// Used by `Emulator`. fn get_input(&mut self) -> u8; }
true
722a7a33904b12f0f16d1119e7b861b533edc412
Rust
sirkibsirkib/middleman
/src/structs.rs
UTF-8
17,075
3.171875
3
[ "MIT" ]
permissive
use super::*; use mio::{ *, event::Evented, }; use ::std::{ io, io::{ Read, Write, ErrorKind, }, time, }; #[derive(Debug)] pub struct Middleman { stream: mio::net::TcpStream, buf: Vec<u8>, buf_occupancy: usize, payload_bytes: Option<u32>, } impl Middleman { fn check_payload(&mut self) { if self.payload_bytes.is_none() && self.buf_occupancy >= 4 { self.payload_bytes = Some( bincode::deserialize(&self.buf[..4]) .unwrap() ) } } /// Create a new Middleman structure to wrap the given Mio TcpStream. /// The Middleman implements `mio::Evented`, but delegates its functions to this given stream /// As such, registering the Middleman and registering the TcpStream are anaologous. pub fn new(stream: mio::net::TcpStream) -> Middleman { Self { stream: stream, buf: Vec::with_capacity(128), buf_occupancy: 0, payload_bytes: None, } } fn read_in(&mut self) -> Result<usize, io::Error> { let mut total = 0; loop { let limit = (self.buf_occupancy + 64) + (self.buf_occupancy); if self.buf.len() < limit { self.buf.resize(limit, 0u8); } match self.stream.read(&mut self.buf[self.buf_occupancy..]) { Ok(0) => return Ok(total), Ok(bytes) => { self.buf_occupancy += bytes; total += bytes; }, Err(ref e) if e.kind() == ErrorKind::WouldBlock => { return Ok(total); }, Err(e) => return Err(e), }; } } /// Write the given message directly into the TcpStream. Returns `Err` variant if there /// is a problem serializing or writing the message. The call returns Ok(()) once the bytes /// are entirely written to the stream. pub fn send<M: Message>(&mut self, m: &M) -> Result<(), SendError> { self.send_packed( & PackedMessage::new(m)? )?; Ok(()) } /// See `send`. This variant can be useful to /// avoid the overhead of repeatedly packing a message for whatever reason, eg: sending /// the same message using multiple Middleman structs. /// /// Note that this function does NOT check for internal consistency of the packed message. /// So, if this message was constructed by a means other than `Packed::new`, then the /// results may be unpredictable. pub fn send_packed(&mut self, msg: & PackedMessage) -> Result<(), io::Error> { self.stream.write_all(&msg.0) } /// Conume an iterator over some Message structs, sending them all in the order traversed (see `send`). /// Returns (a,b) where a gives the total number of messages sent successfully and where b is Ok if /// nothing goes wrong and an error otherwise. In the event of the first error, no more messages will be sent. pub fn send_all<'m, I, M>(&'m mut self, msg_iter: I) -> (usize, Result<(), SendError>) where M: Message + 'm, I: Iterator<Item = &'m M>, { let mut total = 0; for msg in msg_iter { match self.send(msg) { Ok(_) => total += 1, Err(e) => return (total, Err(e)), } } (total, Ok(())) } /// See `send_all` and `send_packed`. This uses the message iterator from the former and /// the packed messages from the latter. pub fn send_all_packed<'m, I>(&'m mut self, packed_msg_iter: I) -> (usize, Result<(), io::Error>) where I: Iterator<Item = &'m PackedMessage>, { let mut total = 0; for msg in packed_msg_iter { match self.send_packed(msg) { Ok(_) => total += 1, Err(e) => return (total, Err(e)), } } (total, Ok(())) } /// Attempt to dedserialize some data in the receiving buffer into a single /// complete structure with the given type M. If there is insufficient data /// at the moment, Ok(None) is returned. /// /// As the type is provided by the reader, it is possible for the sent /// message to be misinterpreted as a different type. At best, this is detected /// by a failure in deserialization. If an error occurs, the data is not consumed /// from the Middleman. Subsequent reads will operate on the same data. /// /// NOTE: The correctness of this call depends on the sender sending an _internally consistent_ /// `PackedMessage`. If you (or the sender) are manually manipulating the internal state of /// sent messages this may cause errors for the receiver. If you are sticking to the Middleman API /// and treating each `PackedMessage` as a black box, everything should be fine. pub fn recv<M: Message>(&mut self) -> Result<Option<M>, RecvError> { self.read_in()?; self.check_payload(); if let Some(pb) = self.payload_bytes { let buf_end = pb as usize + 4; if self.buf_occupancy >= buf_end { let decoded: M = bincode::deserialize( &self.buf[4..buf_end] )?; self.payload_bytes = None; self.buf.drain(0..buf_end); self.buf_occupancy -= buf_end; return Ok(Some(decoded)) } } Ok(None) } /// See `recv`. Will repeatedly call recv() until the next message is not yet ready. /// Recevied messages are placed into the buffer `dest_vector`. The return result is (a,b) /// where a is the total number of message successfully received and where b is OK(()) if all goes well /// and some Err otherwise. In the event of the first error, the call will return and not receive any further. pub fn recv_all_into<M: Message>(&mut self, dest_vector: &mut Vec<M>) -> (usize, Result<(), RecvError>) { let mut total = 0; loop { match self.recv::<M>() { Ok(None) => return (total, Ok(())), Ok(Some(msg)) => { dest_vector.push(msg); total += 1; }, Err(e) => return (total, Err(e)), }; } } /// Hijack the mio event loop, reading and writing to the socket as polling allows. /// Events not related to the recv() of this middleman (determined from the provided mio::Token) /// are pushed into the provided extra_events vector. Returns Ok(Some(_)) if a /// message was successfully received. May return Ok(None) if the user provides as timeout some // non-none Duration. Returns Err(_) if something goes wrong with reading from the socket or /// deserializing the message. See try_recv for more information. /// WARNING: The user should take care to iterate over these events also, as without them all the /// Evented objects registered with the provided poll object might experience lost wakeups. /// It is suggested that in the event of any recv_blocking calls in your loop, you extend the event /// loop with a drain() on the same vector passed here as extra_events (using the iterator chain function, for example.) pub fn recv_blocking<M: Message>(&mut self, poll: &Poll, events: &mut Events, my_tok: Token, extra_events: &mut Vec<Event>, mut timeout: Option<time::Duration>) -> Result<Option<M>, RecvError> { if let Some(msg) = self.recv::<M>()? { // trivial case. // message was already sitting in the buffer. return Ok(Some(msg)); } let started_at = time::Instant::now(); let mut res = None; loop { for event in events.iter() { let tok = event.token(); if res.is_none() && tok == my_tok { if ! event.readiness().is_readable() { continue; } // event is relevant! self.read_in()?; match self.recv::<M>() { Ok(Some(msg)) => { // got a message! res = Some(msg); }, Ok(None) => (), Err(e) => return Err(e), } } else { extra_events.push(event); } } if let Some(msg) = res { // message ready to go. Exiting loop return Ok(Some(msg)); } else { poll.poll(events, timeout).expect("poll() failed inside `recv_blocking()`"); if let Some(t) = timeout { // update remaining timeout let since = started_at.elapsed(); if since >= t { // ran out of time return Ok(None); } timeout = Some(t-since); } } } } /// See `recv_blocking`. This function is intended as an alternative for use /// for cases where it is _certain_ that this Middleman is the only registered `mio::Evented` /// for the provided `Poll` and `Events` objects. Thus, the call _WILL NOT CHECK_ the token at all, /// presuming that all events are associated with this middleman. pub fn recv_blocking_solo<M: Message>(&mut self, poll: &Poll, events: &mut Events, mut timeout: Option<time::Duration>) -> Result<Option<M>, RecvError> { if let Some(msg) = self.recv::<M>()? { // trivial case. // message was already sitting in the buffer. return Ok(Some(msg)); } let started_at = time::Instant::now(); loop { for event in events.iter() { if event.readiness().is_readable(){ // event is relevant! self.read_in()?; match self.recv::<M>() { Ok(Some(msg)) => return Ok(Some(msg)), Ok(None) => (), Err(e) => return Err(e), } } } poll.poll(events, timeout).expect("poll() failed inside `recv_blocking_solo()`"); if let Some(t) = timeout { // update remaining timeout let since = started_at.elapsed(); if since >= t { // ran out of time return Ok(None); } timeout = Some(t-since); } } } /// Similar to `recv_all_into`, but rather than storing each received message 'm', /// the provided function is called with arguments (self, m) where self is `&mut self`. /// This allows for ergonomic utility of the received messages using a closure. pub fn recv_all_map<F,M>(&mut self, mut func: F) -> (usize, Result<(), RecvError>) where M: Message, F: FnMut(&mut Self, M) + Sized { let mut total = 0; loop { match self.recv::<M>() { Ok(None) => return (total, Ok(())), Ok(Some(msg)) => { total += 1; func(self, msg) }, Err(e) => return (total, Err(e)), }; } } /// Combination of `recv_all_map` and `recv_packed`. pub fn recv_all_packed_map<F>(&mut self, mut func: F) -> (usize, Result<(), RecvError>) where F: FnMut(&mut Self, PackedMessage) + Sized { let mut total = 0; loop { match self.recv_packed() { Ok(None) => return (total, Ok(())), Ok(Some(packed)) => { total += 1; func(self, packed) }, Err(e) => return (total, Err(e)), }; } } /// Similar to `recv`, except builds (instead of some M: Message), a `PackedMessage` object. /// These packed messages can be deserialized later, sent on the line without knowledge of the /// message type etc. pub fn recv_packed(&mut self) -> Result<Option<PackedMessage>, RecvError> { self.read_in()?; self.check_payload(); if let Some(pb) = self.payload_bytes { let buf_end = pb as usize + 4; if self.buf_occupancy >= buf_end { let mut vec = self.buf.drain(0..buf_end) .collect::<Vec<_>>(); self.payload_bytes = None; self.buf_occupancy -= buf_end; return Ok(Some(PackedMessage(vec))) } } Ok(None) } /// Similar to `recv_packed`, but the potentially-read bytes are not actually removed /// from the stream. The message will _still be there_. pub fn peek_packed(&mut self) -> Result<Option<PackedMessage>, RecvError> { if let Some(pb) = self.payload_bytes { let buf_end = pb as usize + 4; if self.buf_occupancy >= buf_end { return Ok( Some( PackedMessage::from_raw( self.buf[4..buf_end].to_vec() ) ) ) } } Ok(None) } } /// This structure represents the serialized form of some `Message`-implementing structure. /// Dealing with a PackedMessage may be suitable when: /// (1) You need to send/store/receive a message but don't need to actually _use_ it yourself. /// (2) You want to serialize a message once, and send it multiple times. /// (3) You want to read and discard a message whose type is unknown. /// /// NOTE: The packed message maps 1:1 with the bytes that travel over the TcpStream. As such, /// packed messages also contain the 4-byte length preable. The user is discocuraged from /// manipulating the contents of a packed message. The `recv` statement relies on consistency /// of packed messages pub struct PackedMessage(Vec<u8>); impl PackedMessage { /// Create a new PakcedMessage from the given `Message`-implementing struct pub fn new<M: Message>(m: &M) -> Result<Self, PackingError> { let m_len: usize = bincode::serialized_size(&m)? as usize; if m_len > ::std::u32::MAX as usize { return Err(PackingError::TooBigToRepresent); } let tot_len = m_len+4; let mut vec = Vec::with_capacity(tot_len); vec.resize(tot_len, 0u8); bincode::serialize_into(&mut vec[0..4], &(m_len as u32))?; bincode::serialize_into(&mut vec[4..tot_len], m)?; Ok(PackedMessage(vec)) } /// Attempt to unpack this Packedmessage given a type hint. This may fail if the /// PackedMessage isn't internally consistent or the type doesn't match that /// of the type used for serialization. pub fn unpack<M: Message>(&self) -> Result<M, Box<bincode::ErrorKind>> { bincode::deserialize(&self.0[4..]) } /// Unwrap the byte buffer comprising this PackedMessage #[inline] pub fn into_raw(self) -> Vec<u8> { self.0 } /// Accept the given byte buffer as the basis for a PackedMessage /// /// WARNING: Use this at your own risk! The `recv` functions and their variants rely on /// the correct contents of messages to work correcty. /// /// NOTE: The first 4 bytes of a the buffer are used to store the length of the payload. #[inline] pub fn from_raw(v: Vec<u8>) -> Self { PackedMessage(v) } /// Return the number of bytes this packed message contains. Maps 1:1 with /// the bit complexity of the message sent over the network. #[inline] pub fn byte_len(&self) -> usize { self.0.len() } /// Acquire an immutable reference to the internal buffer of the packed message. #[inline] pub fn get_raw(&self) -> &Vec<u8> { &self.0 } /// Acquire a mutable reference to the internal buffer of the packed message. /// /// WARNING: Contents of a PackedMessage represent a delicata internal state. Sending an /// internally inconsistent PackedMessage will compromise the connection. Use at your own risk! #[inline] pub fn get_mut_raw(&mut self) -> &mut Vec<u8> { &mut self.0 } } impl Evented for Middleman { fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { self.stream.register(poll, token, interest, opts) } fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { self.stream.reregister(poll, token, interest, opts) } fn deregister(&self, poll: &Poll) -> io::Result<()> { self.stream.deregister(poll) } }
true
534738c930cb9798e38a845fb74c54ebbf1b5704
Rust
gengteng/impl-leetcode-for-rust
/src/three_sum.rs
UTF-8
1,618
3.859375
4
[ "MIT" ]
permissive
/// # 15. 3Sum /// /// Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. /// /// # Note: /// /// The solution set must not contain duplicate triplets. /// /// # Example: /// /// Given array nums = [-1, 0, 1, 2, -1, -4], /// /// A solution set is: /// [ /// [-1, 0, 1], /// [-1, -1, 2] /// ] /// use std::collections::HashSet; pub trait ThreeSum { fn three_sum(nums: &[i32]) -> HashSet<[i32;3]>; } pub struct Solution1; impl ThreeSum for Solution1 { fn three_sum(nums: &[i32]) -> HashSet<[i32;3]> { let mut result = HashSet::new(); for (i, a) in nums.iter().enumerate() { for (j, b) in nums.iter().skip(i + 1).enumerate() { for c in nums.iter().skip(i + j + 2) { if a + b + c == 0 { let mut v = [*a, *b, *c]; v.sort(); result.insert(v); } } } } result } } #[cfg(test)] mod test { use super::ThreeSum; use test::Bencher; use super::Solution1; #[test] fn test_solution1() { use std::collections::HashSet; assert_eq!(Solution1::three_sum(&[-1, 0, 1, 2, -1, -4]), { let mut result = HashSet::new(); result.insert([-1, 0, 1]); result.insert([-1, -1, 2]); result }); } #[bench] fn bench_solution1(b: &mut Bencher) { b.iter(|| Solution1::three_sum(&[-1, 0, 1, 2, -1, -4])); } }
true
025a08ef28a850e3a7ede38d3f00a1b48980fc47
Rust
rusty-ecma/resast
/src/pat.rs
UTF-8
2,954
3.265625
3
[]
no_license
use crate::expr::{Expr, Prop}; use crate::{Ident, IntoAllocated}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; /// All of the different ways you can declare an identifier /// and/or value #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub enum Pat<T> { Ident(Ident<T>), Obj(ObjPat<T>), Array(Vec<Option<ArrayPatPart<T>>>), RestElement(Box<Pat<T>>), Assign(AssignPat<T>), } impl<T> IntoAllocated for Pat<T> where T: ToString, { type Allocated = Pat<String>; fn into_allocated(self) -> Self::Allocated { match self { Pat::Ident(inner) => Pat::Ident(inner.into_allocated()), Pat::Obj(inner) => Pat::Obj(inner.into_iter().map(|a| a.into_allocated()).collect()), Pat::Array(inner) => Pat::Array( inner .into_iter() .map(|o| o.map(|a| a.into_allocated())) .collect(), ), Pat::RestElement(inner) => Pat::RestElement(inner.into_allocated()), Pat::Assign(inner) => Pat::Assign(inner.into_allocated()), } } } impl<T> Pat<T> { pub fn ident_from(inner: T) -> Self { Self::Ident(Ident { name: inner }) } } #[derive(PartialEq, Debug, Clone)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub enum ArrayPatPart<T> { Pat(Pat<T>), Expr(Expr<T>), } impl<T> IntoAllocated for ArrayPatPart<T> where T: ToString, { type Allocated = ArrayPatPart<String>; fn into_allocated(self) -> Self::Allocated { match self { ArrayPatPart::Pat(inner) => ArrayPatPart::Pat(inner.into_allocated()), ArrayPatPart::Expr(inner) => ArrayPatPart::Expr(inner.into_allocated()), } } } /// similar to an `ObjectExpr` pub type ObjPat<T> = Vec<ObjPatPart<T>>; /// A single part of an ObjectPat #[derive(PartialEq, Debug, Clone)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub enum ObjPatPart<T> { Assign(Prop<T>), Rest(Box<Pat<T>>), } impl<T> IntoAllocated for ObjPatPart<T> where T: ToString, { type Allocated = ObjPatPart<String>; fn into_allocated(self) -> Self::Allocated { match self { ObjPatPart::Assign(inner) => ObjPatPart::Assign(inner.into_allocated()), ObjPatPart::Rest(inner) => ObjPatPart::Rest(inner.into_allocated()), } } } /// An assignment as a pattern #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub struct AssignPat<T> { pub left: Box<Pat<T>>, pub right: Box<Expr<T>>, } impl<T> IntoAllocated for AssignPat<T> where T: ToString, { type Allocated = AssignPat<String>; fn into_allocated(self) -> Self::Allocated { AssignPat { left: self.left.into_allocated(), right: self.right.into_allocated(), } } }
true
2eb8609523eddcfcf9aaec109460477cbf7759ea
Rust
dan-sf/advent_of_code
/2018/day2/solution2.rs
UTF-8
1,131
3.21875
3
[]
no_license
use std::fs; use std::io; use std::io::BufRead; fn get_common_chars(box_one: &String, box_two: &String) -> String { box_one.chars() .zip(box_two.chars()) .filter(|ch| ch.0 == ch.1) .map(|ch| ch.0) .collect() } fn find_common_id() -> Option<String> { let input = fs::File::open("input.txt") .expect("Something went wrong reading the file"); let reader = io::BufReader::new(input); let mut box_ids: Vec<String> = reader.lines().map(|l| l.unwrap()).collect(); box_ids.sort(); for i in 0..box_ids.len() { let mut diff = 0; if i != box_ids.len() - 1 { for (a, b) in box_ids[i].chars().zip(box_ids[i+1].chars()) { if a != b { diff += 1; } } if diff == 1 { return Some(get_common_chars(&box_ids[i], &box_ids[i+1])); } } } None } fn main() { println!("Common letters in the box ids: {}", match find_common_id() { Some(s) => s, None => "NA".to_string() }); }
true
e13c33e5a575f4ab435f01914a81c74b1033ae9a
Rust
xiaolang315/json-schema-to-c
/src/main.rs
UTF-8
1,037
2.90625
3
[ "MIT" ]
permissive
// use std::process::Command; use std::fs::read_to_string; use std::fs::write; use serde_json::from_str; use serde_json::{Value}; fn make_str(body:String)->String { let head = String::from(r#" #ifdef __cplusplus extern "C" { #endif "#); let tail = String::from(r#" #ifdef __cplusplus } #endif "#); return head + &body + &tail; } fn main() { // let mut echo_hello = Command::new("sh"); // let ret = echo_hello.arg("-c").arg("ls").output(); // println!("结果:{:?}",ret); // let file = File::open( "./src/schema.json").unwrap(); // println!("文件打开成功:{:?}",file); let contents:String = read_to_string("./src/schema.json").unwrap(); let v: Value = from_str(&contents).unwrap(); println!("Please call {} at the number {}", v["type"], v["id"]); let body = String::from(r#" typedef struct All{ char name[100]; int value; }All ; All parser_print(const char* str); "#); write("./src/demo.h", make_str(body)) .unwrap(); } #[test] fn test(){ }
true
27c9d7ded1cb3ebf884c97949751989c6f27c507
Rust
rudib/axess
/axess_gui/src/windows/keyboard.rs
UTF-8
6,231
3.109375
3
[ "MIT" ]
permissive
use std::{borrow::Cow, fmt::Display}; use axess_core::payload::{DeviceState, UiPayload}; use packed_struct::PrimitiveEnum; use crate::config::AxessConfiguration; #[derive(Debug, Copy, Clone)] pub enum UiEvent { KeyDown(usize, u32), KeyUp(usize, u32) } #[derive(Default, Debug)] pub struct KeyboardState { ctrl: bool } #[derive(Debug, Copy, Clone)] pub enum KeyboardCombination { Key(usize), CtrlKey(usize) } impl KeyboardState { pub fn handle_event(&mut self, ev: &UiEvent) -> Option<KeyboardCombination> { const CTRL: usize = 0x11; //const ALT: usize = 0x12; match *ev { UiEvent::KeyDown(CTRL, _) => { self.ctrl = true; } UiEvent::KeyUp(CTRL, _) => { self.ctrl = false; } UiEvent::KeyDown(k, _) => { // todo: ignore repeats? if self.ctrl { return Some(KeyboardCombination::CtrlKey(k)); } else { return Some(KeyboardCombination::Key(k)); } }, UiEvent::KeyUp(_, _) => {} } None } } #[derive(Debug, Copy, Clone, PartialEq, PrimitiveEnum)] pub enum Keys { Enter = 13, PageUp = 33, PageDown = 34, Space = 32, Tab = 9, Number0 = 48, Number1 = 49, Number2 = 50, Number3 = 51, Number4 = 52, Number5 = 53, Number6 = 54, Number7 = 55, Number8 = 56, Number9 = 57, Fn1 = 0x70, Fn2 = 0x71, Fn3 = 0x72, Fn4 = 0x73, Fn5 = 0x74, Fn6 = 0x75, Fn7 = 0x76, Fn8 = 0x77, Fn9 = 0x78, Fn10 = 0x79, Fn11 = 0x7A, Fn12 = 0x7B, Fn13 = 0x7C, Fn14 = 0x7D, Fn15 = 0x7E, Fn16 = 0x7F } impl Display for Keys { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let str = match self { Keys::Number0 => "0", Keys::Number1 => "1", Keys::Number2 => "2", Keys::Number3 => "3", Keys::Number4 => "4", Keys::Number5 => "5", Keys::Number6 => "6", Keys::Number7 => "7", Keys::Number8 => "8", Keys::Number9 => "9", Keys::PageUp => "Page Up", Keys::PageDown => "Page Down", Keys::Fn1 => "F1", Keys::Fn2 => "F2", Keys::Fn3 => "F3", Keys::Fn4 => "F4", Keys::Fn5 => "F5", Keys::Fn6 => "F6", Keys::Fn7 => "F7", Keys::Fn8 => "F8", Keys::Fn9 => "F9", Keys::Fn10 => "F10", Keys::Fn11 => "F11", Keys::Fn12 => "F12", Keys::Fn13 => "F13", Keys::Fn14 => "F14", Keys::Fn15 => "F15", Keys::Fn16 => "F16", _ => { return f.write_fmt(format_args!("{:?}", self)); } }; f.write_str(str) } } #[derive(Debug, Clone)] pub struct KeyboardShortcut { pub key: KeyboardShortcutKey, pub command_description: Cow<'static, str>, pub command: ShortcutCommand } #[derive(Debug, Copy, Clone, PartialEq)] pub enum KeyboardShortcutKey { Key(Keys), CtrlKey(Keys) } impl Display for KeyboardShortcutKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { KeyboardShortcutKey::Key(k) => { k.fmt(f) } KeyboardShortcutKey::CtrlKey(k) => { f.write_str("Ctrl + ")?; k.fmt(f) } } } } #[derive(Debug, Clone)] pub enum ShortcutCommand { UiPayload(UiPayload), SelectPresetOrScene } pub fn get_main_keyboard_shortcuts(config: &AxessConfiguration) -> Vec<KeyboardShortcut> { let mut s = vec![ KeyboardShortcut { key: KeyboardShortcutKey::Key(Keys::Enter), command_description: "Select the preset or scene".into(), command: ShortcutCommand::SelectPresetOrScene } ]; if config.keyboard_shortcuts_axe_edit { s.push(KeyboardShortcut { key: KeyboardShortcutKey::CtrlKey(Keys::PageUp), command_description: "Preset Up".into(), command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: 1 })) }); s.push(KeyboardShortcut { key: KeyboardShortcutKey::CtrlKey(Keys::PageDown), command_description: "Preset Down".into(), command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: -1 })) }); for i in 0..8 { let key = Keys::from_primitive(Keys::Number1.to_primitive() + i); if let Some(key) = key { s.push(KeyboardShortcut { key: KeyboardShortcutKey::CtrlKey(key), command_description: format!("Select Scene {}", i + 1).into(), command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::SetScene { scene: i })) }); } } } if config.keyboard_shortcuts_presets_and_scenes_function_keys { for i in 0..8 { let key = Keys::from_primitive(Keys::Fn1.to_primitive() + i); if let Some(key) = key { s.push(KeyboardShortcut { key: KeyboardShortcutKey::Key(key), command_description: format!("Select Scene {}", i + 1).into(), command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::SetScene { scene: i })) }); } } s.push(KeyboardShortcut { key: KeyboardShortcutKey::Key(Keys::Fn11), command_description: "Preset Down".into(), command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: -1 })) }); s.push(KeyboardShortcut { key: KeyboardShortcutKey::Key(Keys::Fn12), command_description: "Preset Up".into(), command: ShortcutCommand::UiPayload(UiPayload::DeviceState(DeviceState::DeltaPreset { delta: 1 })) }); } s }
true
d8f7063a021efc499a4e1676623450e539b4a860
Rust
simon-whitehead/tetrs
/src/game/scoring/score.rs
UTF-8
1,983
2.859375
3
[ "MIT" ]
permissive
use piston_window::{Graphics, Transformed}; use piston_window::character::CharacterCache; use game::config::Config; use game::render_options::RenderOptions; pub struct Score { score: u32, location: (f64, f64), color: [f32; 4], font_size: u32, } impl Score { pub fn new(config: &Config) -> Score { Score { score: 0, location: (320.0, 29.0), color: config.ui_color, font_size: 16, } } pub fn add(&mut self, value: u32) { self.score += value; } pub fn render<'a, C, G>(&self, options: &mut RenderOptions<'a, G, C>) where C: CharacterCache, G: Graphics<Texture = <C as CharacterCache>::Texture> { let score_label_transform = options.context .transform .trans(self.location.0 as f64, self.location.1 as f64); let score_number_transform = options.context .transform .trans(self.location.0 as f64, self.location.1 + (self.font_size + (self.font_size / 3)) as f64); let score = format!("{}", self.score); ::piston_window::Text::new_color(self.color, self.font_size - (self.font_size / 3)) .draw("Score", options.character_cache, &options.context.draw_state, score_label_transform, options.graphics); ::piston_window::Text::new_color(self.color, self.font_size).draw(&score[..], options.character_cache, &options.context .draw_state, score_number_transform, options.graphics); } }
true
fe91a6ee5a258a2447a117eae677decb355d72c6
Rust
enso-org/enso
/lib/rust/ensogl/component/text/src/buffer/rope/formatted.rs
UTF-8
2,010
3.375
3
[ "AGPL-3.0-only", "Apache-2.0", "AGPL-3.0-or-later" ]
permissive
//! A rope (efficient text representation) with formatting information. use crate::prelude::*; use crate::buffer::formatting::Formatting; use crate::buffer::formatting::FormattingCell; use enso_text::Rope; use enso_text::RopeCell; // ===================== // === FormattedRope === // ===================== /// A rope (efficient text representation) with formatting information. #[derive(Clone, CloneRef, Debug, Default, Deref)] pub struct FormattedRope { data: Rc<FormattedRopeData>, } impl FormattedRope { /// Constructor. pub fn new() -> Self { default() } /// Replace the content of the buffer with the provided text. pub fn replace(&self, range: impl enso_text::RangeBounds, text: impl Into<Rope>) { let text = text.into(); let range = self.crop_byte_range(range); let size = text.last_byte_index(); self.text.replace(range, text); self.formatting.set_resize_with_default(range, size); } } // ========================= // === FormattedRopeData === // ========================= /// Internal data of `FormattedRope`. #[derive(Debug, Default, Deref)] pub struct FormattedRopeData { #[deref] pub(crate) text: RopeCell, pub(crate) formatting: FormattingCell, } impl FormattedRopeData { /// Constructor. pub fn new() -> Self { default() } /// Rope getter. pub fn text(&self) -> Rope { self.text.get() } /// Rope setter. pub fn set_text(&self, text: impl Into<Rope>) { self.text.set(text); } /// Formatting getter. pub fn style(&self) -> Formatting { self.formatting.get() } /// Formatting setter. pub fn set_style(&self, style: Formatting) { self.formatting.set(style) } /// Query style information for the provided range. pub fn sub_style(&self, range: impl enso_text::RangeBounds) -> Formatting { let range = self.crop_byte_range(range); self.formatting.sub(range) } }
true
3df1d52edb3fc2c5ab768b76f40b288745bc7613
Rust
rust-cc/rcmath
/src/utils.rs
UTF-8
576
3.265625
3
[ "Apache-2.0", "MIT" ]
permissive
#[derive(Debug)] pub struct BitIterator<E> { t: E, n: usize, } impl<E: AsRef<[u64]>> BitIterator<E> { pub fn new(t: E) -> Self { let n = t.as_ref().len() * 64; BitIterator { t, n } } } impl<E: AsRef<[u64]>> Iterator for BitIterator<E> { type Item = bool; fn next(&mut self) -> Option<bool> { if self.n == 0 { None } else { self.n -= 1; let part = self.n / 64; let bit = self.n - (64 * part); Some(self.t.as_ref()[part] & (1 << bit) > 0) } } }
true