{ // 获取包含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 root_link = ROOT_LINK,\n code = s.to_u16(),\n msg = msg\n ),\n ));\n resp.headers.set(headers::ContentType::html());\n resp\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134095,"cells":{"blob_id":{"kind":"string","value":"819704e6173ae6b4ae33a8c6260086c26682f477"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"dansoper/adventofcode"},"path":{"kind":"string","value":"/2021/day24/src/main.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":1990,"string":"1,990"},"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 derive_new::new;\n\nconst DATA: &str = include_str!(\"input.txt\");\n\n// WOW I need to get to know what this does!\n// Credit: https://github.com/Crazytieguy/advent-2021/blob/master/src/bin/day24/main.rs\n// I got my answer, and the plan was to try and understand it, but then I ran out of time\n\nfn main() {\n println!(\"part a: {}\", part_a(DATA));\n println!(\"part b: {}\", part_b(DATA));\n}\n\n#[derive(Debug, Clone, Copy)]\nstruct StepParams {\n do_cmp: bool,\n cmp_now: i8,\n cmp_later: i8,\n}\n\n#[allow(clippy::needless_range_loop)]\nfn parse(data: &'static str) -> [StepParams; 14] {\n let lines: Vec<_> = data.lines().collect();\n let mut params = [None; 14];\n let get_param = |line_id: usize| lines[line_id].rsplit_once(' ').unwrap().1.parse().unwrap();\n for i in 0..14 {\n params[i] = Some(StepParams {\n do_cmp: get_param(i * 18 + 4) == 26,\n cmp_now: get_param(i * 18 + 5),\n cmp_later: get_param(i * 18 + 15),\n })\n }\n params.map(Option::unwrap)\n}\n\n#[derive(Debug, new, Clone, Copy)]\nstruct Rule {\n cmp_to: usize,\n val: i8,\n}\n\nfn get_rules(params: [StepParams; 14]) -> [Rule; 14] {\n let mut cmp_stack = Vec::new();\n let mut rules = [None; 14];\n for (i, step_params) in params.iter().enumerate() {\n if step_params.do_cmp {\n let Rule { cmp_to, val } = cmp_stack.pop().unwrap();\n rules[i] = Some(Rule::new(cmp_to, val + step_params.cmp_now));\n rules[cmp_to] = Some(Rule::new(i, -val - step_params.cmp_now));\n } else {\n cmp_stack.push(Rule::new(i, step_params.cmp_later))\n }\n }\n rules.map(Option::unwrap)\n}\n\nfn part_a(data: &'static str) -> String {\n let params = parse(data);\n let rules = get_rules(params);\n rules.map(|r| 9.min(9 + r.val).to_string()).concat()\n}\n\nfn part_b(data: &'static str) -> String {\n let params = parse(data);\n let rules = get_rules(params);\n rules.map(|r| 1.max(1 + r.val).to_string()).concat()\n}"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134096,"cells":{"blob_id":{"kind":"string","value":"3a7abda85426083b2a64cd438ee19eb541fe6b4d"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"nymtech/nym"},"path":{"kind":"string","value":"/common/bin-common/src/version_checker/mod.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2435,"string":"2,435"},"score":{"kind":"number","value":2.84375,"string":"2.84375"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["CC0-1.0","Apache-2.0"],"string":"[\n \"CC0-1.0\",\n \"Apache-2.0\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"// Copyright 2021 - Nym Technologies SA \n// SPDX-License-Identifier: Apache-2.0\n\nuse semver::SemVerError;\npub use semver::Version;\n\n/// Checks whether given `version` is compatible with a given semantic version requirement `req`\n/// according to major-minor semver rules. The semantic version requirement can be passed as a full,\n/// concrete version number, because that's what we'll have in our Cargo.toml files (e.g. 0.3.2).\n/// The patch number in the requirement gets dropped and replaced with a wildcard (0.3.*) as all\n/// minor versions should be compatible with each other.\npub fn is_minor_version_compatible(version: &str, req: &str) -> bool {\n let expected_version = match Version::parse(version) {\n Ok(v) => v,\n Err(_) => return false,\n };\n let req_version = match Version::parse(req) {\n Ok(v) => v,\n Err(_) => return false,\n };\n\n expected_version.major == req_version.major && expected_version.minor == req_version.minor\n}\n\npub fn parse_version(raw_version: &str) -> Result {\n Version::parse(raw_version)\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn version_0_3_0_is_compatible_with_requirement_0_3_x() {\n assert!(is_minor_version_compatible(\"0.3.0\", \"0.3.2\"));\n }\n\n #[test]\n fn version_0_3_1_is_compatible_with_minimum_requirement_0_3_x() {\n assert!(is_minor_version_compatible(\"0.3.1\", \"0.3.2\"));\n }\n\n #[test]\n fn version_0_3_2_is_compatible_with_minimum_requirement_0_3_x() {\n assert!(is_minor_version_compatible(\"0.3.2\", \"0.3.0\"));\n }\n\n #[test]\n fn version_0_2_0_is_not_compatible_with_requirement_0_3_x() {\n assert!(!is_minor_version_compatible(\"0.2.0\", \"0.3.2\"));\n }\n\n #[test]\n fn version_0_4_0_is_not_compatible_with_requirement_0_3_x() {\n assert!(!is_minor_version_compatible(\"0.4.0\", \"0.3.2\"));\n }\n\n #[test]\n fn version_1_3_2_is_not_compatible_with_requirement_0_3_x() {\n assert!(!is_minor_version_compatible(\"1.3.2\", \"0.3.2\"));\n }\n\n #[test]\n fn version_0_4_0_rc_1_is_compatible_with_version_0_4_0_rc_1() {\n assert!(is_minor_version_compatible(\"0.4.0-rc.1\", \"0.4.0-rc.1\"));\n }\n\n #[test]\n fn returns_false_on_foo_version() {\n assert!(!is_minor_version_compatible(\"foo\", \"0.3.2\"));\n }\n\n #[test]\n fn returns_false_on_bar_version() {\n assert!(!is_minor_version_compatible(\"0.3.2\", \"bar\"));\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134097,"cells":{"blob_id":{"kind":"string","value":"b7b38b4a0ce376f633701c711996102dc82d7acd"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Robbe7730/MCRust"},"path":{"kind":"string","value":"/src/server/entity.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":442,"string":"442"},"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 crate::player::Player;\n\nuse crate::error_type::ErrorType;\n\n#[derive(Clone)]\npub enum Entity {\n PlayerEntity(Player),\n}\n\nimpl Entity {\n pub fn as_player(&self) -> Result<&Player, ErrorType> {\n match self {\n Entity::PlayerEntity(p) => Ok(p),\n }\n }\n\n pub fn as_player_mut(&mut self) -> Result<&mut Player, ErrorType> {\n match self {\n Entity::PlayerEntity(p) => Ok(p),\n }\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134098,"cells":{"blob_id":{"kind":"string","value":"b4b9db9178604f55632ef7613060f5664fe56d1c"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Ale0x78/rust-minecraft-proxy"},"path":{"kind":"string","value":"/src/config.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":2828,"string":"2,828"},"score":{"kind":"number","value":3,"string":"3"},"int_score":{"kind":"number","value":3,"string":"3"},"detected_licenses":{"kind":"list like","value":["MIT"],"string":"[\n \"MIT\"\n]"},"license_type":{"kind":"string","value":"permissive"},"text":{"kind":"string","value":"use serde::{Deserialize, Serialize};\nuse std::collections::BTreeMap;\nuse std::default::Default;\nuse std::fs;\nuse std::path::Path;\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct MOTD {\n text: String,\n protocol_name: String,\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct Server {\n pub(crate) ip: String,\n\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct UnknownHost {\n kick_message: String,\n motd: MOTD\n}\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\npub struct Config {\n listen_addr: String,\n unknown_host: UnknownHost,\n hosts: BTreeMap\n}\n\nimpl Default for Config {\n fn default() -> Self {\n\n let unknown_host = UnknownHost {\n kick_message: \"§bRust Minecraft Proxy\\n\\n§cInvalid Address\".to_string(),\n motd: MOTD { text: \"§cUnknown host!\\n§7Please use a valid address to connect.\".to_string(), protocol_name: \"§crust-minecraft-proxy\".to_string() }\n };\n\n let mut hosts: BTreeMap = BTreeMap::new();\n hosts.insert(\"hub.example.com\".to_string(), Server { ip: \"127.0.0.1:35560\".to_string() });\n hosts.insert(\"minigame.example.com\".to_string(), Server { ip: \"127.0.0.1:25561\".to_string() });\n\n Self {\n listen_addr: \"0.0.0.0:25565\".to_string(),\n unknown_host,\n hosts\n }\n }\n}\n\nimpl Config {\n pub fn load_or_init(path: &Path) -> Config {\n if path.exists() {\n serde_yaml::from_str(&fs::read_to_string(path).unwrap()).unwrap()\n } else {\n info!(\"Configuration file does not exist. Use defaults.\");\n let default = Config::default();\n trace!(\"Default configuration: {:?}\", default);\n let string = serde_yaml::to_string(&default).unwrap();\n fs::write(path, &string).unwrap();\n default\n }\n }\n\n pub fn get_unknown_host_kick_msg(&self) -> String {\n let mut message: String = \"{\\\"text\\\":\\\"\".to_owned();\n message.push_str(&self.unknown_host.kick_message);\n message.push_str(\"\\\"}\");\n message\n }\n\n pub fn get_unknown_host_motd(&self) -> String {\n let mut motd: String = \"{\\\"version\\\": {\\\"name\\\": \\\"\".to_owned();\n motd.push_str(&self.unknown_host.motd.protocol_name);\n motd.push_str(\"\\\", \\\"protocol\\\": -1 }, \\\"players\\\": {\\\"max\\\": 0, \\\"online\\\": 0, \\\"sample\\\": [] }, \\\"description\\\": { \\\"text\\\": \\\"\");\n motd.push_str(&self.unknown_host.motd.text);\n motd.push_str(\"\\\" }}\");\n motd\n }\n\n pub fn get_listen_addr(&self) -> &str {\n &self.listen_addr\n }\n\n pub fn get_hosts(&self) -> &BTreeMap {\n &self.hosts\n }\n\n pub fn get_addr_by_host(&self, host: &str) -> Option<&Server> {\n self.hosts.get(host)\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}},{"rowIdx":1134099,"cells":{"blob_id":{"kind":"string","value":"4414fd05d1601c2fffc98389983f15eea08d0773"},"language":{"kind":"string","value":"Rust"},"repo_name":{"kind":"string","value":"Krishnacore/move-tools"},"path":{"kind":"string","value":"/lang/decompiler/src/types.rs"},"src_encoding":{"kind":"string","value":"UTF-8"},"length_bytes":{"kind":"number","value":4911,"string":"4,911"},"score":{"kind":"number","value":2.84375,"string":"2.84375"},"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::generics::Generic;\nuse crate::Encode;\nuse std::fmt::Write;\nuse anyhow::Error;\nuse crate::imports::{Import, Imports};\nuse move_binary_format::file_format::*;\nuse crate::unit::UnitAccess;\n\n/// Extract type signature.\npub fn extract_type_signature<'a>(\n unit: &'a impl UnitAccess,\n signature: &'a SignatureToken,\n imports: &'a Imports,\n type_params: &[Generic],\n) -> FType<'a> {\n match signature {\n SignatureToken::U8 => FType::Primitive(\"u8\"),\n SignatureToken::Bool => FType::Primitive(\"bool\"),\n SignatureToken::U64 => FType::Primitive(\"u64\"),\n SignatureToken::U128 => FType::Primitive(\"u128\"),\n SignatureToken::Address => FType::Primitive(\"address\"),\n SignatureToken::Signer => FType::Primitive(\"signer\"),\n\n SignatureToken::Vector(sign) => FType::Vec(Box::new(extract_type_signature(\n unit,\n sign.as_ref(),\n imports,\n type_params,\n ))),\n SignatureToken::Struct(struct_index) => {\n FType::Struct(extract_struct_name(unit, struct_index, imports))\n }\n SignatureToken::StructInstantiation(struct_index, typed) => FType::StructInst(\n extract_struct_name(unit, struct_index, imports),\n typed\n .iter()\n .map(|t| extract_type_signature(unit, t, imports, type_params))\n .collect::>(),\n ),\n SignatureToken::Reference(sign) => FType::Ref(Box::new(extract_type_signature(\n unit,\n sign.as_ref(),\n imports,\n type_params,\n ))),\n SignatureToken::MutableReference(sign) => FType::RefMut(Box::new(\n extract_type_signature(unit, sign.as_ref(), imports, type_params),\n )),\n SignatureToken::TypeParameter(index) => {\n FType::Generic(type_params[*index as usize].clone())\n }\n }\n}\n\n/// Extract struct name.\npub fn extract_struct_name<'a>(\n unit: &'a impl UnitAccess,\n struct_index: &'a StructHandleIndex,\n imports: &'a Imports,\n) -> FullStructName<'a> {\n let handler = unit.struct_handle(*struct_index);\n\n let module_handler = unit.module_handle(handler.module);\n let module_name = unit.identifier(module_handler.name);\n let address = unit.address(module_handler.address);\n let type_name = unit.identifier(handler.name);\n\n imports\n .get_import(address, module_name)\n .map(|import| FullStructName {\n name: type_name,\n import: Some(import),\n })\n .unwrap_or_else(|| FullStructName {\n name: type_name,\n import: None,\n })\n}\n\n/// Type.\n#[derive(Debug)]\npub enum FType<'a> {\n /// Generic type.\n Generic(Generic),\n /// Primitive type.\n Primitive(&'static str),\n /// Reference type.\n Ref(Box>),\n /// Mutable reference type.\n RefMut(Box>),\n /// Vector type.\n Vec(Box>),\n /// Struct type.\n Struct(FullStructName<'a>),\n /// Struct instantiation instance.\n StructInst(FullStructName<'a>, Vec>),\n}\n\nimpl<'a> Encode for FType<'a> {\n fn encode(&self, w: &mut W, indent: usize) -> Result<(), Error> {\n match self {\n FType::Primitive(name) => {\n w.write_str(name)?;\n }\n FType::Generic(type_param) => {\n type_param.as_name().encode(w, indent)?;\n }\n FType::Ref(t) => {\n w.write_str(\"&\")?;\n t.encode(w, indent)?;\n }\n FType::RefMut(t) => {\n w.write_str(\"&mut \")?;\n t.encode(w, indent)?;\n }\n FType::Vec(t) => {\n w.write_str(\"vector<\")?;\n t.encode(w, indent)?;\n w.write_str(\">\")?;\n }\n FType::Struct(name) => {\n name.encode(w, indent)?;\n }\n FType::StructInst(name, generics) => {\n name.encode(w, indent)?;\n if !generics.is_empty() {\n write!(w, \"<\")?;\n for (index, generic) in generics.iter().enumerate() {\n generic.encode(w, 0)?;\n if index != generics.len() - 1 {\n w.write_str(\", \")?;\n }\n }\n write!(w, \">\")?;\n }\n }\n }\n\n Ok(())\n }\n}\n\n/// Full structure name.\n#[derive(Debug)]\npub struct FullStructName<'a> {\n name: &'a str,\n import: Option>,\n}\n\nimpl<'a> Encode for FullStructName<'a> {\n fn encode(&self, w: &mut W, indent: usize) -> Result<(), Error> {\n if let Some(import) = &self.import {\n import.encode(w, indent)?;\n w.write_str(\"::\")?;\n }\n w.write_str(self.name)?;\n Ok(())\n }\n}\n"},"download_success":{"kind":"bool","value":true,"string":"true"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":11340,"numItemsPerPage":100,"numTotalItems":1135379,"offset":1134000,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1Njc4Mzc4NSwic3ViIjoiL2RhdGFzZXRzL2hvbmdsaXU5OTAzL3N0YWNrX2VkdV9ydXN0IiwiZXhwIjoxNzU2Nzg3Mzg1LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.XjgsdXst0AenVOmgf2bVADVm2T2udyYu28Gc50pS9zGnz8RzaJxtetzygoRV179Y2rYOYs36YAGVTAJtFj_dDg","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
6138154a22502b930bb68f699389cf26176172a8
Rust
port-finance/anchor
/tests/interface/programs/counter-auth/src/lib.rs
UTF-8
1,028
2.78125
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
//! counter-auth is an example of a program *implementing* an external program //! interface. Here the `counter::Auth` trait, where we only allow a count //! to be incremented if it changes the counter from odd -> even or even -> odd. //! Creative, I know. :P. use anchor_lang::prelude::*; use counter::Auth; declare_id!("Aws2XRVHjNqCUbMmaU245ojT2DBJFYX58KVo2YySEeeP"); #[program] pub mod counter_auth { use super::*; #[state] pub struct CounterAuth; impl<'info> Auth<'info, Empty> for CounterAuth { fn is_authorized(_ctx: Context<Empty>, current: u64, new: u64) -> ProgramResult { if current % 2 == 0 { if new % 2 == 0 { return Err(ProgramError::Custom(50)); // Arbitrary error code. } } else { if new % 2 == 1 { return Err(ProgramError::Custom(60)); // Arbitrary error code. } } Ok(()) } } } #[derive(Accounts)] pub struct Empty {}
true
24903a9d9ab0f0b429076fa74a2ea4121fe9fd44
Rust
lazylook2/rust_study
/src/object_oriented.rs
UTF-8
6,469
3.9375
4
[]
no_license
/// 封装 pub fn oo1() { pub struct AveragedCollection{ list: Vec<i32>, average: f64 } impl AveragedCollection{ pub fn add(&mut self, value: i32){ self.list.push(value); self.update_average() } pub fn update_average(&mut self){ let sum: i32 = self.list.iter().sum(); // 这里需要明确变量类型 self.average = sum as f64 / self.list.len() as f64 } pub fn remove(&mut self) -> Option<i32>{ let result = self.list.pop(); match result { Some(value) => { self.update_average(); Some(value) }, None => None } } pub fn average(&self) -> f64 { self.average } } let mut c = AveragedCollection{ list: vec![], average: 0.0 }; c.add(1); c.add(2); c.add(3); println!("平均值:{}", c.average()); c.remove().unwrap(); println!("平均值:{}", c.average()); } /// 多态 <br> /// 为使用不同类型的值而设计的 trait 对象 pub fn oo2 () { /// 绘制 - 接口 pub trait Draw { fn draw(&self); } /// 屏幕 - 实体 pub struct Screen { /// 组件(实现了Draw接口的实体集合) <br> /// dyn Trait与通用参数或不同impl Trait,编译器不知道要传递的具体类型。也就是说,该类型已被擦除。 <br> /// 这样,一个dyn Trait引用包含两个指针。一个指针指向该数据(例如,结构的实例)。 <br> /// 另一个指针指向方法调用名称到函数指针的映射(称为虚拟方法表或vtable)。 pub components: Vec<Box<dyn Draw>>, } impl Screen { /// 循环屏幕上的组件,并调用接口实现类的draw方法 fn run (&self) { for component in self.components.iter() { component.draw(); } } } // 泛型类型参数一次只能替代一个具体类型,而 trait 对象则允许在运行时替代多种具体类型。 /*pub struct Screen<T: Draw> { pub components: Vec<T>, } impl<T> Screen<T> where T: Draw { pub fn run(&self) { for component in self.components.iter() { component.draw(); } } }*/ pub struct Button { pub width: u32, pub height: u32, pub label: String } impl Draw for Button{ fn draw(&self) { println!("开始绘制按钮") } } struct SelectBox { width: u32, height: u32, options: Vec<String>, } impl Draw for SelectBox { fn draw(&self) { println!("开始绘制选择框") } } let screen = Screen{ components: vec![ Box::new(SelectBox{ width: 75, height: 10, options: vec![ String::from("Yes"), String::from("Maybe"), String::from("No") ] }), Box::new(Button { width: 50, height: 10, label: String::from("OK"), }), // 如果值没有实现 trait 对象所需的 trait 则 Rust 不会编译这些代码。 // Box::new(String::from("Hi")), ] }; screen.run(); // Trait 对象要求对象安全 // 只有 对象安全(object safe)的 trait 才可以组成 trait 对象。 // 1、返回值类型不为 Self // 2、方法没有任何泛型类型参数 /*pub trait Clone { fn clone(&self) -> Self; } pub struct Screen { pub components: Vec<Box<dyn Clone>>, }*/ } /// 面向对象设计模式的实现 pub fn oo3(){ /// 博文 pub struct Post { state: Option<Box<dyn State>>, // 使用Option应该是状态,可以换为其他状态还可以清空为NONE content: String } impl Post { pub fn new () -> Post{ Post { state: Some(Box::new(Draft{})), content: String::new() } } /// 插入博文内容 pub fn add_text(&mut self, text: &str) { self.content.push_str(text) } /// 如果是草案状态就返回空 /// 调用 Option 的 as_ref 方法是因为需要 Option 中值的引用而不是获取其所有权。 /// 因为 state 是一个 Option<Box<State>>,调用 as_ref 会返回一个 Option<&Box<State>> /// 如果不调用 as_ref,将会得到一个错误,因为不能将 state 移动出借用的 &self 函数参数。 /// /// 接着调用 unwrap 方法,这里我们知道它永远也不会 panic pub fn content(&self) -> &str{ self.state.as_ref().unwrap().content(self) } pub fn request_review(&mut self){ // 调用 take 方法将 state 字段中的 Some 值取出并留下一个 None // 确保了当 Post 被转换为新状态后其不再能使用老的 state 值。 if let Some(s) = self.state.take() { self.state = Some(s.request_review()) } } pub fn approve(&mut self){ if let Some(s) = self.state.take() { self.state = Some(s.approve()) } } } /// 状态 trait State { fn request_review(self: Box<Self>) -> Box<dyn State>; fn approve(self: Box<Self>) -> Box<dyn State>; fn content<'a>(&self, post: &'a Post) -> &'a str { "" } } // 草案 struct Draft {} impl State for Draft { fn request_review(self: Box<Self>) -> Box<dyn State> { Box::new(PendingReview{}) } fn approve(self: Box<Self>) -> Box<dyn State> { self } } struct PendingReview {} impl State for PendingReview { fn request_review(self: Box<Self>) -> Box<dyn State> { self } fn approve(self: Box<Self>) -> Box<dyn State> { self } } struct Published {} impl State for Published { fn request_review(self: Box<Self>) -> Box<dyn State> { self } fn approve(self: Box<Self>) -> Box<dyn State> { self } fn content<'a>(&self, post: &'a Post) -> &'a str { &post.content } } }
true
1873db80d81daeca9ce4a4ec1a1e47ef13dad663
Rust
teodorlu/Teko
/src/parse.rs
UTF-8
7,794
3.71875
4
[]
no_license
//! Parsing interface for Teko. //! //! Provides utility functions as well as primitives for parsing Teko. //! //! ``` //! extern crate teko; //! assert![teko::parse::parse_string("(+ 1 2 3) (' a (b) c)").is_ok()]; //! ``` use std::fs::File; use std::io::Read; use std::rc::Rc; use data_structures::{Commands, Coredata, ParseState, Program, Sourcedata}; // ////////////////////////////////////////////////////////// /// Parse a `File` into a `Program` /// /// Utility function to easily parse a `File`. pub fn parse_file(filename: &str) -> Result<Program, ParseState> { let mut file = File::open(filename)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; parse_string_with_state(&contents, ParseState::from(filename)) } // ////////////////////////////////////////////////////////// /// Parse a `String` into a `Program` /// /// Utility function to easily parse any `String`. /// /// ``` /// extern crate teko; /// assert![teko::parse::parse_string("(+ 1 2 3) (' a b c)").is_ok()]; /// ``` pub fn parse_string(string: &str) -> Result<Program, ParseState> { let state = ParseState::default(); parse_string_with_state(string, state) } // ////////////////////////////////////////////////////////// fn parse_string_with_state(string: &str, mut state: ParseState) -> Result<Program, ParseState> { for character in string.chars() { parse_character(character, &mut state)?; if state.error.is_some() { break; } } finish_parsing_characters(state) } // ////////////////////////////////////////////////////////// /// Convert the parser into an actual program /// /// This function should be called after a series of calls to `parse_character`. /// It takes a `state` and finalizes it into a program. /// See `parse_character` for an example. /// /// ``` /// extern crate teko; /// assert![teko::parse::finish_parsing_characters( /// teko::data_structures::ParseState::default()).is_ok()]; /// ``` pub fn finish_parsing_characters(mut state: ParseState) -> Result<Program, ParseState> { whitespace(&mut state); if !state.unmatched_opening_parentheses.is_empty() { Err(set_error(&mut state, "Unmatched opening parenthesis")) } else if state.error.is_some() { Err(state) } else { state.stack.reverse(); Ok(state.stack) } } /// Let us know if the parser can safely call `finish_parsing_characters`. /// /// When implement character feeds we may not be certain when input ends, so we /// need this function to be able to check if we can safely get a parse state. /// The nice thing about this is that we can always parse more later and put /// the result into the interpreter with the same effect. pub fn is_ready_to_finish(state: &ParseState) -> bool { state.unmatched_opening_parentheses.is_empty() && state.token.is_empty() && !state.stack.is_empty() } /// Check if the parser is empty. pub fn is_empty(state: &ParseState) -> bool { state.stack.is_empty() } /// Parses character-by-character to allow parsing from arbitrary character sources. /// /// Mainly used to implement utility functions that feed characters. /// /// ``` /// extern crate teko; /// let mut state = teko::data_structures::ParseState::default(); /// for ch in "(+ 1 2 3) (' a b c)".chars() { /// assert![teko::parse::parse_character(ch, &mut state).is_ok()]; /// } /// assert![teko::parse::finish_parsing_characters(state).is_ok()]; /// ``` pub fn parse_character(character: char, state: &mut ParseState) -> Result<(), ParseState> { parse_internal(character, state)?; count_characters_and_lines(character, state); Ok(()) } // ////////////////////////////////////////////////////////// // Internal // // ////////////////////////////////////////////////////////// fn count_characters_and_lines(character: char, state: &mut ParseState) { if character == '\n' { state.current_read_position.line += 1; state.current_read_position.column = 1; } else { state.current_read_position.column += 1; } } fn parse_internal(character: char, state: &mut ParseState) -> Result<(), ParseState> { if character.is_whitespace() { whitespace(state); } else if character == '(' { left_parenthesis(state); } else if character == ')' { right_parenthesis(state)?; } else { otherwise(character, state); } Ok(()) } // ////////////////////////////////////////////////////////// fn whitespace(state: &mut ParseState) { move_token_to_stack_if_nonempty(state); } fn left_parenthesis(state: &mut ParseState) { move_token_to_stack_if_nonempty(state); copy_current_read_position_to_unmatched_opening_parentheses(state); state.stack.push(Rc::new(Sourcedata( Some(state.current_read_position.clone()), Coredata::Internal(Commands::Empty), ))); } fn right_parenthesis(state: &mut ParseState) -> Result<(), ParseState> { move_token_to_stack_if_nonempty(state); pop_previous_opening_parenthesis(state)?; let mut active = Rc::new(Sourcedata( Some(state.current_read_position.clone()), Coredata::Null, )); let mut source = None; while let Some(top) = state.stack.pop() { match *top { Sourcedata(ref pair_source, Coredata::Internal(Commands::Empty)) => { source = pair_source.clone(); break; } _ => { active = Rc::new(Sourcedata( top.0.clone(), Coredata::Pair(top.clone(), active), )); } } } Rc::get_mut(&mut active) .expect("There are no other references to the active set") .0 = source; state.stack.push(active); Ok(()) } fn otherwise(character: char, state: &mut ParseState) { if state.token.is_empty() { state.start_of_current_lexeme = state.current_read_position.clone(); } state.token.push(character); } // ////////////////////////////////////////////////////////// fn move_token_to_stack_if_nonempty(state: &mut ParseState) { if !state.token.is_empty() { state.stack.push(Rc::new(Sourcedata( Some(state.start_of_current_lexeme.clone()), Coredata::Symbol(state.token.clone()), ))); clear_token(state); } } fn clear_token(state: &mut ParseState) { state.token.clear(); } fn set_error(state: &mut ParseState, message: &str) -> ParseState { state.error = Some(String::from(message)); state.clone() } fn copy_current_read_position_to_unmatched_opening_parentheses(state: &mut ParseState) { state .unmatched_opening_parentheses .push(state.current_read_position.clone()); } fn pop_previous_opening_parenthesis(state: &mut ParseState) -> Result<(), ParseState> { if !state.unmatched_opening_parentheses.pop().is_some() { Err(set_error(state, "Unmatched closing parenthesis")) } else { Ok(()) } } // ////////////////////////////////////////////////////////// // Tests // // ////////////////////////////////////////////////////////// #[cfg(test)] mod tests { use super::*; macro_rules! assert_oks { ( $f:expr, $( $x:expr ),*, ) => { assert_oks![$f, $( $x ),*]; }; ( $f:expr, $( $x:expr ),* ) => { { $( assert![$f($x).is_ok()]; )* } }; } macro_rules! assert_errs { ( $f:expr, $( $x:expr ),*, ) => { assert_errs![$f, $( $x ),*]; }; ( $f:expr, $( $x:expr ),* ) => { { $( assert![$f($x).is_err()]; )* } }; } #[test] fn assert_expressions_ok() { assert_oks![ parse_string, "", " ", " ", "[", "]", "{", "}", ".", ",", "'", "\"", "", " ", " ", "[", "]>", "<{", "}|", ".^", ",-", "'Æ", "\"o\"\"", "()", " ()", "() ", " () ", " ( ) ", "test", "(test)", " (test)", "(test) ", " (test) ", "(test1 (test2))", "(test1 (test2 test3 test4) test5) test6", ]; } #[test] fn assert_expressions_err() { assert_errs![ parse_string, "(", ")", "(test", "test)", "(test1 (test2)", "(((((((()))))))", "(((((()))))))" ]; } }
true
adc8e594bcf8854cb2a59b4498fe24346212074f
Rust
tnederlof/abstreet
/santa/src/controls.rs
UTF-8
1,765
3.265625
3
[ "Apache-2.0" ]
permissive
use geom::{Angle, Speed}; use widgetry::{EventCtx, Key}; // TODO The timestep accumulation seems fine. What's wrong? Clamping errors repeated? const HACK: f64 = 5.0; pub struct InstantController { /// Which of the 8 directions are we facing, based on the last set of keys pressed down? pub facing: Angle, } impl InstantController { pub fn new() -> InstantController { InstantController { facing: Angle::ZERO, } } pub fn displacement(&mut self, ctx: &mut EventCtx, speed: Speed) -> Option<(f64, f64)> { let dt = ctx.input.nonblocking_is_update_event()?; // Work around a few bugs here. // // 1) The Santa sprites are all facing 180 degrees, not 0, so invert X. // 2) Invert y so that negative is up. // // It's confusing, but self.facing winds up working for rotating the sprite, and the output // displacement works. self.facing = angle_from_arrow_keys(ctx)?.opposite(); let magnitude = (dt * HACK * speed).inner_meters(); let (sin, cos) = self.facing.normalized_radians().sin_cos(); Some((-magnitude * cos, -magnitude * sin)) } } pub fn angle_from_arrow_keys(ctx: &EventCtx) -> Option<Angle> { let mut x: f64 = 0.0; let mut y: f64 = 0.0; if ctx.is_key_down(Key::LeftArrow) || ctx.is_key_down(Key::A) { x -= 1.0; } if ctx.is_key_down(Key::RightArrow) || ctx.is_key_down(Key::D) { x += 1.0; } if ctx.is_key_down(Key::UpArrow) || ctx.is_key_down(Key::W) { y -= 1.0; } if ctx.is_key_down(Key::DownArrow) || ctx.is_key_down(Key::S) { y += 1.0; } if x == 0.0 && y == 0.0 { return None; } Some(Angle::new_rads(y.atan2(x))) }
true
9dd4620866b4d36740d1f270a4801485203ef52d
Rust
mattlgy/badinputs
/src/lib.rs
UTF-8
2,433
2.890625
3
[]
no_license
extern crate stdweb; #[macro_use] extern crate yew; mod byte_boxes; use yew::prelude::*; use yew::services::ConsoleService; use byte_boxes::ByteBoxes; use std::str; pub struct Model { console: ConsoleService, length: u8, bytes: Vec<u8>, } pub enum Msg { SetLength(u8), SetValueAt(usize, u8), SetStringValue(String), } impl Model { fn update_length(&mut self) { while self.bytes.len() < self.length as usize { self.bytes.push(0); } while self.bytes.len() > self.length as usize { self.bytes.pop(); } } } impl Component for Model { type Message = Msg; type Properties = (); fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self { Model { console: ConsoleService::new(), length: 0, bytes: vec![], } } fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Msg::SetLength(value) => { self.length = value; self.console.log("value set to..."); self.console.log(&value.to_string()); self.update_length(); } Msg::SetValueAt(i, value) => { self.bytes[i] = value; self.console.log("value set to..."); self.console.log(&value.to_string()); } Msg::SetStringValue(str_val) => { self.console.log("String value..."); self.console.log(&str_val); self.length = str_val.len() as u8; self.bytes = str_val.into_bytes(); } } true } } impl Renderable<Model> for Model { fn view(&self) -> Html<Self> { let byte_input = |i| html! { <span> { "|" } <ByteBoxes: value=self.bytes[i], onchange=move |b| Msg::SetValueAt(i, b),/> </span> }; html! { <div> <dic> <input oninput=|e| Msg::SetStringValue(e.value), value= str::from_utf8(&self.bytes).unwrap_or(""), /> </dic> <div> <ByteBoxes: value=self.length, onchange=Msg::SetLength, /> { for (0..self.bytes.len()).map(byte_input) } </div> </div> } } }
true
21ffb1876ece16c432db99133a4bb9c022652c2f
Rust
XDXX/PNA
/benches/benches.rs
UTF-8
1,963
2.96875
3
[ "MIT" ]
permissive
use kvs::{KvStore, KvsEngine, SledKvsEngine}; use rand::prelude::*; use tempfile::TempDir; use criterion::{criterion_group, criterion_main, Criterion}; const SET_REPEATS: usize = 10; const GET_REPEATS: usize = 10000; /// Benchmarking the performance of setting key to database. Note that when collecting /// multiple samples of `set_kvs`, it may trigger the log compacting. fn set_bench(c: &mut Criterion) { let temp_dir_kvs = TempDir::new().unwrap(); let mut kv_store = KvStore::open(&temp_dir_kvs).unwrap(); let temp_dir_sled = TempDir::new().unwrap(); let mut sled_db = SledKvsEngine::open(&temp_dir_sled).unwrap(); c.bench_function("set_kvs", move |b| { b.iter(|| set_n_times(&mut kv_store, SET_REPEATS)) }); c.bench_function("set_sled", move |b| { b.iter(|| set_n_times(&mut sled_db, SET_REPEATS)) }); } fn get_bench(c: &mut Criterion) { let temp_dir_kvs = TempDir::new().unwrap(); let mut kv_store = KvStore::open(&temp_dir_kvs).unwrap(); let temp_dir_sled = TempDir::new().unwrap(); let mut sled_db = SledKvsEngine::open(&temp_dir_sled).unwrap(); set_n_times(&mut kv_store, GET_REPEATS); set_n_times(&mut sled_db, GET_REPEATS); c.bench_function("get_kvs", move |b| { b.iter(|| get_n_times_randomly(&mut kv_store, GET_REPEATS)) }); c.bench_function("get_sled", move |b| { b.iter(|| get_n_times_randomly(&mut sled_db, GET_REPEATS)) }); } fn set_n_times<E: KvsEngine>(engine: &mut E, n: usize) { for i in 0..n { engine .set(format!("key{}", i), "value".to_string()) .unwrap(); } } fn get_n_times_randomly<E: KvsEngine>(engine: &mut E, n: usize) { let mut rng = SmallRng::from_seed([6; 16]); for _ in 0..n { engine .get(format!("key{}", rng.gen_range(0, GET_REPEATS))) .unwrap(); } } criterion_group!(benches, set_bench, get_bench); criterion_main!(benches);
true
3b8d9be825eb928ce9477c6899ed9da6ec144a30
Rust
Xeiron/sndfile.rs
/src/test/test_issue_3.rs
UTF-8
3,048
2.6875
3
[ "MIT" ]
permissive
use crate::*; use tempfile::TempDir; #[test] fn issue_3_no_tags() { // ch = 1, t = 50ms, sr = 2000Hz, tone = sin 880Hz static DATA: &'static [u8] = b"RIFF\x88\x00\x00\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00\xd0\x07\x00\x00\xd0\x07\x00\x00\x01\x00\x08\x00datad\x00\x00\x00\x80\xa59\xdc\x19\xe11\xb1sf\xbc)\xe4\x1b\xd6C\x99\x8cN\xce\x1e\xe6#\xc6Z\x80\xa59\xdc\x19\xe11\xb1sf\xbc)\xe4\x1b\xd6C\x99\x8cN\xce\x1e\xe6#\xc6Z\x7f\xa59\xdc\x19\xe11\xb1sf\xbc)\xe4\x1b\xd6C\x99\x8cN\xce\x1e\xe6#\xc6Z\x7f\xa59\xdc\x19\xe11\xb1sf\xbc)\xe4\x1b\xd6C\x99\x8cN\xce\x1e\xe6#\xc6Z"; let tmp_dir = TempDir::new().unwrap(); let tmp_path = tmp_dir.as_ref().join("issue_3_no_tags.wav"); std::fs::write(&tmp_path, DATA).unwrap(); let snd = OpenOptions::ReadOnly(ReadOptions::Auto).from_path(&tmp_path).unwrap(); // Empty header, should not have any tag set assert_eq!(snd.get_tag(TagType::Title), None); assert_eq!(snd.get_tag(TagType::Copyright), None); assert_eq!(snd.get_tag(TagType::Software), None); assert_eq!(snd.get_tag(TagType::Artist), None); assert_eq!(snd.get_tag(TagType::Comment), None); assert_eq!(snd.get_tag(TagType::Date), None); assert_eq!(snd.get_tag(TagType::Album), None); assert_eq!(snd.get_tag(TagType::License), None); assert_eq!(snd.get_tag(TagType::Tracknumber), None); assert_eq!(snd.get_tag(TagType::Genre), None); } #[test] fn issue_3_some_tags() { // Tags to set const TAG_TITLE_STR: &str = "some_title"; const TAG_COPYRIGHT: &str = "dobby_is_free"; const TAG_COMMENT: &str = "no comment"; // Empty data vec const DEFAULT_BUF: [i16; 256] = [0i16; 256]; let tmp_dir = TempDir::new().unwrap(); let tmp_path = tmp_dir.as_ref().join("issue_3_some_tags.wav"); // Write the file { let mut snd = OpenOptions::WriteOnly(WriteOptions::new( MajorFormat::WAV, SubtypeFormat::PCM_24, Endian::File, 8000, 2, )) .from_path(&tmp_path) .unwrap(); for _ in 0..256 { snd.write_from_slice(&DEFAULT_BUF).unwrap(); } snd.set_tag(TagType::Title, TAG_TITLE_STR).unwrap(); snd.set_tag(TagType::Copyright, TAG_COPYRIGHT).unwrap(); snd.set_tag(TagType::Comment, TAG_COMMENT).unwrap(); } // Check the file { let snd = OpenOptions::ReadOnly(ReadOptions::Auto) .from_path(&tmp_path) .unwrap(); // Check the tags has been set assert_eq!(snd.get_tag(TagType::Title).unwrap(), TAG_TITLE_STR); assert_eq!(snd.get_tag(TagType::Copyright).unwrap(), TAG_COPYRIGHT); assert_eq!(snd.get_tag(TagType::Comment).unwrap(), TAG_COMMENT); // Check the missing tags returns None assert_eq!(snd.get_tag(TagType::Software), None); assert_eq!(snd.get_tag(TagType::Artist), None); assert_eq!(snd.get_tag(TagType::Date), None); assert_eq!(snd.get_tag(TagType::Album), None); assert_eq!(snd.get_tag(TagType::License), None); assert_eq!(snd.get_tag(TagType::Tracknumber), None); assert_eq!(snd.get_tag(TagType::Genre), None); } std::fs::remove_file(&tmp_path).unwrap(); }
true
5b81fe62ea0f86f0d4a16c09d58ec915fc97db70
Rust
yanyushr/fuchsia
/src/connectivity/wlan/lib/common/rust/src/big_endian.rs
UTF-8
1,110
2.859375
3
[ "BSD-3-Clause" ]
permissive
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { byteorder::{BigEndian, ByteOrder}, zerocopy::{AsBytes, FromBytes, Unaligned}, }; #[repr(C)] #[derive(Clone, Copy, Debug, Default, AsBytes, FromBytes, Unaligned, PartialEq, Eq)] pub struct BigEndianU16(pub [u8; 2]); impl BigEndianU16 { pub fn from_native(native: u16) -> Self { let mut buf = [0, 0]; BigEndian::write_u16(&mut buf, native); BigEndianU16(buf) } pub fn to_native(&self) -> u16 { BigEndian::read_u16(&self.0) } pub fn set_from_native(&mut self, value: u16) { BigEndian::write_u16(&mut self.0, value); } } #[cfg(test)] mod tests { use super::*; #[test] fn big_endian_u16() { let mut x = BigEndianU16::from_native(0x1234); assert_eq!([0x12, 0x34], x.0); assert_eq!(0x1234, x.to_native()); x.set_from_native(0x5678); assert_eq!([0x56, 0x78], x.0); assert_eq!(0x5678, x.to_native()); } }
true
5342bb6198e104cb87f1c150b1a2953a9ee4854f
Rust
rabbitXIII/wasm_snake
/src/canvas.rs
UTF-8
1,703
3.03125
3
[]
no_license
use stdweb::traits::*; use crate::stdweb::unstable::TryInto; use stdweb::web::html_element::CanvasElement; use stdweb::web::{document, CanvasRenderingContext2d}; use crate::cell::Cell; pub struct Canvas { pub canvas: CanvasElement, pub ctx: CanvasRenderingContext2d, width_scaling_factor: u32, height_scaling_factor: u32, width: u32, height: u32, } impl Canvas { pub fn new(element_id: &str, width: u32, height: u32) -> Canvas { let canvas: CanvasElement = document() .query_selector(element_id) .unwrap() .unwrap() .try_into() .unwrap(); let ctx: CanvasRenderingContext2d = canvas.get_context().unwrap(); let width_scaling_factor = canvas.width() / width; let height_scaling_factor = canvas.height() / height; Canvas { canvas, ctx, width_scaling_factor, height_scaling_factor, width, height, } } pub fn get_width(&self) -> u32 { return self.width; } pub fn get_height(&self) -> u32 { return self.height; } pub fn draw(&self, cell: Cell, color: &str) { assert!(cell.x < self.width); assert!(cell.y < self.height); self.ctx.set_fill_style_color(color); let x = cell.x * self.width_scaling_factor; let y = cell.y * self.height_scaling_factor; self.ctx.fill_rect( f64::from(x), f64::from(y), f64::from(self.width_scaling_factor), f64::from(self.height_scaling_factor), ); } pub fn clear(&self) { self.ctx.set_fill_style_color("white"); self.ctx.fill_rect( 0.0, 0.0, f64::from(self.width * self.width_scaling_factor), f64::from(self.height * self.height_scaling_factor), ); } }
true
7bab0c0794e8e29a8a51b32368999d4065570076
Rust
papey/aoc
/2k21/day06/src/lib.rs
UTF-8
1,905
3.0625
3
[ "Unlicense" ]
permissive
use helper::Input; use std::collections::HashMap; #[allow(dead_code)] fn part1(input: Input) -> isize { solve(&input, 80) } #[allow(dead_code)] fn part2(input: Input) -> isize { solve(&input, 256) } fn solve(input: &Input, days: usize) -> isize { (0..days) .fold(init_fishes_pool(input), |f, _| { (0..=8).fold(HashMap::new(), |mut acc, age| { if age == 0 { *acc.entry(8).or_insert(0) += f.get(&age).unwrap_or(&0); *acc.entry(6).or_insert(0) += f.get(&age).unwrap_or(&0); } else { *acc.entry(age - 1).or_insert(0) += *f.get(&age).unwrap_or(&0); } acc }) }) .values() .cloned() .sum() } fn init_fishes_pool(input: &Input) -> HashMap<isize, isize> { input .transform(move |line| { line.clone() .split(",") .filter_map(|num| num.parse::<isize>().ok()) .collect::<Vec<_>>() }) .nth(0) .unwrap() .iter() .fold(HashMap::new(), |mut f, age| { *f.entry(*age).or_insert(0) += 1; f }) } #[cfg(test)] mod tests { use helper::Input; #[test] fn test_p1() { let test_input = Input::new("inputs/test.txt".to_string(), 6, 2021).unwrap(); assert_eq!(super::part1(test_input), 5934); let input = Input::new("inputs/input.txt".to_string(), 6, 2021).unwrap(); assert_eq!(super::part1(input), 352872); } #[test] fn test_p2() { let test_input = Input::new("inputs/test.txt".to_string(), 6, 2021).unwrap(); assert_eq!(super::part2(test_input), 26984457539); let input = Input::new("inputs/input.txt".to_string(), 6, 2021).unwrap(); assert_eq!(super::part2(input), 1604361182149); } }
true
79678f6fa2fa5a3fabef94f792555cbb3f2bf67a
Rust
LucasGobbs/trogue
/src/trogue_app/trogue_app.rs
UTF-8
956
3.203125
3
[]
no_license
use crate::buffer::{Buffer}; #[derive(Clone)] pub struct TrogueApp { pub buffers: Vec<Buffer>, pub current_buffer: usize, pub mouse_pos: (i32,i32), size: (i32,i32), } impl TrogueApp { pub fn new(width: i32, height: i32) -> TrogueApp { let mut buffers: Vec<Buffer> = Vec::new(); buffers.push(Buffer::new(width as usize, height as usize)); TrogueApp{ buffers, current_buffer: 0, mouse_pos: (0,0), size: (width, height), } } pub fn set_mouse_pos(&mut self, x: i32, y: i32){ self.mouse_pos.0 = x; self.mouse_pos.1 = y; } pub fn buf(&mut self) ->&mut Buffer { &mut self.buffers[self.current_buffer] } pub fn draw(self) -> Buffer { let n_buf = self.buffers[self.current_buffer].clone(); n_buf } pub fn add_buffer(mut self, n_buf: Buffer){ self.buffers.push(n_buf); } }
true
cd68105d17a9e9d9b52801d32893af5f94e8659c
Rust
Equilibris/rust-hello-huffman
/src/huff_decoder.rs
UTF-8
6,848
2.90625
3
[ "Unlicense" ]
permissive
use crate::bit_byte_increase; use crate::header::Header; use crate::types::*; pub fn decode_string(final_bit_offset: usize, tree: Tree, data: Vec<u8>) -> String { let mut byte_cursor: usize = 0; let len = data.len(); let mut output = String::with_capacity(data.len() << 1); let mut worker_leaf = &tree; loop { let mut byte = data[byte_cursor]; for _ in 0..(if len - 1 != byte_cursor { 8 } else { final_bit_offset }) { worker_leaf = if byte >= 128 { worker_leaf.left().unwrap().as_ref() } else { worker_leaf.right().unwrap().as_ref() }; byte <<= 1; if worker_leaf.is_leaf() { let val = *worker_leaf.leaf_value().unwrap(); output.push(val); worker_leaf = &tree; } } byte_cursor += 1; if len == byte_cursor { break output; } } } // Assume there are only power of 2 sized symbols in the data since there are. // This means that the bit_cursor is an even number fn decode_tree_iteration(data: &Vec<u8>, bit_cursor: &mut u16, byte_cursor: &mut usize) -> Tree { let operator = data[*byte_cursor] << *bit_cursor; if operator >= 0b11000000 { let val = ((data[*byte_cursor] as u32) << 24) | ((data[*byte_cursor + 1] as u32) << 16) | ((data[*byte_cursor + 2] as u32) << 8); let val = (val << *bit_cursor << 2 >> 16) as u16; let bytes: [u8; 2] = val.to_be_bytes(); bit_byte_increase!(*bit_cursor, *byte_cursor, 18); Tree::Node( Box::new(Tree::Leaf(bytes[0] as Symbol)), Box::new(Tree::Leaf(bytes[1] as Symbol)), ) } else if operator >= 0b10000000 { bit_byte_increase!(*bit_cursor, *byte_cursor, 2); let left = decode_tree_iteration(data, bit_cursor, byte_cursor); let right = decode_tree_iteration(data, bit_cursor, byte_cursor); Tree::Node(Box::new(left), Box::new(right)) } else if operator >= 0b01000000 { let val = ((data[*byte_cursor] as u16) << 8) | (data[*byte_cursor + 1] as u16); let val = (val << *bit_cursor << 2 >> 8) as u8; bit_byte_increase!(*bit_cursor, *byte_cursor, 10); Tree::Node( Box::new(Tree::Leaf(val as Symbol)), Box::new(decode_tree_iteration(data, bit_cursor, byte_cursor)), ) } else { let val = ((data[*byte_cursor] as u16) << 8) | (data[*byte_cursor + 1] as u16); let val = (val << *bit_cursor << 2 >> 8) as u8; bit_byte_increase!(*bit_cursor, *byte_cursor, 10); Tree::Leaf(val as Symbol) } } pub fn decode_tree(data: Vec<u8>) -> Tree { let mut bit_cursor: u16 = 0; let mut byte_cursor: usize = 0; decode_tree_iteration(&data, &mut bit_cursor, &mut byte_cursor) } pub fn decoder(data: Vec<u8>) -> String { let header = Header::from_raw(u64::from_be_bytes([ data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], ])); let header_end = (header.symbol_size as usize) + 8; let content_end = (header.content_size as usize) + header_end; let tree = decode_tree(data[8..header_end].to_vec()); decode_string( header.offset as usize, tree, data[header_end..content_end].to_vec(), ) } #[cfg(test)] mod tests { const TEST_STR: &'static str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec elementum arcu, et consequat odio. Nam at velit feugiat, hendrerit leo a, sagittis magna. Donec sit amet sapien sed urna condimentum dapibus in id nibh. Etiam suscipit aliquam egestas. Nunc sit amet condimentum dui. Sed sodales massa nec elit tristique aliquam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis at massa accumsan, condimentum erat in, porta ex. Curabitur a nisi ac augue tincidunt egestas. Sed ut venenatis lacus. Vestibulum et lectus eu mauris semper ornare sit amet at felis. Maecenas sed augue eu elit pharetra iaculis maximus vel sapien. Suspendisse quis neque mollis, aliquet tellus in, ultricies enim. Ut ut eros venenatis, mollis nisi a, convallis massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Suspendisse rutrum magna vitae augue viverra sagittis."; use crate::huff_decoder::*; use crate::huff_encoder::*; #[test] fn it_decodes_string() { let input = String::from(TEST_STR); let frequencies = frequency_extractor(&input); let mut queue = build_queue(frequencies); let tree = build_tree(&mut queue); let inverse_char_map = build_inverse_char_map(&tree); let (out, bit_offset) = encode_string(inverse_char_map, input); let output = decode_string(bit_offset, tree, out); assert_eq!(output, String::from(TEST_STR)); } fn do_tree_test(tree: Tree) { let encoded_tree = encode_tree(&tree); let decoded_tree = decode_tree(encoded_tree); assert_eq!(tree, decoded_tree); } #[test] fn it_decodes_tree() { { let tree = Tree::Node(Box::new(Tree::Leaf('x')), Box::new(Tree::Leaf('a'))); do_tree_test(tree); } { let tree = Tree::Node( Box::new(Tree::Node( Box::new(Tree::Leaf('x')), Box::new(Tree::Leaf('a')), )), Box::new(Tree::Node( Box::new(Tree::Leaf('z')), Box::new(Tree::Leaf('b')), )), ); do_tree_test(tree); } { let tree = Tree::Node( Box::new(Tree::Node( Box::new(Tree::Leaf('x')), Box::new(Tree::Leaf('a')), )), Box::new(Tree::Leaf('z')), ); do_tree_test(tree); } { let tree = Tree::Node( Box::new(Tree::Leaf('z')), Box::new(Tree::Node( Box::new(Tree::Leaf('x')), Box::new(Tree::Leaf('a')), )), ); do_tree_test(tree); } { let input = String::from(TEST_STR); let frequencies = frequency_extractor(&input); let mut queue = build_queue(frequencies); let tree = build_tree(&mut queue); do_tree_test(tree); } } #[test] fn it_decodes() { let input = String::from(TEST_STR); let encoded = encoder(input); let decoded = decoder(encoded); assert_eq!(decoded, String::from(TEST_STR)); } }
true
f76f2d9ee4e67e03fce5c3467e8a553f81f4eca7
Rust
Logicalshift/flowbetween
/canvas_animation/src/effects/time_curve.rs
UTF-8
4,241
3.25
3
[ "Apache-2.0" ]
permissive
use crate::region::*; use flo_curves::bezier::*; use std::sync::*; use std::time::{Duration}; /// /// The time curve effect applies a bezier curve time effect to an existing animation /// /// It can be used to define simple effects like ease-in, ease-out or more complex /// effects over time /// #[derive(Clone)] pub struct TimeCurveEffect<TEffect: AnimationEffect> { /// The effect that the time curve is being applied to effect: TEffect, /// The control points for the time curve (a 1D bezier curve, in time coordinates). Time is linear after the last control point, /// and the start point is always 0. Control points should always be moving forward in time (though there are no restrictions /// between two control points) /// /// Order is control point 1, control point 2, end point curve_points: Vec<(f64, f64, f64)> } impl<TEffect: AnimationEffect> TimeCurveEffect<TEffect> { /// /// Creates a new time curve effect with the specified control points /// pub fn with_control_points(effect: TEffect, control_points: Vec<(f64, f64, f64)>) -> TimeCurveEffect<TEffect> { TimeCurveEffect { effect: effect, curve_points: control_points } } /// /// Works out where the specified time lies on the curve /// pub fn time_for_time(curve_points: &Vec<(f64, f64, f64)>, time: Duration) -> Duration { // Convert time to milliseconds let time = (time.as_nanos() as f64) / 1_000_000.0; // Find the two curve points that this time is between (first where the control point is greater than the time) let mut start_point = 0.0; let cp1; let cp2; let end_point; let mut curve_iter = curve_points.iter(); loop { if let Some((test_cp1, test_cp2, test_end_point)) = curve_iter.next() { // If the end point is > time then this is the section containing the requested time if test_end_point > &time { // This is the curve section containing the specified time region cp1 = *test_cp1; cp2 = *test_cp2; end_point = *test_end_point; break; } // The end point of this section is the start of the next section start_point = *test_end_point; } else { // The time is beyond the end of the curve, so we just treat it linearly return Duration::from_nanos((time * 1_000_000.0) as u64); } } // We have the curve section with the time: the t value is the ratio that 'time' is along the curve let t = (time-start_point) / (end_point-start_point); // Time can be calculated using the bezier algorithm let milliseconds = de_casteljau4(t, start_point, cp1, cp2, end_point); Duration::from_nanos((milliseconds * 1_000_000.0) as u64) } } impl<TEffect: AnimationEffect> AnimationEffect for TimeCurveEffect<TEffect> { /// /// Given the contents of the regions for this effect, calculates the path that should be rendered /// fn animate(&self, region_contents: Arc<AnimationRegionContent>, time: Duration) -> Arc<AnimationRegionContent>{ self.effect.animate(region_contents, Self::time_for_time(&self.curve_points, time)) } /// /// Given an input region that will remain fixed throughout the time period, returns a function that /// will animate it. This can be used to speed up operations when some pre-processing is required for /// the region contents, but is not always available as the region itself might be changing over time /// (eg, if many effects are combined) /// fn animate_cached(&self, region_contents: Arc<AnimationRegionContent>) -> Box<dyn Send+Fn(Duration) -> Arc<AnimationRegionContent>> { let cached_effect = self.effect.animate_cached(region_contents); let curve_points = self.curve_points.clone(); Box::new(move |time| { cached_effect(Self::time_for_time(&curve_points, time)) }) } }
true
0dadae74884b48172f28b318d4b5e9ef14d640aa
Rust
taochunyu/editor_lib
/editor/src/transform/replace.rs
UTF-8
2,771
2.875
3
[]
no_license
use std::rc::Rc; use crate::node::slice::Slice; use crate::transform::step::{Step, StepResult}; use crate::node::Node; use crate::Doc; use crate::transform::Transform; use crate::transform::step_map::StepMap; use crate::transform::mapping::Mapping; pub struct ReplaceStep { from: usize, to: usize, slice: Slice, structure: bool, } impl Step for ReplaceStep { fn apply(&self, doc: Doc) -> StepResult { let is_content_between = match Self::content_between(doc.clone(), self.from, self.to) { Ok(is_content_between) => is_content_between, Err(err) => return StepResult::failed(err), }; if self.structure && is_content_between { StepResult::failed(format!("Structure replace would overwrite content.")) } else { StepResult::from_replace(doc, self.from, self.to, self.slice.clone()) } } fn invert(&self, doc: Doc) -> Result<Box<dyn Step>, String> { let slice = doc.slice(self.from, self.to)?; Ok(Self::new(self.from, self.from + self.slice.size(), slice, false)) } fn get_map(&self) -> StepMap { StepMap::new(vec![(self.from, self.to - self.from, self.slice.size())], false) } fn map(&self, mapping: Mapping) -> Option<Box<dyn Step>> { unimplemented!() } } impl ReplaceStep { pub fn new(from: usize, to: usize, slice: Slice, structure: bool) -> Box<dyn Step> { Box::new(ReplaceStep { from, to, slice, structure }) } fn content_between(doc: Doc, from: usize, to: usize) -> Result<bool, String> { if to < from { Err(format!("From {} should not be greater than to {}.", from, to)) } else { let from = doc.resolve(from)?; let mut depth = from.depth(); let mut dist = to - from.offset(); while depth > 0 && dist > 0 && from.index_after(depth)? == from.step(depth)?.node.child_count() { depth -= 1; dist -= 1; } if dist > 0 { let mut next = from.step(depth)?.node.get_child(from.index_after(depth)?); while dist > 0 { if let Ok(node) = &next { if node.children().is_some() { return Ok(true); } next = node.get_child(0); dist -= 1; } return Ok(true); } } Ok(false) } } } impl Transform { pub fn replace(&mut self, from: usize, to: usize, slice: Slice) -> &mut Self { let step = ReplaceStep::new(from, to, slice, false); self.step(step); self } }
true
a02966c74d8068912607e3c6f60bd777e38f9dbd
Rust
mateuszJS/battle
/crate/src/position_utils/track_utils/mod.rs
UTF-8
5,986
2.671875
3
[ "MIT" ]
permissive
mod a_star; use super::basic_utils::{BasicUtils, Line, Point}; use super::obstacles_lazy_statics::ObstaclesLazyStatics; use super::CalcPositions; use crate::constants::{MATH_PI, NORMAL_SQUAD_RADIUS}; use a_star::AStar; use std::collections::HashMap; pub struct TrackUtils {} impl TrackUtils { fn calc_complicated_track<'a>( start_point: &'a Point, end_point: &'a Point, obstacles_points: &'static Vec<&'static Point>, obstacles_lines: &'static Vec<Line<'static>>, permanent_connection_graph: &'static HashMap<u32, Vec<&'static Point>>, ) -> Vec<&'a Point> { let mut graph = permanent_connection_graph.clone(); graph.insert(start_point.id, vec![]); [&start_point, &end_point].iter().for_each(|track_point| { obstacles_points.iter().for_each(|obstacle_point| { if track_point.x.is_nan() || track_point.y.is_nan() || obstacle_point.x.is_nan() || obstacle_point.y.is_nan() { log!( "START checking intersection: {} - {} - {} - {}", track_point.x, track_point.y, obstacle_point.x, obstacle_point.y ); } // ------------START checking intersection------------------- let new_line = Line { p1: track_point, p2: obstacle_point, }; let mut is_intersect = false; obstacles_lines.iter().for_each(|obstacle_line| { if obstacle_line.p1.id != obstacle_point.id && obstacle_line.p2.id != obstacle_point.id && BasicUtils::check_intersection(&new_line, obstacle_line) { is_intersect = true; }; }); // ------------end checking intersection------------------- if !is_intersect { if graph.contains_key(&track_point.id) { let graph_item = graph.get_mut(&track_point.id).unwrap(); graph_item.push(&obstacle_point); } else { let graph_item = graph.get_mut(&obstacle_point.id).unwrap(); graph_item.push(&track_point); } } }); }); AStar::shortest_path(graph, &start_point, &end_point) } pub fn calculate_track<'a>(start_point: &'a Point, end_point: &'a Point) -> Vec<&'a Point> { if start_point.x.is_nan() || start_point.y.is_nan() || end_point.x.is_nan() || end_point.y.is_nan() { log!( "calculate_track: {} - {} - {} - {}", start_point.x, start_point.y, end_point.x, end_point.y ); } let obstacles_lines = ObstaclesLazyStatics::get_obstacles_lines(); // ------------START checking intersection------------------- let direct_connection_line = Line { p1: start_point, p2: end_point, }; let mut is_possible_direct_connection = true; obstacles_lines.iter().for_each(|obstacle_line| { if BasicUtils::check_intersection(&direct_connection_line, obstacle_line) { is_possible_direct_connection = false; }; }); // ------------END checking intersection------------------- if is_possible_direct_connection { vec![start_point, end_point] } else { TrackUtils::calc_complicated_track( start_point, end_point, ObstaclesLazyStatics::get_obstacles_points(), obstacles_lines, ObstaclesLazyStatics::get_permanent_connection_graph(), ) } } pub fn shift_track_from_obstacles<'a>(track: Vec<&'a Point>) -> Vec<(f32, f32)> { let last_index = track.len() - 1; track .iter() .enumerate() .map(|(index, point)| { if index == 0 || index == last_index { /* 1. find the nearest line 2. check if distance to the nearest line is less than NORMAL_SQUAD_RADIUS 3. if is less, then move point away by (NORMAL_SQUAD_RADIUS - distance) */ (point.x, point.y) } else { let previous_point = track[index - 1]; let next_point = track[index + 1]; let from_previous_point_angle = (point.x - previous_point.x).atan2(previous_point.y - point.y); let from_next_point_angle = (point.x - next_point.x).atan2(next_point.y - point.y); if (from_previous_point_angle - from_next_point_angle).abs() % MATH_PI <= std::f32::EPSILON { // straight line // in this case it's impossible to figure out, on // which site are obstacles (if are even on one site) // so we have to check manually let angle = from_previous_point_angle + MATH_PI / 2.0; let maybe_correct_point = ( (angle.sin() * NORMAL_SQUAD_RADIUS + point.x) as i16, (-angle.cos() * NORMAL_SQUAD_RADIUS + point.y) as i16, ); if CalcPositions::get_is_point_inside_any_obstacle( (maybe_correct_point.0, maybe_correct_point.1), false, ) { let correct_angle = angle + MATH_PI; ( correct_angle.sin() * NORMAL_SQUAD_RADIUS + point.x, -correct_angle.cos() * NORMAL_SQUAD_RADIUS + point.y, ) } else { ( angle.sin() * NORMAL_SQUAD_RADIUS + point.x, -angle.cos() * NORMAL_SQUAD_RADIUS + point.y, ) } } else { // https://rosettacode.org/wiki/Averages/Mean_angle#Rust let sin_mean = (from_previous_point_angle.sin() + from_next_point_angle.sin()) / 2.0; let cos_mean = (from_previous_point_angle.cos() + from_next_point_angle.cos()) / 2.0; let mean_angle = sin_mean.atan2(cos_mean); ( mean_angle.sin() * NORMAL_SQUAD_RADIUS + point.x, -mean_angle.cos() * NORMAL_SQUAD_RADIUS + point.y, ) } } }) .collect() } }
true
e7db6871b6fc1498e4fed3b1405d945b1782e199
Rust
maniankara/rustbyexample
/tutorial/23traits/24traits_derive.rs
UTF-8
353
3.40625
3
[ "Apache-2.0" ]
permissive
#[derive(PartialEq, PartialOrd, Debug)] struct Centimeters(f64); #[derive(Debug)] struct Inches(i32); impl Inches { fn to_cms(&self) -> Centimeters { let & Inches(inches) = self; Centimeters (inches as f64 * 2.54) } } fn main() { let inch = Inches(10); println!("{:?} inches is {:?} cms", inch, inch.to_cms()); }
true
ea57a09c80f8406fc291c248fb22bf2dda041359
Rust
Nystya/Rust-Lists
/src/second.rs
UTF-8
5,310
3.859375
4
[]
no_license
/* A slightly better implementation of a linked-list. It now uses Option to describe an empty list as None, and a non-empty list as Some<Box<Node<T>>> It now uses Option methods such as take(), as_ref() and as_deref() to access data in the the Option instead of mem::replace() This implementation also works with generics. */ pub struct List<T> { head: Link<T>, } type Link<T> = Option<Box<Node<T>>>; struct Node<T> { elem: T, next: Link<T>, } pub struct IntoIter<T>(List<T>); pub struct Iter<'a, T> { next: Option<&'a Node<T>>, } pub struct IterMut<'a, T> { next: Option<&'a mut Node<T>>, } impl<T> List<T> { pub fn new() -> Self { List { head: None, } } pub fn push(&mut self, elem: T) { let new_node = Box::new(Node { elem: elem, next: self.head.take(), }); self.head = Link::Some(new_node); } pub fn pop(&mut self) -> Option<T> { self.head.take().map(|node| { self.head = node.next; node.elem }) } pub fn peek(&self) -> Option<&T> { self.head.as_ref().map(|node| { &node.elem }) } pub fn peek_mut(&mut self) -> Option<&mut T> { self.head.as_mut().map(|node| { &mut node.elem }) } pub fn into_iter(self) -> IntoIter<T> { IntoIter(self) } pub fn iter(&self) -> Iter<'_, T> { Iter { next: self.head.as_deref() } } pub fn iter_mut(&mut self) -> IterMut<'_, T> { IterMut { next: self.head.as_deref_mut() } } } impl<T> Drop for List<T> { fn drop(&mut self) { let mut p = self.head.take(); while let Some(mut node) = p { p = node.next.take(); } } } impl<T> Iterator for IntoIter<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { self.0.pop() } } impl <'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.next.map(|node| { self.next = node.next.as_deref(); &node.elem }) } } impl <'a, T> Iterator for IterMut<'a, T> { type Item = &'a mut T; fn next(&mut self) -> Option<Self::Item> { self.next.take().map(|node| { self.next = node.next.as_deref_mut(); &mut node.elem }) } } #[cfg(test)] mod test { use super::List; #[test] fn basics() { // Create empty list let mut list = List::new(); // Check empty list works right assert_eq!(list.pop(), None); // Populate list list.push(1); list.push(2); list.push(3); assert_eq!(list.pop(), Some(3)); assert_eq!(list.pop(), Some(2)); // Push some more data list.push(4); list.push(5); assert_eq!(list.pop(), Some(5)); assert_eq!(list.pop(), Some(4)); assert_eq!(list.pop(), Some(1)); assert_eq!(list.pop(), None); } #[test] fn peek() { let mut list = List::new(); // Populate list list.push(1); list.push(2); list.push(3); assert_eq!(list.peek(), Some(&3)); assert_eq!(list.peek_mut(), Some(&mut 3)); list.peek_mut().map(|value| { *value = 42 }); assert_eq!(list.peek(), Some(&42)); } #[test] fn into_iter() { let mut list = List::new(); // Populate list list.push(1); list.push(2); list.push(3); let mut iter = list.into_iter(); assert_eq!(iter.next(), Some(3)); assert_eq!(iter.next(), Some(2)); assert_eq!(iter.next(), Some(1)); assert_eq!(iter.next(), None); } #[test] fn iter() { let mut list = List::new(); // Populate list list.push(1); list.push(2); list.push(3); let mut iter = list.iter(); assert_eq!(iter.next(), Some(&3)); assert_eq!(iter.next(), Some(&2)); assert_eq!(iter.next(), Some(&1)); assert_eq!(iter.next(), None); let mut iter = list.iter(); assert_eq!(iter.next(), Some(&3)); assert_eq!(iter.next(), Some(&2)); assert_eq!(iter.next(), Some(&1)); assert_eq!(iter.next(), None); } #[test] fn iter_mut() { let mut list = List::new(); // Populate list list.push(1); list.push(2); list.push(3); let mut iter = list.iter_mut(); assert_eq!(iter.next(), Some(&mut 3)); assert_eq!(iter.next(), Some(&mut 2)); assert_eq!(iter.next(), Some(&mut 1)); assert_eq!(iter.next(), None); let mut iter = list.iter_mut(); iter.next().map(|value| { *value = 41 }); iter.next().map(|value| { *value = 42 }); iter.next().map(|value| { *value = 43 }); let mut iter = list.iter_mut(); assert_eq!(iter.next(), Some(&mut 41)); assert_eq!(iter.next(), Some(&mut 42)); assert_eq!(iter.next(), Some(&mut 43)); assert_eq!(iter.next(), None); } }
true
3cc6d29da8a571d133df5260116191846fb20a95
Rust
pelian/bn-api
/db/tests/unit/venues.rs
UTF-8
7,832
2.9375
3
[ "BSD-3-Clause" ]
permissive
use bigneon_db::dev::TestProject; use bigneon_db::prelude::*; use bigneon_db::utils::errors::ErrorCode::ValidationError; #[test] fn commit() { let project = TestProject::new(); let name = "Name"; let venue = Venue::create(name.clone(), None, None, "America/Los_Angeles".into()) .commit(project.get_connection()) .unwrap(); assert_eq!(venue.name, name); assert_eq!(venue.id.to_string().is_empty(), false); } #[test] fn new_venue_with_validation_errors() { let project = TestProject::new(); let name = "Name"; let venue = Venue::create(name.clone(), None, None, "".into()); let result = venue.commit(project.get_connection()); match result { Ok(_) => { panic!("Expected validation error"); } Err(error) => match &error.error_code { ValidationError { errors } => { assert!(errors.contains_key("timezone")); assert_eq!(errors["timezone"].len(), 1); assert_eq!(errors["timezone"][0].code, "length"); } _ => panic!("Expected validation error"), }, } } #[test] fn update_with_validation_errors() { let project = TestProject::new(); let venue = project.create_venue().finish(); let parameters = VenueEditableAttributes { timezone: Some("".to_string()), ..Default::default() }; let result = venue.update(parameters, project.get_connection()); match result { Ok(_) => { panic!("Expected validation error"); } Err(error) => match &error.error_code { ValidationError { errors } => { assert!(errors.contains_key("timezone")); assert_eq!(errors["timezone"].len(), 1); assert_eq!(errors["timezone"][0].code, "length"); } _ => panic!("Expected validation error"), }, } } #[test] fn update() { let project = TestProject::new(); let venue = project.create_venue().finish(); let new_name = "New Venue Name"; let new_address = "Test Address"; let parameters = VenueEditableAttributes { name: Some(new_name.to_string()), address: Some(new_address.to_string()), ..Default::default() }; let updated_venue = venue.update(parameters, project.get_connection()).unwrap(); assert_eq!(updated_venue.name, new_name); assert_eq!(updated_venue.address, new_address); } #[test] fn set_privacy() { let project = TestProject::new(); let connection = project.get_connection(); let mut venue = project.create_venue().finish(); assert!(!venue.is_private); venue = venue.set_privacy(true, connection).unwrap(); assert!(venue.is_private); venue = venue.set_privacy(false, connection).unwrap(); assert!(!venue.is_private); } #[test] fn find() { let project = TestProject::new(); let venue = project.create_venue().finish(); let found_venue = Venue::find(venue.id, project.get_connection()).unwrap(); assert_eq!(venue, found_venue); } #[test] fn find_by_ids() { let project = TestProject::new(); let venue = project .create_venue() .with_name("Venue1".to_string()) .finish(); let _ = project .create_venue() .with_name("Venue2".to_string()) .finish(); let venue3 = project .create_venue() .with_name("Venue3".to_string()) .finish(); let mut expected_venues = vec![venue.clone(), venue3.clone()]; expected_venues.sort_by_key(|v| v.id); let found_venues = Venue::find_by_ids(vec![venue.id, venue3.id], &project.get_connection()).unwrap(); assert_eq!(expected_venues, found_venues); } #[test] fn all() { let project = TestProject::new(); let venue = project .create_venue() .with_name("Venue1".to_string()) .finish(); let venue2 = project .create_venue() .with_name("Venue2".to_string()) .finish(); let organization = project.create_organization().finish(); let conn = &project.get_connection(); let all_found_venues = Venue::all(None, conn).unwrap(); let mut all_venues = vec![venue, venue2]; assert_eq!(all_venues, all_found_venues); let venue3 = project .create_venue() .with_name("Venue3".to_string()) .make_private() .finish(); let venue3 = venue3.add_to_organization(&organization.id, conn); let user = project.create_user().finish(); let _org_user = organization .add_user(user.id, vec![Roles::OrgMember], Vec::new(), conn) .unwrap(); all_venues.push(venue3.unwrap()); let all_found_venues = Venue::all(Some(&user), conn).unwrap(); assert_eq!(all_venues, all_found_venues); let all_found_venues = Venue::all(Some(&User::find(user.id, conn).unwrap()), conn).unwrap(); assert_eq!(all_venues, all_found_venues); } #[test] fn find_for_organization() { let project = TestProject::new(); let owner = project.create_user().finish(); let member = project.create_user().finish(); let user = project.create_user().finish(); let organization = project .create_organization() .with_member(&owner, Roles::OrgOwner) .with_member(&member, Roles::OrgMember) .finish(); let venue1 = project .create_venue() .with_name("Venue1".to_string()) .with_organization(&organization) .finish(); let venue2 = project .create_venue() .with_name("Venue2".to_string()) .with_organization(&organization) .finish(); let venue3 = project .create_venue() .with_name("Venue3".to_string()) .with_organization(&organization) .make_private() .finish(); // Add another venue for another org to make sure it isn't included let organization2 = project .create_organization() .with_member(&user, Roles::OrgOwner) .finish(); let venue4 = project .create_venue() .with_name("Venue4".to_string()) .with_organization(&organization2) .finish(); let user = project.create_user().finish(); let mut all_venues = vec![venue1, venue2]; let found_venues = Venue::find_for_organization(None, organization.id, project.get_connection()).unwrap(); assert_eq!(found_venues, all_venues); let found_venues = Venue::find_for_organization(None, organization.id, project.get_connection()).unwrap(); assert_eq!(found_venues, all_venues); assert!(!found_venues.contains(&venue3)); assert!(!found_venues.contains(&venue4)); // Private venue is not shown for users let found_venues = Venue::find_for_organization(Some(user.id), organization.id, project.get_connection()) .unwrap(); assert_eq!(found_venues, all_venues); // Private venue is shown for owners and members all_venues.push(venue3); let found_venues = Venue::find_for_organization(Some(owner.id), organization.id, project.get_connection()) .unwrap(); assert_eq!(found_venues, all_venues); let found_venues = Venue::find_for_organization(Some(member.id), organization.id, project.get_connection()) .unwrap(); assert_eq!(found_venues, all_venues); } #[test] fn organization() { let project = TestProject::new(); let organization = project.create_organization().finish(); let venue = project .create_venue() .with_organization(&organization) .finish(); let venue2 = project.create_venue().finish(); assert_eq!( Ok(Some(organization)), venue.organization(project.get_connection()) ); assert_eq!(Ok(None), venue2.organization(project.get_connection())); }
true
36fc8c709598fbffa072e52e0bcae2dd7e84cf62
Rust
mgxm/datafusion-rs
/src/bin/console/main.rs
UTF-8
4,334
2.6875
3
[ "Apache-2.0" ]
permissive
extern crate clap; extern crate datafusion; extern crate rprompt; extern crate serde; extern crate serde_json; use std::fs::File; use std::io::BufReader; use std::io::BufRead; use std::str; use std::time::Instant; use clap::{Arg, App}; use datafusion::exec::*; use datafusion::parser::*; use datafusion::sql::ASTNode::SQLCreateTable; const VERSION: &'static str = env!("CARGO_PKG_VERSION"); fn main() { println!("DataFusion Console"); let cmdline = App::new("DataFusion Console") .version(VERSION) .arg(Arg::with_name("ETCD") .help("etcd endpoints") .short("e") .long("etcd") .value_name("URL") .required(true) .takes_value(true)) .arg(Arg::with_name("SCRIPT") .help("SQL script to run") .short("s") .long("script") .required(false) .takes_value(true)) .get_matches(); // parse args let etcd_endpoints = cmdline.value_of("ETCD").unwrap(); let mut console = Console::new(etcd_endpoints.to_string()); match cmdline.value_of("SCRIPT") { Some(filename) => { match File::open(filename) { Ok(f) => { let mut reader = BufReader::new(&f); for line in reader.lines() { match line { Ok(cmd) => console.execute(&cmd), Err(e) => println!("Error: {}", e) } } }, Err(e) => println!("Could not open file {}: {}", filename, e) } }, None => { loop { match rprompt::prompt_reply_stdout("$ ") { Ok(command) => match command.as_ref() { "exit" | "quit" => break, _ => console.execute(&command) }, Err(e) => println!("Error parsing command: {:?}", e) } } } } } /// Interactive SQL console struct Console { ctx: ExecutionContext } impl Console { fn new(etcd: String) -> Self { Console { ctx: ExecutionContext::remote(etcd) } } /// Execute a SQL statement or console command fn execute(&mut self, sql: &str) { println!("Executing query ..."); let timer = Instant::now(); // parse the SQL match Parser::parse_sql(String::from(sql)) { Ok(ast) => match ast { SQLCreateTable { .. } => { self.ctx.sql(&sql).unwrap(); println!("Registered schema with execution context"); () }, _ => { match self.ctx.create_logical_plan(sql) { Ok(logical_plan) => { let physical_plan = PhysicalPlan::Interactive { plan: logical_plan }; let result = self.ctx.execute(&physical_plan); match result { Ok(result) => { let elapsed = timer.elapsed(); let elapsed_seconds = elapsed.as_secs() as f64 + elapsed.subsec_nanos() as f64 / 1000000000.0; match result { ExecutionResult::Unit => { println!("Query executed in {} seconds", elapsed_seconds); } ExecutionResult::Count(n) => { println!("Query executed in {} seconds and updated {} rows", elapsed_seconds, n); } } }, Err(e) => println!("Error: {:?}", e) } } Err(e) => println!("Error: {:?}", e) } } } Err(e) => println!("Error: {:?}", e) } } }
true
e918fe1e4c31121defc5d931b2b4514cb25c5e2e
Rust
boylede/aoc2019
/src/day12/mod.rs
UTF-8
4,133
3.09375
3
[]
no_license
use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::collections::HashMap; use std::collections::HashSet; use aoc2019::Day; const DAY: i32 = 12; fn calculate_energy([x, y, z]: [i32;3]) -> i32 { // println!("{} + {} + {} = {}", x.abs(), y.abs(), z.abs(), x.abs() + y.abs() + z.abs()); x.abs() + y.abs() + z.abs() } fn print(pos: &Vec<[i32;3]>, vel: &Vec<[i32;3]>, num: usize) { println!("after {}", num); pos.iter().zip(vel.iter()).for_each(|(p, v)| { println!("pos: {:?} vel: {:?}", p, v); }); println!(""); } fn part1(lines: &Vec<String>) { // let lines = vec!["<x=-1, y=0, z=2>","<x=2, y=-10, z=-7>","<x=4, y=-8, z=8>","<x=3, y=5, z=-1>"]; // let lines = vec!["<x=-8, y=-10, z=0>","<x=5, y=5, z=10>","<x=2, y=-7, z=3>","<x=9, y=-8, z=-3>"]; let mut moon_positions : Vec<[i32;3]> = lines.iter().map(|line| { let mut parts: Vec<String> = line.split(",").map(|s|s.to_string()).collect(); let x = parts[0].split_off(3).parse::<i32>().unwrap(); let y = parts[1].split_off(3).parse::<i32>().unwrap(); let mut z = parts[2].split_off(3); z.pop(); let z = z.parse::<i32>().unwrap(); // println!("{}, {}, {}", x, y, z); [x, y, z] // (1, 2, 3) }).collect(); let mut moon_velocities : Vec<[i32;3]> = vec![[0;3];4]; for turn in 0..1000 { // print(&moon_positions, &moon_velocities, turn); //gravity for (i, moon) in moon_positions.iter().enumerate() { for (j, other) in moon_positions.iter().enumerate() { if i != j { // println!("comparing {} with {}", i, j); for axis in 0..3 { if moon[axis] > other[axis] { moon_velocities[i][axis] -= 1; // moon_velocities[j][axis] += 1; } else if moon[axis] < other[axis]{ // moon_velocities[j][axis] -= 1; moon_velocities[i][axis] += 1; } } } } } // velocity for (i, moon) in moon_velocities.iter().enumerate() { for axis in 0..3 { moon_positions[i][axis] += moon[axis]; } } } // print(&moon_positions, &moon_velocities, 100); let total_energy = moon_positions.iter().zip(moon_velocities.iter()).fold(0, |t, (pos, vel)| { let p = calculate_energy(*pos); let v = calculate_energy(*vel); t + (p * v) }); // println("pot: {}", potential_energy); // let kinetic_energy = moon_velocities.iter().fold(0, |t, moon| { // let e = calculate_energy(*moon); // t + e // }); // println!("pot: {}, kin: {}, *= {}", total_energy, kinetic_energy, potential_energy * kinetic_energy); // let total_energy = potential_energy * kinetic_energy; println!("Part 1: {:?}", total_energy); } fn part2(lines: &Vec<String>) { println!("Part 2: {}", 0); } pub fn load(days_array: &mut Vec<Day>) { days_array.push(Day::new(DAY, run)); } pub fn run(input: File) { println!("loading day {} input.", DAY); let a_time = time::precise_time_ns(); let mut lines = vec![]; { let mut lines_iterator = BufReader::new(&input).lines(); while let Some(Ok(line)) = lines_iterator.next() { lines.push(line); } } let b_time = time::precise_time_ns(); let total_time = b_time - a_time; if total_time > 100000 { println!("Loading took: {}ms", total_time as f32 / 1000000.0); } else { println!("Loading took: {}ns", total_time); } post_load(lines); } fn post_load(lines: Vec<String>) { let a_time = time::precise_time_ns(); part1(&lines); let b_time = time::precise_time_ns(); part2(&lines); let c_time = time::precise_time_ns(); println!("Day {} Part 1 took: {}ns", DAY, b_time - a_time); println!("Day {} Part 2 took: {}ns", DAY, c_time - b_time); } #[test] pub fn tests() {}
true
475cc38c285ca2d5b80baf5c787d697711896f4f
Rust
mrnugget/risp
/src/main.rs
UTF-8
556
2.703125
3
[]
no_license
#![allow(dead_code)] use std::io; use std::io::prelude::*; mod evaluator; mod object; mod reader; fn main() -> io::Result<()> { const PROMPT: &str = "> "; loop { print!("{}", PROMPT); io::stdout().flush()?; let mut input = String::new(); io::stdin().read_line(&mut input)?; match reader::read(&input) { Ok(objects) => { objects.iter().for_each(|object| println!("{}", object)); } Err(e) => println!("Something went wrong: {}", e), }; } }
true
c758cbe494fa99293dfc9b4b37cdc28d6485ebc1
Rust
zthompson47/tapedeck
/src/bin/tdsearch.rs
UTF-8
4,898
2.703125
3
[]
no_license
use std::{cmp::Ordering, collections::HashMap, convert::TryFrom, path::PathBuf, time::SystemTime}; use clap::Parser; use crossterm::style::Stylize; //use structopt::StructOpt; use tokio::runtime::Runtime; use walkdir::WalkDir; use tapedeck::{ audio_dir::{MaybeFetched, MediaDir, MediaFile, MediaType}, database::Store, logging, }; #[derive(Parser)] struct Cli { #[arg(short, long)] list: bool, search_path: Option<PathBuf>, } fn main() -> Result<(), anyhow::Error> { let _log = logging::init(); tracing::info!("Start tdsearch"); let args = Cli::parse(); let rt = Runtime::new()?; if args.list { rt.block_on(list_dirs())?; } else if let Some(path) = args.search_path { rt.block_on(import_dirs(path))?; } Ok(()) } /// Get all audio_dir records from the database and print them to stdout. async fn list_dirs() -> Result<(), anyhow::Error> { let store = Store::new()?; let audio_dirs = MediaDir::get_audio_dirs(&store)?; for dir in audio_dirs.iter() { println!( "{}. {}", // All AudioDir from the database have `id` &dir.id.unwrap().to_string().magenta(), &dir.location.to_string_lossy(), ); } Ok(()) } /// Search search_path for audio directories and save to database. async fn import_dirs(search_path: PathBuf) -> Result<(), anyhow::Error> { let store = Store::new()?; let mut mime_type_count: HashMap<String, usize> = HashMap::new(); let mut new_files: Vec<MediaFile> = Vec::new(); let mut found_audio = false; // Sort directories-first with file entries forming an alpahbetized // contiguous list followed by their parent directory. for entry in WalkDir::new(search_path) .contents_first(true) .sort_by( |a, b| match (a.file_type().is_dir(), b.file_type().is_dir()) { (true, false) => Ordering::Less, (false, true) => Ordering::Greater, (true, true) | (false, false) => a.file_name().cmp(b.file_name()), }, ) .into_iter() .flatten() { let path = entry.path(); let guess = mime_guess::from_path(path); // Try to identify file by mime type if let Some(guess) = guess.first() { if guess.type_() == "audio" { found_audio = true; } if ["audio", "text"].contains(&guess.type_().as_str()) { // Count by mime type for summary output let counter = mime_type_count .entry(guess.essence_str().to_string()) .or_insert(0); *counter += 1; // Create new AudioFile new_files.push(MediaFile { id: None, location: path.as_os_str().to_owned(), media_type: MediaType::Audio(guess.clone()), file_size: i64::try_from(entry.metadata()?.len()).ok(), directory: MaybeFetched::None, }); } } // Look for non-mime support files if path.is_file() { if let Some(ext) = path.extension() { if ["md5", "st5"].contains(&ext.to_str().unwrap_or("")) { new_files.push(MediaFile { id: None, location: path.as_os_str().to_owned(), media_type: MediaType::Checksum(ext.to_os_string()), file_size: i64::try_from(entry.metadata()?.len()).ok(), directory: MaybeFetched::None, }); } } } // Fold each completed directory into results if path.is_dir() { if found_audio { found_audio = false; // Create new MediaDir let mut audio_dir = MediaDir::from(path.to_owned()); audio_dir.extend(std::mem::take(&mut new_files)); //audio_dir.last_modified = timestamp(entry.metadata()?.modified()?); audio_dir.last_modified = entry .metadata()? .modified()? .duration_since(SystemTime::UNIX_EPOCH)? .as_millis() as u64; // Insert into database match audio_dir.db_insert(&store) { Ok(_) => print!("{}", &audio_dir), Err(_) => println!("dup"), // TODO } } else { new_files.clear(); } } } println!("{mime_type_count:#?}"); Ok(()) } /* use chrono::{DateTime, Utc}; use std::time::SystemTime; fn timestamp(t: SystemTime) -> i64 { let utc: DateTime<Utc> = DateTime::from(t); utc.timestamp_millis() } */
true
af11e94b14a2f916d766fd85b49e91f3c7757170
Rust
vamolessa/ase-rs
/src/chunk/cel_extra_chunk.rs
UTF-8
1,495
2.84375
3
[ "MIT" ]
permissive
use std::io::{self, Read, Seek, SeekFrom, Write}; use bitflags::bitflags; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; bitflags! { pub struct Flags: u32 { const PreciseBounds = 1; } } #[derive(Debug)] pub struct CelExtraChunk { pub flags: Flags, pub precise_x_position: f32, pub precise_y_position: f32, pub width: f32, pub height: f32, } impl CelExtraChunk { pub fn from_read<R>(read: &mut R) -> io::Result<Self> where R: Read + Seek, { let flags = Flags::from_bits_truncate(read.read_u32::<LittleEndian>()?); let precise_x_position = read.read_f32::<LittleEndian>()?; let precise_y_position = read.read_f32::<LittleEndian>()?; let width = read.read_f32::<LittleEndian>()?; let height = read.read_f32::<LittleEndian>()?; read.seek(SeekFrom::Current(16))?; Ok(Self { flags, precise_x_position, precise_y_position, width, height, }) } pub fn write<W>(&self, wtr: &mut W) -> io::Result<()> where W: Write + Seek, { wtr.write_u32::<LittleEndian>(self.flags.bits)?; wtr.write_f32::<LittleEndian>(self.precise_x_position)?; wtr.write_f32::<LittleEndian>(self.precise_y_position)?; wtr.write_f32::<LittleEndian>(self.width)?; wtr.write_f32::<LittleEndian>(self.height)?; wtr.seek(SeekFrom::Current(16))?; Ok(()) } }
true
2a0227dabe91a3357c29d57df5b751d40d6d69d6
Rust
rust-lang/rust-analyzer
/crates/ide-ssr/src/replacing.rs
UTF-8
9,884
2.859375
3
[ "Apache-2.0", "MIT" ]
permissive
//! Code for applying replacement templates for matches that have previously been found. use ide_db::{FxHashMap, FxHashSet}; use itertools::Itertools; use syntax::{ ast::{self, AstNode, AstToken}, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken, TextRange, TextSize, }; use text_edit::TextEdit; use crate::{fragments, resolving::ResolvedRule, Match, SsrMatches}; /// Returns a text edit that will replace each match in `matches` with its corresponding replacement /// template. Placeholders in the template will have been substituted with whatever they matched to /// in the original code. pub(crate) fn matches_to_edit( db: &dyn hir::db::ExpandDatabase, matches: &SsrMatches, file_src: &str, rules: &[ResolvedRule], ) -> TextEdit { matches_to_edit_at_offset(db, matches, file_src, 0.into(), rules) } fn matches_to_edit_at_offset( db: &dyn hir::db::ExpandDatabase, matches: &SsrMatches, file_src: &str, relative_start: TextSize, rules: &[ResolvedRule], ) -> TextEdit { let mut edit_builder = TextEdit::builder(); for m in &matches.matches { edit_builder.replace( m.range.range.checked_sub(relative_start).unwrap(), render_replace(db, m, file_src, rules), ); } edit_builder.finish() } struct ReplacementRenderer<'a> { db: &'a dyn hir::db::ExpandDatabase, match_info: &'a Match, file_src: &'a str, rules: &'a [ResolvedRule], rule: &'a ResolvedRule, out: String, // Map from a range within `out` to a token in `template` that represents a placeholder. This is // used to validate that the generated source code doesn't split any placeholder expansions (see // below). placeholder_tokens_by_range: FxHashMap<TextRange, SyntaxToken>, // Which placeholder tokens need to be wrapped in parenthesis in order to ensure that when `out` // is parsed, placeholders don't get split. e.g. if a template of `$a.to_string()` results in `1 // + 2.to_string()` then the placeholder value `1 + 2` was split and needs parenthesis. placeholder_tokens_requiring_parenthesis: FxHashSet<SyntaxToken>, } fn render_replace( db: &dyn hir::db::ExpandDatabase, match_info: &Match, file_src: &str, rules: &[ResolvedRule], ) -> String { let rule = &rules[match_info.rule_index]; let template = rule .template .as_ref() .expect("You called MatchFinder::edits after calling MatchFinder::add_search_pattern"); let mut renderer = ReplacementRenderer { db, match_info, file_src, rules, rule, out: String::new(), placeholder_tokens_requiring_parenthesis: FxHashSet::default(), placeholder_tokens_by_range: FxHashMap::default(), }; renderer.render_node(&template.node); renderer.maybe_rerender_with_extra_parenthesis(&template.node); for comment in &match_info.ignored_comments { renderer.out.push_str(&comment.syntax().to_string()); } renderer.out } impl ReplacementRenderer<'_> { fn render_node_children(&mut self, node: &SyntaxNode) { for node_or_token in node.children_with_tokens() { self.render_node_or_token(&node_or_token); } } fn render_node_or_token(&mut self, node_or_token: &SyntaxElement) { match node_or_token { SyntaxElement::Token(token) => { self.render_token(token); } SyntaxElement::Node(child_node) => { self.render_node(child_node); } } } fn render_node(&mut self, node: &SyntaxNode) { if let Some(mod_path) = self.match_info.rendered_template_paths.get(node) { self.out.push_str(&mod_path.display(self.db).to_string()); // Emit everything except for the segment's name-ref, since we already effectively // emitted that as part of `mod_path`. if let Some(path) = ast::Path::cast(node.clone()) { if let Some(segment) = path.segment() { for node_or_token in segment.syntax().children_with_tokens() { if node_or_token.kind() != SyntaxKind::NAME_REF { self.render_node_or_token(&node_or_token); } } } } } else { self.render_node_children(node); } } fn render_token(&mut self, token: &SyntaxToken) { if let Some(placeholder) = self.rule.get_placeholder(token) { if let Some(placeholder_value) = self.match_info.placeholder_values.get(&placeholder.ident) { let range = &placeholder_value.range.range; let mut matched_text = self.file_src[usize::from(range.start())..usize::from(range.end())].to_owned(); // If a method call is performed directly on the placeholder, then autoderef and // autoref will apply, so we can just substitute whatever the placeholder matched to // directly. If we're not applying a method call, then we need to add explicitly // deref and ref in order to match whatever was being done implicitly at the match // site. if !token_is_method_call_receiver(token) && (placeholder_value.autoderef_count > 0 || placeholder_value.autoref_kind != ast::SelfParamKind::Owned) { cov_mark::hit!(replace_autoref_autoderef_capture); let ref_kind = match placeholder_value.autoref_kind { ast::SelfParamKind::Owned => "", ast::SelfParamKind::Ref => "&", ast::SelfParamKind::MutRef => "&mut ", }; matched_text = format!( "{}{}{}", ref_kind, "*".repeat(placeholder_value.autoderef_count), matched_text ); } let edit = matches_to_edit_at_offset( self.db, &placeholder_value.inner_matches, self.file_src, range.start(), self.rules, ); let needs_parenthesis = self.placeholder_tokens_requiring_parenthesis.contains(token); edit.apply(&mut matched_text); if needs_parenthesis { self.out.push('('); } self.placeholder_tokens_by_range.insert( TextRange::new( TextSize::of(&self.out), TextSize::of(&self.out) + TextSize::of(&matched_text), ), token.clone(), ); self.out.push_str(&matched_text); if needs_parenthesis { self.out.push(')'); } } else { // We validated that all placeholder references were valid before we // started, so this shouldn't happen. panic!( "Internal error: replacement referenced unknown placeholder {}", placeholder.ident ); } } else { self.out.push_str(token.text()); } } // Checks if the resulting code, when parsed doesn't split any placeholders due to different // order of operations between the search pattern and the replacement template. If any do, then // we rerender the template and wrap the problematic placeholders with parenthesis. fn maybe_rerender_with_extra_parenthesis(&mut self, template: &SyntaxNode) { if let Some(node) = parse_as_kind(&self.out, template.kind()) { self.remove_node_ranges(node); if self.placeholder_tokens_by_range.is_empty() { return; } self.placeholder_tokens_requiring_parenthesis = self.placeholder_tokens_by_range.values().cloned().collect(); self.out.clear(); self.render_node(template); } } fn remove_node_ranges(&mut self, node: SyntaxNode) { self.placeholder_tokens_by_range.remove(&node.text_range()); for child in node.children() { self.remove_node_ranges(child); } } } /// Returns whether token is the receiver of a method call. Note, being within the receiver of a /// method call doesn't count. e.g. if the token is `$a`, then `$a.foo()` will return true, while /// `($a + $b).foo()` or `x.foo($a)` will return false. fn token_is_method_call_receiver(token: &SyntaxToken) -> bool { // Find the first method call among the ancestors of `token`, then check if the only token // within the receiver is `token`. if let Some(receiver) = token .parent_ancestors() .find_map(ast::MethodCallExpr::cast) .and_then(|call| call.receiver()) { let tokens = receiver.syntax().descendants_with_tokens().filter_map(|node_or_token| { match node_or_token { SyntaxElement::Token(t) => Some(t), _ => None, } }); if let Some((only_token,)) = tokens.collect_tuple() { return only_token == *token; } } false } fn parse_as_kind(code: &str, kind: SyntaxKind) -> Option<SyntaxNode> { if ast::Expr::can_cast(kind) { if let Ok(expr) = fragments::expr(code) { return Some(expr); } } if ast::Item::can_cast(kind) { if let Ok(item) = fragments::item(code) { return Some(item); } } None }
true
6fa8642ab57b7ea1599735c1ad19b8669eda6c83
Rust
tawaren/Sanskrit
/sanskrit_bench/src/bench/opcodes/ret.rs
UTF-8
3,818
2.8125
3
[]
no_license
use test::Bencher; use std::sync::Mutex; use std::collections::BTreeMap; use crate::test_utils::{bench_ops, measure_ops, Interpolator}; use sanskrit_interpreter::model::{OpCode, Kind}; use sanskrit_common::model::ValueRef; use crate::bench::opcodes::op::{Op, OpTest}; use sanskrit_common::arena::VirtualHeapArena; //9-10 + 25-30*fields -> roundto: 15 + 25*fields // Note: 30 is only for the lower numbers: so we counteract by using base of 15 instead of 10 // Note: with that formula we charge 35 to few with 64 fields correct would be: 25.5 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] pub struct ReturnTest(usize,usize); impl Op for ReturnTest { fn get_kind(&self) -> Kind { Kind::U8} fn get_params(&self) -> usize { self.1 } fn get_base_num(&self) -> isize { 0 } fn get_repeats(&self) -> usize { self.0 } fn build_opcode<'b>(&self, iter: usize, alloc:&'b VirtualHeapArena) -> OpCode<'b> { let mut builder = alloc.slice_builder(self.1).unwrap(); let base = iter*self.1; for i in 0..self.1 { builder.push(ValueRef((base + i) as u16)); } OpCode::Return(builder.finish()) } } lazy_static! { pub static ref MEASURE_CACHE: Mutex<BTreeMap<OpTest<ReturnTest>, u128>> = Mutex::new(BTreeMap::new()); } pub fn measure(test:OpTest<ReturnTest>, loops:usize) -> u128 { let mut cache = MEASURE_CACHE.lock().unwrap(); if !cache.contains_key(&test){ cache.insert(test, measure_ops(test, loops).unwrap()); } *cache.get(&test).unwrap() } pub fn test(rep:usize, returns:u8) -> OpTest<ReturnTest> { OpTest(ReturnTest(rep, returns as usize))} pub fn measure_gas(loops:usize) { let op = "Return"; let base = measure(test(1000,0), loops) as i128; println!("{}Params{} - {}", op, 0, base/1000); let mut inter = Interpolator::new(base,0); let trials = vec![1,4,16,32,64]; for i in &trials { let res = measure(test(1000,*i as u8), loops) as i128; println!("{}Params{} - {}", op, i, res/1000); inter.add_measure(res, *i); } println!("{} - {} + {}*params", op, base/1000, inter.eval()/1000.0) } mod f0 { use super::*; const FIELDS:u8 = 0; #[bench] fn bench_0(b: &mut Bencher) { bench_ops(test(0, FIELDS), b).unwrap()} #[bench] fn bench_500(b: &mut Bencher) { bench_ops(test(500, FIELDS), b).unwrap()} #[bench] fn bench_1000(b: &mut Bencher) { bench_ops(test(1000, FIELDS), b).unwrap()} } mod f1 { use super::*; const FIELDS:u8 = 1; #[bench] fn bench_0(b: &mut Bencher) { bench_ops(test(0, FIELDS), b).unwrap()} #[bench] fn bench_500(b: &mut Bencher) { bench_ops(test(500, FIELDS), b).unwrap()} #[bench] fn bench_1000(b: &mut Bencher) { bench_ops(test(1000, FIELDS), b).unwrap()} } mod f4 { use super::*; const FIELDS:u8 = 4; #[bench] fn bench_0(b: &mut Bencher) { bench_ops(test(0, FIELDS), b).unwrap()} #[bench] fn bench_500(b: &mut Bencher) { bench_ops(test(500, FIELDS), b).unwrap()} #[bench] fn bench_1000(b: &mut Bencher) { bench_ops(test(1000, FIELDS), b).unwrap()} } mod f16 { use super::*; const FIELDS:u8 = 16; #[bench] fn bench_0(b: &mut Bencher) { bench_ops(test(0, FIELDS), b).unwrap()} #[bench] fn bench_500(b: &mut Bencher) { bench_ops(test(500, FIELDS), b).unwrap()} #[bench] fn bench_1000(b: &mut Bencher) { bench_ops(test(1000, FIELDS), b).unwrap()} } mod f64 { use super::*; const FIELDS:u8 = 64; #[bench] fn bench_0(b: &mut Bencher) { bench_ops(test(0, FIELDS), b).unwrap()} #[bench] fn bench_500(b: &mut Bencher) { bench_ops(test(500, FIELDS), b).unwrap()} #[bench] fn bench_1000(b: &mut Bencher) { bench_ops(test(1000, FIELDS), b).unwrap()} }
true
1a6e89c0160b740ec42ba9a74115b320454eb30d
Rust
namachan10777/lindera
/lindera-core/src/core/connection.rs
UTF-8
684
2.84375
3
[ "MIT" ]
permissive
use byteorder::{ByteOrder, LittleEndian}; #[derive(Clone)] pub struct ConnectionCostMatrix { pub costs_data: Vec<u8>, pub backward_size: u32, } impl ConnectionCostMatrix { pub fn load(conn_data: &[u8]) -> ConnectionCostMatrix { let backward_size = LittleEndian::read_i16(&conn_data[2..4]); ConnectionCostMatrix { costs_data: conn_data[4..].to_vec(), backward_size: backward_size as u32, } } pub fn cost(&self, forward_id: u32, backward_id: u32) -> i32 { let cost_id = (backward_id + forward_id * self.backward_size) as usize; LittleEndian::read_i16(&self.costs_data[cost_id * 2..]) as i32 } }
true
1a3f8799cb75a0a93138da831ac92626901d1f22
Rust
jackcmay/solana
/perf/src/deduper.rs
UTF-8
6,116
2.8125
3
[ "Apache-2.0" ]
permissive
//! Utility to deduplicate baches of incoming network packets. use { crate::packet::{Packet, PacketBatch}, ahash::AHasher, rand::{thread_rng, Rng}, solana_sdk::saturating_add_assign, std::{ convert::TryFrom, hash::Hasher, sync::atomic::{AtomicBool, AtomicU64, Ordering}, time::{Duration, Instant}, }, }; pub struct Deduper { filter: Vec<AtomicU64>, seed: (u128, u128), age: Instant, max_age: Duration, pub saturated: AtomicBool, } impl Deduper { pub fn new(size: u32, max_age: Duration) -> Self { let mut filter: Vec<AtomicU64> = Vec::with_capacity(size as usize); filter.resize_with(size as usize, Default::default); let seed = thread_rng().gen(); Self { filter, seed, age: Instant::now(), max_age, saturated: AtomicBool::new(false), } } pub fn reset(&mut self) { let now = Instant::now(); //this should reset every 500k unique packets per 1m sized deduper //false positive rate is 1/1000 at that point let saturated = self.saturated.load(Ordering::Relaxed); if saturated || now.duration_since(self.age) > self.max_age { let len = self.filter.len(); self.filter.clear(); self.filter.resize_with(len, AtomicU64::default); self.seed = thread_rng().gen(); self.age = now; self.saturated.store(false, Ordering::Relaxed); } } /// Compute hash from packet data, returns (hash, bin_pos). fn compute_hash(&self, packet: &Packet) -> (u64, usize) { let mut hasher = AHasher::new_with_keys(self.seed.0, self.seed.1); hasher.write(packet.data(..).unwrap_or_default()); let h = hasher.finish(); let len = self.filter.len(); let pos = (usize::try_from(h).unwrap()).wrapping_rem(len); (h, pos) } // Deduplicates packets and returns 1 if packet is to be discarded. Else, 0. fn dedup_packet(&self, packet: &mut Packet) -> u64 { // If this packet was already marked as discard, drop it if packet.meta().discard() { return 1; } let (hash, pos) = self.compute_hash(packet); // saturate each position with or let prev = self.filter[pos].fetch_or(hash, Ordering::Relaxed); if prev == u64::MAX { self.saturated.store(true, Ordering::Relaxed); //reset this value self.filter[pos].store(hash, Ordering::Relaxed); } if hash == prev & hash { packet.meta_mut().set_discard(true); return 1; } 0 } pub fn dedup_packets_and_count_discards( &self, batches: &mut [PacketBatch], mut process_received_packet: impl FnMut(&mut Packet, bool, bool), ) -> u64 { let mut num_removed: u64 = 0; batches.iter_mut().for_each(|batch| { batch.iter_mut().for_each(|p| { let removed_before_sigverify = p.meta().discard(); let is_duplicate = self.dedup_packet(p); if is_duplicate == 1 { saturating_add_assign!(num_removed, 1); } process_received_packet(p, removed_before_sigverify, is_duplicate == 1); }) }); num_removed } } #[cfg(test)] #[allow(clippy::integer_arithmetic)] mod tests { use { super::*, crate::{packet::to_packet_batches, sigverify, test_tx::test_tx}, }; #[test] fn test_dedup_same() { let tx = test_tx(); let mut batches = to_packet_batches(&std::iter::repeat(tx).take(1024).collect::<Vec<_>>(), 128); let packet_count = sigverify::count_packets_in_batches(&batches); let filter = Deduper::new(1_000_000, Duration::from_millis(0)); let mut num_deduped = 0; let discard = filter.dedup_packets_and_count_discards( &mut batches, |_deduped_packet, _removed_before_sigverify_stage, _is_dup| { num_deduped += 1; }, ) as usize; assert_eq!(num_deduped, discard + 1); assert_eq!(packet_count, discard + 1); } #[test] fn test_dedup_diff() { let mut filter = Deduper::new(1_000_000, Duration::from_millis(0)); let mut batches = to_packet_batches(&(0..1024).map(|_| test_tx()).collect::<Vec<_>>(), 128); let discard = filter.dedup_packets_and_count_discards(&mut batches, |_, _, _| ()) as usize; // because dedup uses a threadpool, there maybe up to N threads of txs that go through assert_eq!(discard, 0); filter.reset(); for i in filter.filter { assert_eq!(i.load(Ordering::Relaxed), 0); } } #[test] #[ignore] fn test_dedup_saturated() { let filter = Deduper::new(1_000_000, Duration::from_millis(0)); let mut discard = 0; assert!(!filter.saturated.load(Ordering::Relaxed)); for i in 0..1000 { let mut batches = to_packet_batches(&(0..1000).map(|_| test_tx()).collect::<Vec<_>>(), 128); discard += filter.dedup_packets_and_count_discards(&mut batches, |_, _, _| ()) as usize; trace!("{} {}", i, discard); if filter.saturated.load(Ordering::Relaxed) { break; } } assert!(filter.saturated.load(Ordering::Relaxed)); } #[test] fn test_dedup_false_positive() { let filter = Deduper::new(1_000_000, Duration::from_millis(0)); let mut discard = 0; for i in 0..10 { let mut batches = to_packet_batches(&(0..1024).map(|_| test_tx()).collect::<Vec<_>>(), 128); discard += filter.dedup_packets_and_count_discards(&mut batches, |_, _, _| ()) as usize; debug!("false positive rate: {}/{}", discard, i * 1024); } //allow for 1 false positive even if extremely unlikely assert!(discard < 2); } }
true
e734fd0f04ca15e6768784b724c9c87d9ca0fe53
Rust
coriolinus/counter-rs
/src/impls/add_self.rs
UTF-8
1,589
3.4375
3
[ "MIT" ]
permissive
use crate::Counter; use num_traits::Zero; use std::hash::Hash; use std::ops::{Add, AddAssign}; impl<T, N> Add for Counter<T, N> where T: Clone + Hash + Eq, N: AddAssign + Zero, { type Output = Counter<T, N>; /// Add two counters together. /// /// `out = c + d;` -> `out[x] == c[x] + d[x]` for all `x` /// /// ```rust /// # use counter::Counter; /// # use std::collections::HashMap; /// let c = "aaab".chars().collect::<Counter<_>>(); /// let d = "abb".chars().collect::<Counter<_>>(); /// /// let e = c + d; /// /// let expect = [('a', 4), ('b', 3)].iter().cloned().collect::<HashMap<_, _>>(); /// assert_eq!(e.into_map(), expect); /// ``` fn add(mut self, rhs: Counter<T, N>) -> Self::Output { self += rhs; self } } impl<T, N> AddAssign for Counter<T, N> where T: Hash + Eq, N: Zero + AddAssign, { /// Add another counter to this counter. /// /// `c += d;` -> `c[x] += d[x]` for all `x` /// /// ```rust /// # use counter::Counter; /// # use std::collections::HashMap; /// let mut c = "aaab".chars().collect::<Counter<_>>(); /// let d = "abb".chars().collect::<Counter<_>>(); /// /// c += d; /// /// let expect = [('a', 4), ('b', 3)].iter().cloned().collect::<HashMap<_, _>>(); /// assert_eq!(c.into_map(), expect); /// ``` fn add_assign(&mut self, rhs: Self) { for (key, value) in rhs.map { let entry = self.map.entry(key).or_insert_with(N::zero); *entry += value; } } }
true
eec2cda8599906837960c516fe9c2c7bb79ea204
Rust
fredyw/leetcode
/src/main/rust/src/bin/problem2829.rs
UTF-8
710
3.359375
3
[ "MIT" ]
permissive
use std::collections::HashSet; // https://leetcode.com/problems/determine-the-minimum-sum-of-a-k-avoiding-array/ pub fn minimum_sum(n: i32, k: i32) -> i32 { let mut answer = 0; let mut count = 0; let mut set: HashSet<i32> = HashSet::new(); let mut i = 1; while count < n { if set.contains(&i) { i += 1; continue; } if k - i > 0 { set.insert(k - i); } answer += i; i += 1; count += 1; } answer } fn main() { println!("{}", minimum_sum(5, 4)); // 18 println!("{}", minimum_sum(2, 6)); // 3 println!("{}", minimum_sum(3, 3)); // 8 println!("{}", minimum_sum(10, 6)); // 69 }
true
1ae0125a661d03b30f12e3f83cca016e9692cec6
Rust
readlnh/darwinia
/core/merkle-mountain-range/src/tests/mod.rs
UTF-8
1,756
2.65625
3
[ "Apache-2.0" ]
permissive
pub mod support; use std::time::Instant; use blake2::{Blake2b, Digest}; use test::Bencher; use crate::*; // pub use support::{Digest, *}; type Hasher = Blake2b; // type Hasher = DebugHasher; fn mmr_with_count(count: usize) -> MerkleMountainRange<Hasher> { let mut mmr = MerkleMountainRange::<Hasher>::new(vec![]); for i in 0..count { let hash = usize_to_hash(i); mmr.append(&hash); } mmr } fn usize_to_hash(x: usize) -> Hash { Hasher::digest(&x.to_le_bytes()).to_vec() } #[test] fn t1() { let mmr = mmr_with_count(6); let a = chain_two_hash::<Hasher, _>(&mmr[0], &mmr[1]); let b = chain_two_hash::<Hasher, _>(&a, &mmr[5]); let c = chain_two_hash::<Hasher, _>(&mmr[7], &mmr[8]); let d = chain_two_hash::<Hasher, _>(&b, &c); assert_eq!(mmr.root().unwrap(), d); } #[test] fn t2() { let mmr = mmr_with_count(6); let root = mmr.root().unwrap(); let index = 0; let hash = usize_to_hash(index); let proof = mmr.to_merkle_proof(index).unwrap(); assert!(proof.verify::<Hasher, _>(root, hash, index)); } #[bench] fn b1(b: &mut Bencher) { let mmr = mmr_with_count(10_000_000); let index = 23_333; let mmr_index = leaf_index(index); let root = mmr.root().unwrap(); let hash = usize_to_hash(index); let proof = mmr.to_merkle_proof(mmr_index).unwrap(); b.iter(|| assert!(proof.verify::<Hasher, _>(root.clone(), hash.clone(), mmr_index))); } #[test] fn b2() { let mmr = mmr_with_count(100_000_000); let index = 233_333; let mmr_index = leaf_index(index); let root = mmr.root().unwrap(); let hash = usize_to_hash(index); let start = Instant::now(); let proof = mmr.to_merkle_proof(mmr_index).unwrap(); proof.verify::<Hasher, _>(root, hash, mmr_index); let elapsed = start.elapsed(); println!("{}", elapsed.as_nanos()); }
true
72d77ad20d90ff47522d3dace8891735b0dd1aa8
Rust
danielsvitols/tornado
/tornado/engine_api/src/error.rs
UTF-8
1,371
2.53125
3
[ "MIT", "Apache-2.0" ]
permissive
use actix::MailboxError; use actix_web::HttpResponse; use failure_derive::Fail; use tornado_engine_matcher::error::MatcherError; #[derive(Fail, Debug, PartialEq)] pub enum ApiError { #[fail(display = "MatcherError: [{}]", cause)] MatcherError { cause: MatcherError }, #[fail(display = "ActixMailboxError: [{}]", cause)] ActixMailboxError { cause: String }, #[fail(display = "JsonError: [{}]", cause)] JsonError { cause: String }, } impl From<MatcherError> for ApiError { fn from(err: MatcherError) -> Self { ApiError::MatcherError { cause: err } } } impl From<MailboxError> for ApiError { fn from(err: MailboxError) -> Self { ApiError::ActixMailboxError { cause: format!("{}", err) } } } impl From<serde_json::Error> for ApiError { fn from(err: serde_json::Error) -> Self { ApiError::JsonError { cause: format!("{}", err) } } } // Use default implementation for `error_response()` method. impl actix_web::error::ResponseError for ApiError { fn error_response(&self) -> HttpResponse { match *self { ApiError::MatcherError { .. } => HttpResponse::BadRequest().finish(), ApiError::ActixMailboxError { .. } => HttpResponse::InternalServerError().finish(), ApiError::JsonError { .. } => HttpResponse::InternalServerError().finish(), } } }
true
8a08632fb2699ba1b1b15d66daad43695dcf78db
Rust
boneskull/wld
/src/enums/tbool.rs
UTF-8
1,654
3.3125
3
[ "Apache-2.0" ]
permissive
use scroll::{ ctx::{ SizeWith, TryFromCtx, TryIntoCtx, }, Endian, Error as ScrollError, Pread, Pwrite, LE, }; #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[repr(C)] pub enum TBool { False, True, } impl SizeWith<Endian> for TBool { fn size_with(_: &Endian) -> usize { u8::size_with(&LE) } } impl<'a> TryFromCtx<'a, Endian> for TBool { type Error = ScrollError; fn try_from_ctx( buf: &'a [u8], _: Endian, ) -> Result<(Self, usize), Self::Error> { let offset = &mut 0; let value = buf.gread::<u8>(offset)?; Ok((if value == 0 { Self::False } else { Self::True }, *offset)) } } impl<'a> TryIntoCtx<Endian> for &'a TBool { type Error = ScrollError; fn try_into_ctx( self, buf: &mut [u8], _: Endian, ) -> Result<usize, Self::Error> { let offset = &mut 0; buf.gwrite(if *self == TBool::True { 1_u8 } else { 0_u8 }, offset)?; let expected_size = TBool::size_with(&LE); assert!( expected_size == *offset, "TBool offset mismatch on write; expected {:?}, got {:?}", expected_size, offset ); Ok(*offset) } } #[cfg(test)] mod test_tbool { use super::{ Pread, Pwrite, TBool, }; #[test] fn test_tbool_true_rw() { let t = &TBool::True; let mut bytes = [0; 1]; let _res = bytes.pwrite::<&TBool>(t, 0).unwrap(); assert_eq!(bytes.pread::<TBool>(0).unwrap(), TBool::True); } #[test] fn test_tbool_false_rw() { let t = &TBool::False; let mut bytes = [0; 1]; let _res = bytes.pwrite::<&TBool>(t, 0).unwrap(); assert_eq!(bytes.pread::<TBool>(0).unwrap(), TBool::False); } }
true
76d3d822fec7134038bca6fd3867d59f66402dae
Rust
realotz/material-yew
/website/src/components/switch.rs
UTF-8
1,603
2.6875
3
[ "Apache-2.0" ]
permissive
use crate::components::Codeblock; use crate::with_raw_code; use material_yew::MatSwitch; use yew::prelude::*; pub struct Switch {} impl Component for Switch { type Message = (); type Properties = (); fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self { Self {} } fn update(&mut self, _msg: Self::Message) -> ShouldRender { false } fn change(&mut self, _props: Self::Properties) -> bool { false } fn view(&self) -> Html { let standard = with_raw_code!(standard { html! { <section class="demo"> <h3>{"Switch"}</h3> <MatSwitch /> </section> }}); let checked = with_raw_code!(checked { html! { <section class="demo"> <h3>{"Switch"}</h3> <MatSwitch checked=true /> </section> }}); let disabled = with_raw_code!(disabled { html! { <section class="demo"> <h3>{"Switch"}</h3> <MatSwitch disabled=true /> </section> }}); let disabled_checked = with_raw_code!(disabled_checked { html! { <section class="demo"> <h3>{"Switch"}</h3> <MatSwitch disabled=true checked=true /> </section> }}); html! {<> <Codeblock title="Standard" code_and_html=standard /> <Codeblock title="Checked" code_and_html=checked /> <Codeblock title="Disabled" code_and_html=disabled /> <Codeblock title="Disabled checked" code_and_html=disabled_checked /> </>} } }
true
960646b80de58b873f89fc3239a6125a39c50b67
Rust
guilgaly/advent-of-code-2020
/day_22/src/main.rs
UTF-8
3,688
3.484375
3
[ "Apache-2.0" ]
permissive
use std::collections::{HashSet, VecDeque}; static INPUT_1: &str = include_str!("input_player_1"); static INPUT_2: &str = include_str!("input_player_2"); fn main() -> Result<(), String> { let deck_1 = parse_deck(INPUT_1)?; let deck_2 = parse_deck(INPUT_2)?; println!("Part 1 result: {}", play_combat(deck_1.clone(), deck_2.clone())); println!( "Part 2 result: {}", play_recursive_combat(deck_1.clone(), deck_2.clone()).1 ); Ok(()) } fn play_combat(deck_1: VecDeque<usize>, deck_2: VecDeque<usize>) -> usize { let mut deck_1 = deck_1; let mut deck_2 = deck_2; while !deck_1.is_empty() && !deck_2.is_empty() { let card_1 = deck_1.pop_front().unwrap(); let card_2 = deck_2.pop_front().unwrap(); if card_1 > card_2 { deck_1.push_back(card_1); deck_1.push_back(card_2); } else { deck_2.push_back(card_2); deck_2.push_back(card_1); } } let winning_deck = if deck_1.is_empty() { deck_2 } else { deck_1 }; count_score(&winning_deck) } fn play_recursive_combat(deck_1: VecDeque<usize>, deck_2: VecDeque<usize>) -> (Winner, usize) { let mut deck_1 = deck_1; let mut deck_2 = deck_2; let mut previous_decks: HashSet<(VecDeque<usize>, VecDeque<usize>)> = HashSet::new(); loop { let state = (deck_1.clone(), deck_2.clone()); if previous_decks.contains(&state) { return (Winner::Player1, count_score(&deck_1)); } previous_decks.insert(state); let card_1 = deck_1.pop_front().unwrap(); let card_2 = deck_2.pop_front().unwrap(); let winner = if deck_1.len() >= card_1 && deck_2.len() >= card_2 { play_recursive_combat(copy_top_n_cards(&deck_1, card_1), copy_top_n_cards(&deck_2, card_2)).0 } else { if card_1 > card_2 { Winner::Player1 } else { Winner::Player2 } }; match winner { Winner::Player1 => { deck_1.push_back(card_1); deck_1.push_back(card_2); } Winner::Player2 => { deck_2.push_back(card_2); deck_2.push_back(card_1); } } if deck_1.is_empty() { return (Winner::Player2, count_score(&deck_2)); } else if deck_2.is_empty() { return (Winner::Player1, count_score(&deck_1)); } } } fn count_score(winning_deck: &VecDeque<usize>) -> usize { winning_deck .iter() .rev() .enumerate() .fold(0, |acc, (i, card)| acc + (i + 1) * *card) } fn copy_top_n_cards(deck: &VecDeque<usize>, n: usize) -> VecDeque<usize> { deck.iter().take(n).copied().collect() } /// Top card is at the beginning, bottom card at the end fn parse_deck(input: &str) -> Result<VecDeque<usize>, String> { input .lines() .map(|line| { line.parse::<usize>() .map_err(|e| format!("Cannot parse {}: {}", line, e)) }) .collect() } enum Winner { Player1, Player2, } #[cfg(test)] mod tests { use super::*; fn deck(cards: &[usize]) -> VecDeque<usize> { cards.iter().copied().collect::<VecDeque<_>>() } fn deck_1() -> VecDeque<usize> { deck(&[9, 2, 6, 3, 1]) } fn deck_2() -> VecDeque<usize> { deck(&[5, 8, 4, 7, 10]) } #[test] fn test_combat() { assert_eq!(play_combat(deck_1(), deck_2()), 306); } #[test] fn test_recursive_combat() { assert_eq!(play_recursive_combat(deck_1(), deck_2()).1, 291); } }
true
a2dd8c1cfd618b638166ecac65c0a92bf3c14c84
Rust
moulins/brainfuck-rs
/src/itertools.rs
UTF-8
2,934
3.0625
3
[]
no_license
use std::collections::VecDeque; pub fn stateful<I, St, F, L, B>(iter: I, init_state: St, map: F, last: L) -> impl Iterator<Item=B> where I: Iterator, F: FnMut(St, I::Item) -> (St, B), L: FnOnce(St) -> Option<B> { struct StatefulIter<I, St, F, L> { state: Option<(St, L)>, map: F, iter: I } impl<I, St, F, L, B> Iterator for StatefulIter<I, St, F, L> where I: Iterator, F: FnMut(St, I::Item) -> (St, B), L: FnOnce(St) -> Option<B> { type Item = B; fn next(&mut self) -> Option<Self::Item> { use std::mem::*; match self.iter.next() { Some(item) => { let (state, last) = match self.state.take() { Some(s) => s, None => return None }; let (state, item) = (self.map)(state, item); replace(&mut self.state, Some((state, last))); Some(item) }, None => self.state.take().and_then(|state| (state.1)(state.0)) } } fn size_hint(&self) -> (usize, Option<usize>) { let (min, max) = self.iter.size_hint(); (min, max.and_then(|x| { if x == usize::max_value() { None } else { Some(x+1) } })) } } StatefulIter { iter: iter, state: Some((init_state, last)), map: map } } pub fn combine<I, F>(iter: I, neutral_value: I::Item, mut combinator: F) -> impl Iterator<Item=I::Item> where I: Iterator, F: FnMut(&I::Item, &I::Item) -> Option<I::Item> { stateful(iter, neutral_value, move |last, cur| { match combinator(&last, &cur) { Some(res) => (res, None), None => (cur, Some(last)) } }, move |last| Some(Some(last))).filter_map(|i| i) } pub fn replace_sized_pattern<I, M>(iter: I, pattern_size: usize, matcher: M) -> impl Iterator<Item=I::Item> where I: Iterator, M: FnMut(&VecDeque<I::Item>) -> Option<I::Item> { struct PatternIter<I: Iterator, M> { iter: I, matcher: M, size: usize, list: VecDeque<I::Item>, is_done: bool } impl<I, M> Iterator for PatternIter<I, M> where I: Iterator, M: FnMut(&VecDeque<I::Item>) -> Option<I::Item> { type Item = I::Item; fn next(&mut self) -> Option<Self::Item> { if !self.is_done { for i in &mut self.iter { self.list.push_back(i); if self.list.len() == self.size { return if let Some(res) = (self.matcher)(&self.list) { self.list.drain(..); Some(res) } else { self.list.pop_front() } } } } let r = self.list.pop_front(); if r.is_none() { self.is_done = false } r } } assert!(pattern_size > 0); PatternIter { iter: iter, matcher: matcher, size: pattern_size, list: VecDeque::with_capacity(pattern_size), is_done: false } }
true
18f9c77a77c107da919d491e5a773ccf77b7e983
Rust
Cassin01/PracticeForCompetitiveProgramming
/at_coder/C/abc_116/src/main.rs
UTF-8
2,393
2.828125
3
[]
no_license
#![allow(unused_mut)] #![allow(non_snake_case)] #![allow(unused_imports)] use std::collections::HashSet; use std::collections::HashMap; use std::collections::BTreeSet; use std::collections::VecDeque; use std::cmp::{max, min}; // https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 #[allow(unused_macros)] macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); input_inner!{iter, $($r)*} }; ($($r:tt)*) => { let s = { use std::io::Read; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).unwrap(); s }; let mut iter = s.split_whitespace(); input_inner!{iter, $($r)*} }; } #[allow(unused_macros)] macro_rules! input_inner { ($iter:expr) => {}; ($iter:expr, ) => {}; ($iter:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($iter, $t); input_inner!{$iter $($r)*} }; } #[allow(unused_macros)] macro_rules! read_value { ($iter:expr, ( $($t:tt),* )) => { ( $(read_value!($iter, $t)),* ) }; ($iter:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>() }; ($iter:expr, chars) => { read_value!($iter, String).chars().collect::<Vec<char>>() }; ($iter:expr, usize1) => { read_value!($iter, usize) - 1 }; ($iter:expr, $t:ty) => { $iter.next().unwrap().parse::<$t>().expect("Parse error") }; } fn dfs(mut h: Vec<i64>, r: usize, l: usize, dp: usize) -> i64 { let mut az = true; let mut u = r; let mut vs = Vec::new(); for j in r..l { h[j] -= 1; if h[j] >= 0 { az = false; } else { } if h[j] > 0 { } else { vs.push((u, j)); u = j+1; } } if az { return 0; } vs.push((u, l)); let mut cnt = 0; for v in vs { //println!("{:?} dp{}", v, dp); cnt += dfs(h.clone(), v.0, v.1, dp+1); } cnt + 1 } fn main() { input! { n: usize, xs: [i64; n], } let mut res = 0; for i in 0..n { if i == 0 { res += xs[i]; } else { if xs[i-1] < xs[i] { res += xs[i] - xs[i - 1]; } } } println!("{}", res); }
true
4f7cd4452ed3dd162761974ac61de21fb2ce3a73
Rust
risooonho/dotrix
/dotrix_core/src/assets/resource.rs
UTF-8
552
3.140625
3
[ "MIT", "Apache-2.0" ]
permissive
/* * TODO: Implement resources state control use std::vec::Vec; pub enum State { Busy, Ready, Fail, } */ pub struct Resource { name: String, path: String, // state: State, // data: Option<Vec<u8>>, } impl Resource { pub fn new(name: String, path: String) -> Self { Self { name, path, // state: State::Busy, // data: None, } } pub fn path(&self) -> &String { &self.path } pub fn name(&self) -> &String { &self.name } }
true
3ca3ab6b9b07ea0294f82e82faa8fe2ea009a39b
Rust
huangjj27/leetcode-SAO
/src/problems/problem7.rs
UTF-8
1,328
3.765625
4
[]
no_license
/// 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 /// ## Examples /// ### Example1: /// 输入: 123 /// 输出: 321 /// ```rust /// # use leetcode_SAO::problems::problem7::reverse; /// assert_eq!(reverse(123), 321); /// ``` /// /// ### Example2: /// 输入: -123 /// 输出: -321 /// ```rust /// # use leetcode_SAO::problems::problem7::reverse; /// assert_eq!(reverse(-123), -321); /// ``` /// /// ### Example3: /// 输入: 120 /// 输出: 21 /// ```rust /// # use leetcode_SAO::problems::problem7::reverse; /// assert_eq!(reverse(120), 21); /// ``` pub fn reverse(x: i32) -> i32 { let mut x: i32 = x; let mut result: i32 = 0; if x > 0 { while x > 0 { let i: i32 = x % 10; if result > std::i32::MAX / 10 || (result == std::i32::MAX && i > 7) { return 0; } else { result = result * 10 + i; x = x / 10; } } result } else { while x < 0 { let i: i32 = x % 10; if result < std::i32::MIN / 10 || ((result * -1) == std::i32::MIN && i < -8) { return 0; } else { result = result * 10 + i; x = x / 10; } } result } }
true
480a9dfb1c2f791ad50be2ee9884f4961d80ca5a
Rust
Alin-kkk/icse2020
/collect-results/src/rq05.rs
UTF-8
8,483
2.53125
3
[]
no_license
use results; use results::blocks; use results::functions; use std::io::BufReader; use std::io::BufRead; use std::fs::OpenOptions; use std::io::BufWriter; use std::io::Write; use std::path::PathBuf; struct AnalysisResult { pub name: String, pub crate_unsafe_blocks: usize, pub crate_unsafe_functions: usize, pub total_unsafe_blocks: usize, pub total_unsafe_functions: usize, } pub fn calculate_dependency_size() { // use the FULL_ANALYSIS folder let full_analysis_dir = match std::env::var("FULL_ANALYSIS_DIR") { Ok (val) => {val.to_string()} Err (_) => {"~/unsafe_analysis/analysis-data-2019/full-analysis".to_string()} }; let mut crates_no = 0; let mut dependencies_no =0; for krate_dir_entry_res in std::fs::read_dir(full_analysis_dir).unwrap() { crates_no = crates_no + 1; let krate_dir_entry = krate_dir_entry_res.unwrap(); for dependencies_dir_entry_res in std::fs::read_dir(krate_dir_entry.path()).unwrap() { let dependencies_dir_entry = dependencies_dir_entry_res.unwrap(); if dependencies_dir_entry.file_name() != krate_dir_entry.file_name() { dependencies_no = dependencies_no + 1; } } } println!("dependencies per crate {}", dependencies_no/crates_no); } pub fn calculate_percentage() { // use the FULL_ANALYSIS folder let full_analysis_dir = match std::env::var("FULL_ANALYSIS_DIR") { Ok (val) => {val.to_string()} Err (_) => {"~/unsafe_analysis/analysis-data-2019/full-analysis".to_string()} }; let mut from_dependency_only = 0; let mut both = 0; let mut total = 0; // for each directory in full_analysis dir for krate_dir_entry_res in std::fs::read_dir(full_analysis_dir).unwrap() { let krate_dir_entry = krate_dir_entry_res.unwrap(); let krate = krate_dir_entry.file_name(); let mut current_crate_summary = blocks::BlockSummary::new(0,0,0); let mut dependencies_summary = blocks::BlockSummary::new(0,0,0); let mut current_crate_fn_summary = results::functions::Summary::new(0,0); let mut dependencies_fn_summary = results::functions::Summary::new(0,0); for dependencies_dir_entry_res in std::fs::read_dir(krate_dir_entry.path()).unwrap() { //error!("{:?} depends on {:?}", krate, dependencies_dir_entry.unwrap().file_name()); let dependencies_dir_entry = dependencies_dir_entry_res.unwrap(); let block_summary = sum_for_crate_blocks(dependencies_dir_entry.path()); if dependencies_dir_entry.file_name() == krate_dir_entry.file_name() { current_crate_summary.user_unsafe_blocks = block_summary.user_unsafe_blocks; current_crate_summary.unsafe_blocks = block_summary.unsafe_blocks; current_crate_summary.total = block_summary.total; } else { dependencies_summary.user_unsafe_blocks += block_summary.user_unsafe_blocks; dependencies_summary.unsafe_blocks += block_summary.unsafe_blocks; dependencies_summary.total += block_summary.total; } let fn_summary = sum_for_crate_fn(dependencies_dir_entry.path()); if dependencies_dir_entry.file_name() == krate_dir_entry.file_name() { current_crate_fn_summary.unsafe_no = fn_summary.unsafe_no; current_crate_fn_summary.total = fn_summary.total; } else { dependencies_fn_summary.unsafe_no += fn_summary.unsafe_no; dependencies_fn_summary.total += fn_summary.total; } } if ((current_crate_summary.user_unsafe_blocks!=0 || current_crate_fn_summary.unsafe_no!=0)|| dependencies_summary.user_unsafe_blocks != 0 || dependencies_fn_summary.total!= 0) { if current_crate_summary.user_unsafe_blocks == 0 && current_crate_fn_summary.unsafe_no ==0 && (dependencies_summary.user_unsafe_blocks > 0 || dependencies_fn_summary.unsafe_no >0) { from_dependency_only += 1; } if (current_crate_summary.user_unsafe_blocks > 0 || current_crate_fn_summary.unsafe_no > 0) && (dependencies_summary.user_unsafe_blocks > 0 || dependencies_fn_summary.unsafe_no >0) { both += 1; } total += 1; println!("blocks: {:?}\t{}\t{}\t{}\t{}", krate, current_crate_summary.user_unsafe_blocks, dependencies_summary.user_unsafe_blocks, current_crate_fn_summary.unsafe_no, dependencies_fn_summary.unsafe_no ); } } println!("blocks: from dependency only {} both {} total with some unsafe {}", from_dependency_only, both, total); } pub fn sum_for_crate_blocks( crate_path: PathBuf ) -> blocks::BlockSummary { let mut result = blocks::BlockSummary::new(0,0,0); // for each version for version in std::fs::read_dir(crate_path).unwrap() { //for each file for file_res in std::fs::read_dir(version.unwrap().path()).unwrap() { let file = file_res.unwrap(); let filename_tmp = file.file_name(); // check if it is a block summary file let filename = filename_tmp.to_str().unwrap(); if ( filename.starts_with(results::BLOCK_SUMMARY_BB) ) { let file_tmp = OpenOptions::new() .read(true) .create(false) .open(file.path()) .unwrap(); let mut reader = BufReader::new(file_tmp); //read line by line loop { let mut line = String::new(); let len = reader.read_line(&mut line).expect("Error reading file"); if len == 0 { //EOF reached break; } else { //process line let trimmed_line = line.trim_right(); if trimmed_line.len() > 0 { // ignore empty lines let block_summary: blocks::BlockSummary = serde_json::from_str(&trimmed_line).unwrap(); result.user_unsafe_blocks += block_summary.user_unsafe_blocks; result.unsafe_blocks += block_summary.unsafe_blocks; result.total += block_summary.total; } } } } } } result } pub fn sum_for_crate_fn( crate_path: PathBuf ) -> results::functions::Summary { let mut result = results::functions::Summary::new(0,0); // for each version for version in std::fs::read_dir(crate_path).unwrap() { //for each file for file_res in std::fs::read_dir(version.unwrap().path()).unwrap() { let file = file_res.unwrap(); let filename_tmp = file.file_name(); // check if it is a block summary file let filename = filename_tmp.to_str().unwrap(); if ( filename.starts_with(results::SUMMARY_FUNCTIONS_FILE_NAME) ) { let file_tmp = OpenOptions::new() .read(true) .create(false) .open(file.path()) .unwrap(); let mut reader = BufReader::new(file_tmp); //read line by line loop { let mut line = String::new(); let len = reader.read_line(&mut line).expect("Error reading file"); if len == 0 { //EOF reached break; } else { //process line let trimmed_line = line.trim_right(); if trimmed_line.len() > 0 { // ignore empty lines let summary: results::functions::Summary = serde_json::from_str(&trimmed_line).unwrap(); result.unsafe_no += summary.unsafe_no; result.total += summary.total; } } } } } } result }
true
b49780f6649c449fceb86c2097db7c4f6fb3d622
Rust
Carrigan/advent-of-code-2019
/day-11/src/main.rs
UTF-8
4,312
3.53125
4
[]
no_license
#[derive(Debug)] struct Point { color: Color, x: i64, y: i64 } #[derive(Copy, Clone, PartialEq, Debug)] enum Direction { Up, Down, Left, Right } impl Direction { fn turn(&self, other: Direction) -> Direction { match self { Direction::Up => if other == Direction::Left { Direction::Left } else { Direction::Right }, Direction::Down => if other == Direction::Left { Direction::Right } else { Direction::Left }, Direction::Left => if other == Direction::Left { Direction::Down } else { Direction::Up }, Direction::Right => if other == Direction::Left { Direction::Up } else { Direction::Down } } } } #[derive(Copy, Clone, PartialEq, Debug)] enum Color { White, Black } struct Space { visited: Vec<Point> } impl Space { fn new() -> Self { Space { visited: vec!(Point { x: 0, y: 0, color: Color::White }) } } fn update(&mut self, x: i64, y: i64, color: Color) { for point in &mut self.visited { if point.x == x && point.y == y { point.color = color; return; } } self.visited.push(Point { x, y, color }); } fn has_visited(&self, x: i64, y: i64) -> bool { for point in &self.visited { if point.x == x && point.y == y { return true; } } false } fn color_of(&self, x: i64, y: i64) -> Color { for point in &self.visited { if point.x == x && point.y == y { return point.color; } } Color::Black } } struct Robot { brain: intcode::Program, heading: Direction, x: i64, y: i64, } impl Robot { fn new(code: String) -> Self { Robot { brain: intcode::Program::from(code), x: 0, y: 0, heading: Direction::Up } } fn iterate(&mut self, current_color: Color) -> Option<(Color, Direction)> { // Run the program let input: i64 = if current_color == Color::White { 1 } else { 0 }; self.brain.append_inputs(&mut vec!(input)); let color = match self.brain.run_until_event() { intcode::ProgramResult::Output(c) => if c == 1 { Color::White } else { Color::Black }, intcode::ProgramResult::Complete => return None }; let direction = match self.brain.run_until_event() { intcode::ProgramResult::Output(c) => if c == 1 { Direction::Right } else { Direction::Left }, intcode::ProgramResult::Complete => return None }; // Update our positional state self.heading = self.heading.turn(direction); self.x = match self.heading { Direction::Left => self.x - 1, Direction::Right => self.x + 1, _ => self.x }; self.y = match self.heading { Direction::Up => self.y + 1, Direction::Down => self.y - 1, _ => self.y }; println!("Program output: {:?}, {:?}", color, direction); Some((color, direction)) } } struct RobotProgram<'a> { robot: &'a mut Robot, space: &'a mut Space } impl <'a> Iterator for RobotProgram<'a> { type Item = Point; fn next(&mut self) -> Option<Self::Item> { let current_x = self.robot.x; let current_y = self.robot.y; let current_color = self.space.color_of(current_x, current_y); // This will return the next color if let Some((color, _)) = self.robot.iterate(current_color) { self.space.update(current_x, current_y, color); return Some(Point { x: current_x, y: current_y, color: color }); } None } } fn main() { let code = std::fs::read_to_string("input.txt").unwrap(); let mut robot = Robot::new(code); let mut space = Space::new(); let program = RobotProgram { robot: &mut robot, space: &mut space }; for visitation in program { println!("Visited: {:?} {:?} -> {:?}", visitation.x, visitation.y, visitation.color); } for y in 0..6 { for x in 0..41 { print!("{}", if space.color_of(x, 0 - y) == Color::White { '#' } else { ' ' }); } println!(""); } }
true
7481e5fecf5103e215d637472e81da637b734c70
Rust
vigna/dsi-bitstream-rs
/src/codes/minimal_binary.rs
UTF-8
3,365
3.046875
3
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
/* * SPDX-FileCopyrightText: 2023 Tommaso Fontana * SPDX-FileCopyrightText: 2023 Inria * SPDX-FileCopyrightText: 2023 Sebastiano Vigna * * SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later */ //! # Minimal Binary //! //! Also called [Truncated binary encoding](https://en.wikipedia.org/wiki/Truncated_binary_encoding) //! is optimal for uniform distributions. //! When the size of the alphabet is a power of two, this is equivalent to //! the classical binary encoding. use crate::traits::*; use anyhow::{bail, Result}; /// Returns how long the minimal binary code for `value` will be for a given /// `max` #[must_use] #[inline] pub fn len_minimal_binary(value: u64, max: u64) -> usize { if max == 0 { return 0; } let l = max.ilog2(); let limit = (1 << (l + 1)) - max; let mut result = l as usize; if value >= limit { result += 1; } result } /// Trait for objects that can read Minimal Binary codes pub trait MinimalBinaryRead<BO: Endianness>: BitRead<BO> { /// Read a minimal binary code from the stream. /// /// # Errors /// This function fails only if the BitRead backend has problems reading /// bits, as when the stream ends unexpectedly #[inline(always)] fn read_minimal_binary(&mut self, max: u64) -> Result<u64> { if max == 0 { bail!("The max of a minimal binary value can't be zero."); } let l = max.ilog2(); let mut value = self.read_bits(l as _)?; let limit = (1 << (l + 1)) - max; Ok(if value < limit { value } else { value <<= 1; value |= self.read_bits(1)?; value - limit }) } /// Read a minimal binary code from the stream. /// /// # Errors /// This function fails only if the BitRead backend has problems reading /// bits, as when the stream ends unexpectedly #[inline(always)] fn skip_minimal_binary(&mut self, max: u64) -> Result<()> { if max == 0 { bail!("The max of a minimal binary value can't be zero."); } let l = max.ilog2(); let limit = (1 << (l + 1)) - max; let value = self.read_bits(l as _)?; if value >= limit { self.skip_bits(1)?; } Ok(()) } } /// Trait for objects that can write Minimal Binary codes pub trait MinimalBinaryWrite<BO: Endianness>: BitWrite<BO> { /// Write a value on the stream and return the number of bits written. /// /// # Errors /// This function fails only if the BitRead backend has problems writing /// bits, as when the stream ends unexpectedly #[inline] fn write_minimal_binary(&mut self, value: u64, max: u64) -> Result<usize> { if max == 0 { bail!("The max of a minimal binary value can't be zero."); } let l = max.ilog2(); let limit = (1 << (l + 1)) - max; if value < limit { self.write_bits(value, l as _)?; Ok(l as usize) } else { let to_write = value + limit; self.write_bits(to_write >> 1, l as _)?; self.write_bits(to_write & 1, 1)?; Ok((l + 1) as usize) } } } impl<BO: Endianness, B: BitRead<BO>> MinimalBinaryRead<BO> for B {} impl<BO: Endianness, B: BitWrite<BO>> MinimalBinaryWrite<BO> for B {}
true
632994eff29324f4aa90c038ff7c5964b20108e1
Rust
rustwasm/wasm-bindgen
/crates/test/src/lib.rs
UTF-8
2,102
2.53125
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! Runtime support for the `#[wasm_bindgen_test]` attribute //! //! More documentation can be found in the README for this crate! #![deny(missing_docs)] pub use wasm_bindgen_test_macro::wasm_bindgen_test; // Custom allocator that only returns pointers in the 2GB-4GB range // To ensure we actually support more than 2GB of memory #[cfg(all(test, feature = "gg-alloc"))] #[global_allocator] static A: gg_alloc::GgAlloc<std::alloc::System> = gg_alloc::GgAlloc::new(std::alloc::System); /// Helper macro which acts like `println!` only routes to `console.log` /// instead. #[macro_export] macro_rules! console_log { ($($arg:tt)*) => ( $crate::__rt::log(&format_args!($($arg)*)) ) } /// A macro used to configured how this test is executed by the /// `wasm-bindgen-test-runner` harness. /// /// This macro is invoked as: /// /// ```ignore /// wasm_bindgen_test_configure!(foo bar baz); /// ``` /// /// where all of `foo`, `bar`, and `baz`, would be recognized options to this /// macro. The currently known options to this macro are: /// /// * `run_in_browser` - requires that this test is run in a browser rather than /// node.js, which is the default for executing tests. /// * `run_in_worker` - requires that this test is run in a web worker rather than /// node.js, which is the default for executing tests. /// /// This macro may be invoked at most one time per test suite (an entire binary /// like `tests/foo.rs`, not per module) #[macro_export] macro_rules! wasm_bindgen_test_configure { (run_in_browser $($others:tt)*) => ( #[link_section = "__wasm_bindgen_test_unstable"] #[cfg(target_arch = "wasm32")] pub static __WBG_TEST_RUN_IN_BROWSER: [u8; 1] = [0x01]; $crate::wasm_bindgen_test_configure!($($others)*); ); (run_in_worker $($others:tt)*) => ( #[link_section = "__wasm_bindgen_test_unstable"] #[cfg(target_arch = "wasm32")] pub static __WBG_TEST_RUN_IN_WORKER: [u8; 1] = [0x10]; $crate::wasm_bindgen_test_configure!($($others)*); ); () => () } #[path = "rt/mod.rs"] pub mod __rt;
true
0db2e357fde8e1a147621042c353c8eed9ff534c
Rust
tweedegolf/blue_hal
/src/drivers/stm32f4/flash.rs
UTF-8
15,733
2.859375
3
[ "MIT" ]
permissive
//! Internal Flash controller for the STM32F4 family use crate::{ hal::flash::ReadWrite, stm32pac::FLASH, utilities::{ bitwise::SliceBitSubset, memory::{self, IterableByOverlaps}, }, }; use core::ops::{Add, Sub}; use nb::block; pub struct McuFlash { flash: FLASH, } #[derive(Copy, Clone, Debug)] pub enum Error { MemoryNotReachable, MisalignedAccess, } #[derive(Default, Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq)] pub struct Address(pub u32); impl Add<usize> for Address { type Output = Self; fn add(self, rhs: usize) -> Address { Address(self.0 + rhs as u32) } } impl Sub<usize> for Address { type Output = Self; fn sub(self, rhs: usize) -> Address { Address(self.0.saturating_sub(rhs as u32)) } } impl Sub<Address> for Address { type Output = usize; fn sub(self, rhs: Address) -> usize { self.0.saturating_sub(rhs.0) as usize } } impl Into<usize> for Address { fn into(self) -> usize { self.0 as usize } } #[derive(Copy, Clone, Debug)] struct Range(Address, Address); /// Different address blocks as defined in [Table 5](../../../../../../../documentation/hardware/stm32f412_reference.pdf#page=58) #[derive(Copy, Clone, Debug, PartialEq)] pub enum Block { /// Main memory, but reserved for immutable data (e.g. a bootloader image) Reserved, /// Main memory, where the application is written Main, SystemMemory, OneTimeProgrammable, OptionBytes, } /// A memory map sector, with an associated block and an address range #[derive(Copy, Clone, Debug, PartialEq)] #[non_exhaustive] struct Sector { block: Block, location: Address, size: usize, } #[non_exhaustive] pub struct MemoryMap { sectors: [Sector; SECTOR_NUMBER], } const UNLOCK_KEYS: [u32; 2] = [0x45670123, 0xCDEF89AB]; #[cfg(feature = "stm32f412")] const SECTOR_NUMBER: usize = 15; #[cfg(feature = "stm32f446")] const SECTOR_NUMBER: usize = 11; #[cfg(feature = "stm32f412")] const MEMORY_MAP: MemoryMap = MemoryMap { sectors: [ Sector::new(Block::Reserved, Address(0x0800_0000), KB!(16)), Sector::new(Block::Reserved, Address(0x0800_4000), KB!(16)), Sector::new(Block::Reserved, Address(0x0800_8000), KB!(16)), Sector::new(Block::Reserved, Address(0x0800_C000), KB!(16)), Sector::new(Block::Main, Address(0x0801_0000), KB!(64)), Sector::new(Block::Main, Address(0x0802_0000), KB!(128)), Sector::new(Block::Main, Address(0x0804_0000), KB!(128)), Sector::new(Block::Main, Address(0x0806_0000), KB!(128)), Sector::new(Block::Main, Address(0x0808_0000), KB!(128)), Sector::new(Block::Main, Address(0x080A_0000), KB!(128)), Sector::new(Block::Main, Address(0x080C_0000), KB!(128)), Sector::new(Block::Main, Address(0x080E_0000), KB!(128)), Sector::new(Block::SystemMemory, Address(0x1FFF_0000), KB!(32)), Sector::new(Block::OneTimeProgrammable, Address(0x1FFF_7800), 528), Sector::new(Block::OptionBytes, Address(0x1FFF_C000), 16), ], }; #[cfg(feature = "stm32f446")] const MEMORY_MAP: MemoryMap = MemoryMap { sectors: [ Sector::new(Block::Reserved, Address(0x0800_0000), KB!(16)), Sector::new(Block::Reserved, Address(0x0800_4000), KB!(16)), Sector::new(Block::Reserved, Address(0x0800_8000), KB!(16)), Sector::new(Block::Reserved, Address(0x0800_C000), KB!(16)), Sector::new(Block::Main, Address(0x0801_0000), KB!(64)), Sector::new(Block::Main, Address(0x0802_0000), KB!(128)), Sector::new(Block::Main, Address(0x0804_0000), KB!(128)), Sector::new(Block::Main, Address(0x0806_0000), KB!(128)), Sector::new(Block::SystemMemory, Address(0x1FFF_0000), KB!(30)), Sector::new(Block::OneTimeProgrammable, Address(0x1FFF_7800), 528), Sector::new(Block::OptionBytes, Address(0x1FFF_C000), 16), ], }; const fn max_sector_size() -> usize { let (mut index, mut size) = (0, 0usize); loop { let sector_size = MEMORY_MAP.sectors[index].size; size = if sector_size > size { sector_size } else { size }; index += 1; if index == SECTOR_NUMBER { break size; } } } impl MemoryMap { // Verifies that the memory map is consecutive and well formed fn is_sound(&self) -> bool { let main_sectors = self.sectors.iter().filter(|s| s.is_in_main_memory_area()); let mut consecutive_pairs = main_sectors.clone().zip(main_sectors.skip(1)); let consecutive = consecutive_pairs.all(|(a, b)| a.end() == b.start()); let ranges_valid = self.sectors.iter().map(|s| Range(s.start(), s.end())).all(Range::is_valid); consecutive && ranges_valid } fn sectors() -> impl Iterator<Item = Sector> { MEMORY_MAP.sectors.iter().cloned() } pub const fn writable_start() -> Address { let mut i = 0; loop { if MEMORY_MAP.sectors[i].is_writable() { break MEMORY_MAP.sectors[i].start(); } i += 1; } } pub const fn writable_end() -> Address { let mut i = 0; loop { // Reach the writable area. if MEMORY_MAP.sectors[i].is_writable() { break; } i += 1; } loop { // Reach the end of the writable area if !MEMORY_MAP.sectors[i + 1].is_writable() { break MEMORY_MAP.sectors[i].end(); } i += 1; } } } impl Range { /// Sectors spanned by this range of addresses fn span(self) -> &'static [Sector] { let first = MEMORY_MAP .sectors .iter() .enumerate() .find_map(|(i, sector)| self.overlaps(sector).then_some(i)); let last = MEMORY_MAP .sectors .iter() .enumerate() .rev() .find_map(|(i, sector)| self.overlaps(sector).then_some(i)); match (first, last) { (Some(first), Some(last)) if (last >= first) => &MEMORY_MAP.sectors[first..(last + 1)], _ => &MEMORY_MAP.sectors[0..1], } } const fn is_valid(self) -> bool { let Range(Address(start), Address(end)) = self; let after_map = start >= MEMORY_MAP.sectors[SECTOR_NUMBER - 1].end().0; let before_map = end < MEMORY_MAP.sectors[0].end().0; let monotonic = end >= start; monotonic && !before_map && !after_map } fn overlaps(self, sector: &Sector) -> bool { (self.0 <= sector.start()) && (self.1 > sector.end()) || (self.0 < sector.end()) && (self.1 >= sector.end()) || (self.0 >= sector.start() && self.0 < sector.end()) || (self.1 < sector.end() && self.1 >= sector.start()) } /// Verify that all sectors spanned by this range are writable fn is_writable(self) -> bool { self.span().iter().all(Sector::is_writable) } } impl memory::Region<Address> for Sector { fn contains(&self, address: Address) -> bool { (self.start() <= address) && (self.end() > address) } } impl Sector { const fn start(&self) -> Address { self.location } const fn end(&self) -> Address { Address(self.start().0 + self.size as u32) } const fn new(block: Block, location: Address, size: usize) -> Self { Sector { block, location, size } } fn number(&self) -> Option<u8> { MEMORY_MAP.sectors.iter().enumerate().find_map(|(index, sector)| { (sector.is_in_main_memory_area() && self == sector).then_some(index as u8) }) } const fn is_writable(&self) -> bool { self.block as u8 == Block::Main as u8 } const fn is_in_main_memory_area(&self) -> bool { self.block as u8 == Block::Main as u8 || self.block as u8 == Block::Reserved as u8 } } impl McuFlash { pub fn new(flash: FLASH) -> Result<Self, Error> { assert!(MEMORY_MAP.is_sound()); Ok(Self { flash }) } /// Parallelism for 3v3 voltage from [table 7](../../../../../../../../documentation/hardware/stm32f412_reference.pdf#page=63) /// (Word access parallelism) fn unlock(&mut self) -> nb::Result<(), Error> { if self.is_busy() { return Err(nb::Error::WouldBlock); } // NOTE(Safety): Unsafe block to use the 'bits' convenience function. // Applies to all blocks in this file unless specified otherwise self.flash.keyr.write(|w| unsafe { w.bits(UNLOCK_KEYS[0]) }); self.flash.keyr.write(|w| unsafe { w.bits(UNLOCK_KEYS[1]) }); self.flash.cr.modify(|_, w| unsafe { w.psize().bits(0b10) }); Ok(()) } fn lock(&mut self) { self.flash.cr.modify(|_, w| w.lock().set_bit()); } fn erase(&mut self, sector: &Sector) -> nb::Result<(), Error> { let number = sector.number().ok_or(nb::Error::Other(Error::MemoryNotReachable))?; self.unlock()?; self.flash .cr .modify(|_, w| unsafe { w.ser().set_bit().snb().bits(number).strt().set_bit() }); self.lock(); Ok(()) } fn is_busy(&self) -> bool { self.flash.sr.read().bsy().bit_is_set() } fn write_bytes( &mut self, bytes: &[u8], sector: &Sector, address: Address, ) -> nb::Result<(), Error> { if (address < sector.start()) || (address + bytes.len() > sector.end()) { return Err(nb::Error::Other(Error::MisalignedAccess)); } let words = bytes.chunks(4).map(|bytes| { u32::from_le_bytes([ bytes.get(0).cloned().unwrap_or(0), bytes.get(1).cloned().unwrap_or(0), bytes.get(2).cloned().unwrap_or(0), bytes.get(3).cloned().unwrap_or(0), ]) }); block!(self.unlock())?; self.flash.cr.modify(|_, w| w.pg().set_bit()); let base_address = address.0 as *mut u32; for (index, word) in words.enumerate() { // NOTE(Safety): Writing to a memory-mapped flash // directly is naturally unsafe. We have to trust that // the memory map is correct, and that these dereferences // won't cause a hardfault or overlap with our firmware. unsafe { *(base_address.add(index)) = word; } } self.lock(); Ok(()) } } impl ReadWrite for McuFlash { type Error = Error; type Address = Address; fn range(&self) -> (Address, Address) { (MemoryMap::writable_start(), MemoryMap::writable_end()) } // NOTE: This only erases the sections of the MCU flash that are writable // from the application's perspective. Not the reserved sector, system bytes, etc. fn erase(&mut self) -> nb::Result<(), Self::Error> { for sector in MEMORY_MAP.sectors.iter().filter(|s| s.is_writable()) { self.erase(sector)?; } Ok(()) } fn write(&mut self, address: Address, bytes: &[u8]) -> nb::Result<(), Self::Error> { if address.0 % 4 != 0 { return Err(nb::Error::Other(Error::MisalignedAccess)); } let range = Range(address, Address(address.0 + bytes.len() as u32)); if !range.is_writable() { return Err(nb::Error::Other(Error::MemoryNotReachable)); } // Early yield if busy if self.is_busy() { return Err(nb::Error::WouldBlock); } for (block, sector, address) in MemoryMap::sectors().overlaps(bytes, address) { let sector_data = &mut [0u8; max_sector_size()][0..sector.size]; let offset_into_sector = address.0.saturating_sub(sector.start().0) as usize; block!(self.read(sector.start(), sector_data))?; if block.is_subset_of(&sector_data[offset_into_sector..sector.size]) { // No need to erase the sector, as we can just flip bits off // (since our block is a bitwise subset of the sector) block!(self.write_bytes(block, &sector, address))?; } else { // We have to erase and rewrite any saved data alongside the new block block!(self.erase(&sector))?; sector_data .iter_mut() .skip(offset_into_sector) .zip(block) .for_each(|(byte, input)| *byte = *input); block!(self.write_bytes(sector_data, &sector, sector.location))?; } } Ok(()) } fn read(&mut self, address: Address, bytes: &mut [u8]) -> nb::Result<(), Self::Error> { let range = Range(address, Address(address.0 + bytes.len() as u32)); if !range.is_writable() { Err(nb::Error::Other(Error::MemoryNotReachable)) } else { let base = address.0 as *const u8; for (index, byte) in bytes.iter_mut().enumerate() { // NOTE(Safety) we are reading directly from raw memory locations, // which is inherently unsafe. *byte = unsafe { *(base.add(index)) }; } Ok(()) } } fn write_from_blocks<I: Iterator<Item = [u8; N]>, const N: usize>( &mut self, address: Self::Address, blocks: I, ) -> Result<(), Self::Error> { const TRANSFER_SIZE: usize = KB!(4); assert!(TRANSFER_SIZE % N == 0); let mut transfer_array = [0x00u8; TRANSFER_SIZE]; let mut memory_index = 0usize; for block in blocks { let slice = &mut transfer_array [(memory_index % TRANSFER_SIZE)..((memory_index % TRANSFER_SIZE) + N)]; slice.clone_from_slice(&block); memory_index += N; if memory_index % TRANSFER_SIZE == 0 { nb::block!(self.write(address + (memory_index - TRANSFER_SIZE), &transfer_array))?; transfer_array.iter_mut().for_each(|b| *b = 0x00u8); } } let remainder = &transfer_array[0..(memory_index % TRANSFER_SIZE)]; nb::block!(self.write(address + (memory_index - remainder.len()), &remainder))?; Ok(()) } fn label() -> &'static str { "stm32f4 flash (Internal)" } } #[cfg(test)] mod test { use super::*; #[test] fn ranges_overlap_sectors_correctly() { let sector = Sector::new(Block::Reserved, Address(10), 10usize); assert!(Range(Address(10), Address(20)).overlaps(&sector)); assert!(Range(Address(5), Address(15)).overlaps(&sector)); assert!(Range(Address(15), Address(25)).overlaps(&sector)); assert!(Range(Address(5), Address(25)).overlaps(&sector)); assert!(Range(Address(12), Address(18)).overlaps(&sector)); assert!(!Range(Address(0), Address(5)).overlaps(&sector)); assert!(!Range(Address(20), Address(25)).overlaps(&sector)); } #[test] fn ranges_span_the_correct_sectors() { let range = Range(Address(0x0801_1234), Address(0x0804_5678)); let expected_sectors = &MEMORY_MAP.sectors[4..7]; assert_eq!(expected_sectors, range.span()); } #[test] fn map_shows_correct_writable_range() { let (start, end) = (MemoryMap::writable_start(), MemoryMap::writable_end()); assert_eq!(start, MEMORY_MAP.sectors[4].start()); assert_eq!(end, MEMORY_MAP.sectors[11].end()); } #[test] fn ranges_are_correctly_marked_writable() { let (start, size) = (Address(0x0801_0008), 48usize); let range = Range(start, Address(start.0 + size as u32)); assert!(range.is_writable()); } }
true
177256ebabea833448908261fa2cde932cb1bd0a
Rust
MananSoni42/learning-rust
/enum_match_null/src/main.rs
UTF-8
936
3.75
4
[ "MIT" ]
permissive
use std::option::Option; enum IP { V4(u8,u8,u8,u8), V6(u8,u8,u8,u8,u8,u8), } fn print_ip(ip: &Option<IP>) { match ip { // rust match is exhaustive! None => println!("No IP specified"), &Some(IP::V4(a,b,c,d)) => println!("IPv4: {}.{}.{}.{}",a,b,c,d), &Some(IP::V6(a,b,c,d,e,f)) => println!("IPv6: {}.{}.{}.{}.{}.{}",a,b,c,d,e,f), } } fn main() { let user_ip1: Option<IP> = Some(IP::V6(0,1,2,3,4,5)); let user_ip2: Option<IP> = Some(IP::V4(4,3,2,1)); let user_ip3: Option<IP> = None; print_ip(&user_ip1); print_ip(&user_ip2); print_ip(&user_ip3); // how to print an enum if let Some(IP::V4(a,b,c,d)) = user_ip2 { println!("{}.{}.{}.{}",a,b,c,d); } else { println!("Not in ipv4 format"); } if let Some(IP::V4(a,b,c,d)) = user_ip1 { println!("{}.{}.{}.{}",a,b,c,d); } else { println!("Not in ipv4 format"); } }
true
e66b552648bd03949c00c1c7c1be90f9e2a73d94
Rust
fnuttens/rust_katas
/src/morse_code.rs
UTF-8
1,915
3.25
3
[]
no_license
use std::collections::HashMap; macro_rules! map( { $($key:expr => $value:expr),+ } => { { let mut m = ::std::collections::HashMap::new(); $( m.insert($key.to_owned(), $value.to_owned()); )+ m } }; ); struct MorseDecoder { morse_code: HashMap<String, String>, } impl MorseDecoder { fn new() -> MorseDecoder { MorseDecoder { morse_code: map! { ".-" => "A", "-..." => "B", "-.-." => "C", "-.." => "D", "." => "E", "..-." => "F", "--." => "G", "...." => "H", ".." => "I", ".---" => "J", "-.-" => "K", "--" => "M", "-." => "N", "---" => "O", ".--." => "P", "--.-" => "Q", ".-." => "R", "..." => "S", "-" => "T", "..-" => "U", "...-" => "V", ".--" => "W", "-..-" => "X", "-.--" => "Y", "--.." => "Z", ".----" => "1", "..---" => "2", "...--" => "3", "....-" => "4", "....." => "5", "-...." => "6", "--..." => "7", "---.." => "8", "----." => "9", "-----" => "0" }, } } fn decode_morse(&self, encoded: &str) -> String { encoded .trim() .split(" ") .map(|w| self.decode_word(w)) .collect::<Vec<String>>() .join(" ") } fn decode_word(&self, morse_word: &str) -> String { morse_word .split_ascii_whitespace() .map(|morse_char| self.morse_code.get(morse_char).unwrap().clone()) .collect() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_hey_jude() { let decoder = MorseDecoder::new(); assert_eq!( decoder.decode_morse(".... . -.-- .--- ..- -.. ."), "HEY JUDE" ); } }
true
9fedfbc7d21538cd5e701f9cdeabfdaa8f967c7f
Rust
kardeiz/pallet
/src/search/scored_ids.rs
UTF-8
1,847
2.921875
3
[ "MIT" ]
permissive
/// Datastore `id`, scored according to search performance pub struct ScoredId { pub id: u64, pub score: f32, } /// Like `tantivy`'s `TopDocs` collector, but without any limit /// /// Returns `ScoredId`, a container for the datastore `id` and search score. pub struct ScoredIds { pub size_hint: Option<usize>, pub id_field: tantivy::schema::Field, } // Used by the `ScoredIds` collector. #[doc(hidden)] pub struct ScoredIdsSegmentCollector { id_field_reader: Option<tantivy::fastfield::FastFieldReader<u64>>, buffer: Vec<ScoredId>, } impl tantivy::collector::Collector for ScoredIds { type Fruit = Vec<ScoredId>; type Child = ScoredIdsSegmentCollector; fn for_segment( &self, _segment_local_id: tantivy::SegmentLocalId, segment: &tantivy::SegmentReader, ) -> tantivy::Result<Self::Child> { Ok(ScoredIdsSegmentCollector { buffer: self.size_hint.map(Vec::with_capacity).unwrap_or_else(Vec::new), id_field_reader: segment.fast_fields().u64(self.id_field.clone()).ok(), }) } fn requires_scoring(&self) -> bool { true } fn merge_fruits(&self, segment_fruits: Vec<Self::Fruit>) -> tantivy::Result<Self::Fruit> { let mut out = segment_fruits.into_iter().flatten().collect::<Vec<_>>(); out.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or_else(|| a.id.cmp(&b.id))); Ok(out) } } impl tantivy::collector::SegmentCollector for ScoredIdsSegmentCollector { type Fruit = Vec<ScoredId>; fn collect(&mut self, doc: tantivy::DocId, score: tantivy::Score) { if let Some(ref id_field_reader) = self.id_field_reader { self.buffer.push(ScoredId { score, id: id_field_reader.get(doc) }); } } fn harvest(self) -> Self::Fruit { self.buffer } }
true
2062eba9602d1b884461cd4dd09cfb3096a2cfd3
Rust
kenrick95/adventofcode2017
/src/day23part2.rs
UTF-8
772
2.984375
3
[]
no_license
/** * Thanks to https://www.reddit.com/r/adventofcode/comments/7lms6p/2017_day_23_solutions/ to suggest translating assembly to code. * Especially https://www.reddit.com/r/adventofcode/comments/7lms6p/2017_day_23_solutions/drngj9r/ */ pub fn main() { let a = 1; let mut b = 93; let mut c = b; if a != 0 { b = b * 100 + 100000; c = b + 17000; } let mut f = 1; let mut d = 2; let mut e = 2; let mut g = 0; let mut h = 0; while b <= c { f = 1; d = 2; while d * d <= b { if b % d == 0 { f = 0; break; } d += 1; } if f == 0 { h += 1; } b += 17; } println!("a {}, b {}, c {}, d {}, e {}, f {}, g {}, h {}", a, b, c, d, e, f, g, h); }
true
4d325b453363ecb84d13880c15a8e9e035691b84
Rust
arichnad/slsh
/src/builtins_str.rs
UTF-8
5,373
2.859375
3
[ "MIT" ]
permissive
use std::collections::HashMap; use std::hash::BuildHasher; use std::io; use std::rc::Rc; use crate::builtins_util::*; use crate::environment::*; use crate::shell::*; use crate::types::*; fn builtin_str_trim(environment: &mut Environment, args: &[Expression]) -> io::Result<Expression> { if args.len() != 1 { return Err(io::Error::new( io::ErrorKind::Other, "str-trim takes one form", )); } let arg = eval(environment, &args[0])?.make_string(environment)?; Ok(Expression::Atom(Atom::String(arg.trim().to_string()))) } fn builtin_str_ltrim(environment: &mut Environment, args: &[Expression]) -> io::Result<Expression> { if args.len() != 1 { return Err(io::Error::new( io::ErrorKind::Other, "str-ltrim takes one form", )); } let arg = eval(environment, &args[0])?.make_string(environment)?; Ok(Expression::Atom(Atom::String(arg.trim_start().to_string()))) } fn builtin_str_rtrim(environment: &mut Environment, args: &[Expression]) -> io::Result<Expression> { if args.len() != 1 { return Err(io::Error::new( io::ErrorKind::Other, "str-rtrim takes one form", )); } let arg = eval(environment, &args[0])?.make_string(environment)?; Ok(Expression::Atom(Atom::String(arg.trim_end().to_string()))) } fn builtin_str_replace( environment: &mut Environment, args: &[Expression], ) -> io::Result<Expression> { if args.len() != 3 { return Err(io::Error::new( io::ErrorKind::Other, "str-replace takes three forms", )); } let args = to_args_str(environment, args)?; let new_str = args[0].replace(&args[1], &args[2]); Ok(Expression::Atom(Atom::String(new_str))) } fn builtin_str_split(environment: &mut Environment, args: &[Expression]) -> io::Result<Expression> { if args.len() != 2 { return Err(io::Error::new( io::ErrorKind::Other, "str-split takes two forms", )); } let args = to_args_str(environment, args)?; let mut split_list: Vec<Expression> = Vec::new(); for s in args[1].split(&args[0]) { split_list.push(Expression::Atom(Atom::String(s.to_string()))); } Ok(Expression::List(split_list)) } fn builtin_str_cat_list( environment: &mut Environment, args: &[Expression], ) -> io::Result<Expression> { if args.len() != 2 { return Err(io::Error::new( io::ErrorKind::Other, "str-cat-list takes two forms", )); } let args = to_args(environment, args)?; let join_str = args[0].make_string(environment)?; let mut new_str = String::new(); if let Expression::List(list) = &args[1] { let mut first = true; for s in list { if !first { new_str.push_str(&join_str); } new_str.push_str(&s.make_string(environment)?); first = false; } } else { return Err(io::Error::new( io::ErrorKind::Other, "str-cat-list second form must be a list", )); } Ok(Expression::Atom(Atom::String(new_str))) } fn builtin_str_sub(environment: &mut Environment, args: &[Expression]) -> io::Result<Expression> { if args.len() != 3 { return Err(io::Error::new( io::ErrorKind::Other, "str-sub takes three forms (int, int String)", )); } let start = if let Expression::Atom(Atom::Int(i)) = args[0] { i as usize } else { return Err(io::Error::new( io::ErrorKind::Other, "str-sub first form must be an int", )); }; let len = if let Expression::Atom(Atom::Int(i)) = args[1] { i as usize } else { return Err(io::Error::new( io::ErrorKind::Other, "str-sub second form must be an int", )); }; let arg3 = eval(environment, &args[2])?; if let Expression::Atom(Atom::String(s)) = &arg3 { if (start + len) <= s.len() { Ok(Expression::Atom(Atom::String( s.as_str()[start..(start + len)].to_string(), ))) } else { Err(io::Error::new( io::ErrorKind::Other, "str-sub index out of range", )) } } else { Err(io::Error::new( io::ErrorKind::Other, "str-sub third form must be an String", )) } } pub fn add_str_builtins<S: BuildHasher>(data: &mut HashMap<String, Rc<Expression>, S>) { data.insert( "str-trim".to_string(), Rc::new(Expression::Func(builtin_str_trim)), ); data.insert( "str-ltrim".to_string(), Rc::new(Expression::Func(builtin_str_ltrim)), ); data.insert( "str-rtrim".to_string(), Rc::new(Expression::Func(builtin_str_rtrim)), ); data.insert( "str-replace".to_string(), Rc::new(Expression::Func(builtin_str_replace)), ); data.insert( "str-split".to_string(), Rc::new(Expression::Func(builtin_str_split)), ); data.insert( "str-cat-list".to_string(), Rc::new(Expression::Func(builtin_str_cat_list)), ); data.insert( "str-sub".to_string(), Rc::new(Expression::Func(builtin_str_sub)), ); }
true
20b60271f1bfe098c809ac8ae40e6e0eda3fa92c
Rust
geekskick/rusty_notes
/src/bin/write_item.rs
UTF-8
863
2.765625
3
[]
no_license
extern crate diesel_demo; extern crate clap; use self::diesel_demo::models::NewItem; use self::diesel_demo::{create_item, establish_connection}; use clap::{App, Arg}; fn main(){ let args = App::new("Create a to do list item") .arg(Arg::with_name("title").value_name("title").takes_value(true).required(true).help("The title of the item in the todo list")) .arg(Arg::with_name("detail").short("d").long("detail").value_name("detail").takes_value(true).help("Any required detail about the item in the to do list")).get_matches(); let title = args.value_of("title").unwrap(); let detail = args.value_of("detail").unwrap_or(""); println!("{}, {}", title, detail); let item = NewItem::new(title, detail); println!("{:?}", item); println!("Inserted {} items", create_item(&establish_connection(), item)); }
true
811186b277ce23dfd6c13d0c1ced9250161daf13
Rust
LinAGKar/advent-of-code-2018-rust
/day8a/src/main.rs
UTF-8
624
3.15625
3
[ "MIT" ]
permissive
use std::io; use std::io::Read; fn parse_node<T>(numbers: &mut T) -> Option<u32> where T:Iterator<Item = u32> { let child_count = numbers.next()?; let metadata_count = numbers.next()?; let mut total = 0; for _ in 0..child_count { total += parse_node(numbers)?; } for _ in 0..metadata_count { total += numbers.next()?; } Some(total) } fn main() { let mut input = String::new(); io::stdin().read_to_string(&mut input).unwrap(); let mut numbers = input.split_whitespace().map(|x| x.parse::<u32>().unwrap()); println!("{}", parse_node(&mut numbers).unwrap()); }
true
fee4534d17bd3368d7c0922d5e1cf7b5c88a119c
Rust
tempbottle/event_rust
/test/test_timer.rs
UTF-8
1,701
3.0625
3
[ "MIT" ]
permissive
use event_rust::*; use std::fmt; use std::ptr; static mut s_count : i32 = 0; static mut s_delTimer : u64 = 0; //timer return no success(0) will no be repeat fn time_callback(ev : *mut EventLoop, fd : u64, _ : EventFlags, data : *mut ()) -> i32 { let obj : *mut Point = data as *mut Point; if obj.is_null() { println!("data is null {:?}", data); let count = unsafe { s_count = s_count + 1; s_count }; if count >= 5 { let mut ev = unsafe { &mut *ev }; ev.shutdown(); } } else { let obj : &mut Point = unsafe { &mut *obj }; obj.y = obj.y+1; println!("callback {:?}", obj); } if unsafe { s_delTimer == fd } { return -1; } 0 } #[derive(Default, Debug, Clone)] struct Point { x: i32, y: i32, } impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "(--{}, {}--)", self.x, self.y) } } impl Drop for Point { fn drop(&mut self) { println!("drop point"); } } #[test] pub fn test_timer() { println!("Starting TEST_TIMER"); let mut event_loop : EventLoop = EventLoop::new().unwrap(); let p = Point { x : 10, y : 20 }; event_loop.add_timer(EventEntry::new_timer(100, false, Some(time_callback), Some( &p as *const _ as *mut () ))); unsafe { s_delTimer = event_loop.add_timer(EventEntry::new_timer(150, true, Some(time_callback), Some( &p as *const _ as *mut () ))); } event_loop.add_timer(EventEntry::new_timer(200, true, Some(time_callback), Some( ptr::null_mut() ))); event_loop.run().unwrap(); assert!(p.y == 22); assert!(unsafe { s_count } == 5); }
true
861cca8895309485762b1312e298be272c89e40f
Rust
mileswatson/blockkey
/src/consensus/events/line28.rs
UTF-8
3,308
2.6875
3
[ "MIT" ]
permissive
use crate::{ consensus::{App, Broadcast, Error, Prevote, Step, Tendermint}, crypto::hashing::Hashable, }; impl<A: App<B>, B: Hashable + Clone + Eq> Tendermint<A, B> { /// Recieves a proposal with 2f+1 prevotes and prevotes according to whether the value is valid. pub async fn line28(&mut self) -> Result<bool, Error> { match self.line28_check() { None => Ok(false), Some((v, valid_round)) => { // if valid(v) & (lockedRound <= vr || lockedValue = v) let vote_id = if self.app.validate_block(v) && self .locked .as_ref() .map(|x| x.round <= valid_round || &x.value == v) .unwrap_or(true) { // id(v) Some(v.hash()) } else { // nil None }; // broadcast <prevote, h_p, round_p, _> let prevote = Prevote::new(self.height, self.current.round, vote_id); self.broadcast(Broadcast::Prevote(self.app.sign(prevote))) .await?; // step_p <- prevote self.current.step = Step::prevote(); Ok(true) } } } fn line28_check(&self) -> Option<(&B, u64)> { // while step_p = propose if !self.current.step.is_propose() { return None; } let proposer = self.app.proposer(self.current.round); let messages = self.log.get_current(); messages // upon <proposal, ...> .proposals .iter() // from proposer(h_p, round_p) .filter(|contract| contract.signee.hash() == proposer) .map(|contract| &contract.content) .filter_map(|proposal| { // upon <..., h_p, round_p, v, vr> where (vr >= 0 ^ vr < round_p) proposal.valid_round.and_then(|vr| { if vr < self.current.round && proposal.height == self.height && proposal.round == self.current.round { Some((&proposal.proposal, vr)) } else { None } }) }) // AND 2f+1 <prevote, ...> .find(|(proposal, valid_round)| { let id = proposal.hash(); let total_weight = messages .prevotes .iter() .map(|contract| { ( self.voting_weight(contract.signee.hash()), &contract.content, ) }) // <_, h_p, vr, id(v)> .filter(|(_, prevote)| { prevote.height == self.height && prevote.round == *valid_round && prevote.id == Some(id) }) .map(|(weight, _)| weight) .sum::<u64>(); total_weight > self.two_f() }) } }
true
8b57f3c32dfc6a03ea91fb6c120d349a2ee0e51d
Rust
jvff/dkr
/src/docker/docker_run.rs
UTF-8
1,799
3.046875
3
[]
no_license
use super::docker_command::DockerCommand; use std::{borrow::Cow, io}; pub struct DockerRun<'a> { image: Cow<'a, str>, command: DockerCommand<'a>, } impl<'a> DockerRun<'a> { pub fn new(image: impl Into<Cow<'a, str>>) -> Self { let mut command = DockerCommand::new(); command.append("run"); DockerRun { image: image.into(), command, } } pub fn temporary(&mut self) -> &mut Self { self.command.append("--rm"); self } pub fn interactive(&mut self) -> &mut Self { self.command.append("-it"); self } pub fn volume(&mut self, source: impl AsRef<str>, target: impl AsRef<str>) -> &mut Self { self.command .append("-v") .append(format!("{}:{}", source.as_ref(), target.as_ref())); self } pub fn read_only_volume(&mut self, source: impl AsRef<str>, target: impl AsRef<str>) -> &mut Self { self.command .append("-v") .append(format!("{}:{}:ro", source.as_ref(), target.as_ref())); self } pub fn env(&mut self, variable: impl AsRef<str>, value: impl AsRef<str>) -> &mut Self { self.command .append("-e") .append(format!("{}={}", variable.as_ref(), value.as_ref())); self } pub fn run(self) -> Result<(), io::Error> { let mut command = self.command; command.append(self.image); command.run() } pub fn run_shell_command(self, shell_command: impl AsRef<str>) -> Result<(), io::Error> { let mut command = self.command; command .append(self.image) .append("sh") .append("-c") .append(shell_command.as_ref()); command.run() } }
true
2ef7f012bfe7e57596a47e26ae217b461d0cedcb
Rust
NullOranje/rust_nif
/native/rustprimes/src/lib.rs
UTF-8
1,030
2.890625
3
[]
no_license
use rustler::{Encoder, Env, Error, Term}; mod atoms { rustler::rustler_atoms! { atom ok; atom error; //atom __true__ = "true"; //atom __false__ = "false"; } } rustler::rustler_export_nifs! { "Elixir.RustNif.RustPrimes", [ ("prime_numbers", 1, prime_numbers, rustler::SchedulerFlags::DirtyCpu) ], None } fn is_prime_number(x: i64) -> bool { let end_of_range = x - 1; if x == 1 { false } else { !(2..end_of_range).any(|num| x % num == 0) } } fn prime_numbers<'a>(env: Env<'a>, args: &[Term<'a>]) -> Result<Term<'a>, Error> { let is_list: bool = args[0].is_list(); if !is_list { Ok((atoms::error(), "No list supplied").encode(env)) } else { let numbers: Vec<i64> = args[0].decode()?; let mut vec = Vec::new(); for number in numbers { if is_prime_number(number) { vec.push(number) } } Ok((atoms::ok(), &*vec).encode(env)) } }
true
2e0ca214e05a841485a16ad11ef358ec4493cfe2
Rust
csixteen/LeetCode
/Problems/Algorithms/src/Rust/increasing-order-search-tree/src/lib.rs
UTF-8
4,877
3.515625
4
[ "MIT" ]
permissive
// https://leetcode.com/problems/increasing-order-search-tree/ use std::rc::Rc; use std::cell::RefCell; #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, left: None, right: None } } } type Node = Option<Rc<RefCell<TreeNode>>>; struct Solution; impl Solution { pub fn increasing_bst(root: Node) -> Node { fn tree_to_vec(node: &Node, acc: &mut Vec<i32>) { if let Some(n) = node { let n = n.borrow(); if let Some(_) = &n.left { tree_to_vec(&n.left, acc); } acc.push(n.val); if let Some(_) = &n.right { tree_to_vec(&n.right, acc); } } } fn vec_to_tree(vs: &Vec<i32>, i: usize) -> Node { if i >= vs.len() { None } else { let node = TreeNode { val: vs[i], left: None, right: vec_to_tree(vs, i+1) }; Some(Rc::new(RefCell::new(node))) } } let mut acc = Vec::new(); tree_to_vec(&root, &mut acc); vec_to_tree(&acc, 0) } } #[cfg(test)] mod tests { use super::*; #[test] fn example1() { assert_eq!( Some(Rc::new(RefCell::new(TreeNode { val: 1, left: None, right: Some(Rc::new(RefCell::new(TreeNode { val: 2, left: None, right: Some(Rc::new(RefCell::new(TreeNode { val: 3, left: None, right: Some(Rc::new(RefCell::new(TreeNode { val: 4, left: None, right: Some(Rc::new(RefCell::new(TreeNode { val: 5, left: None, right: Some(Rc::new(RefCell::new(TreeNode { val: 6, left: None, right: Some(Rc::new(RefCell::new(TreeNode { val: 7, left: None, right: Some(Rc::new(RefCell::new(TreeNode { val: 8, left: None, right: Some(Rc::new(RefCell::new(TreeNode::new(9)))), }))), }))), }))), }))), }))), }))), }))), }))), Solution::increasing_bst( Some(Rc::new(RefCell::new(TreeNode { val: 5, left: Some(Rc::new(RefCell::new(TreeNode { val: 3, left: Some(Rc::new(RefCell::new(TreeNode { val: 2, left: Some(Rc::new(RefCell::new(TreeNode::new(1)))), right: None, }))), right: Some(Rc::new(RefCell::new(TreeNode::new(4)))), }))), right: Some(Rc::new(RefCell::new(TreeNode { val: 6, left: None, right: Some(Rc::new(RefCell::new(TreeNode { val: 8, left: Some(Rc::new(RefCell::new(TreeNode::new(7)))), right: Some(Rc::new(RefCell::new(TreeNode::new(9)))), }))), }))), })))) ); } #[test] fn example2() { assert_eq!( Some(Rc::new(RefCell::new(TreeNode { val: 1, left: None, right: Some(Rc::new(RefCell::new(TreeNode { val: 5, left: None, right: Some(Rc::new(RefCell::new(TreeNode::new(7)))) }))) }))), Solution::increasing_bst( Some(Rc::new(RefCell::new(TreeNode { val: 5, left: Some(Rc::new(RefCell::new(TreeNode::new(1)))), right: Some(Rc::new(RefCell::new(TreeNode::new(7)))) }))) ) ); } }
true
bd2c78e0ac532bb92581815231f18de607c06264
Rust
NamikoToriyama/hoge
/rust/variables/src/main.rs
UTF-8
215
3.359375
3
[]
no_license
fn fiv(n : i32) -> i32 { if n == 1 { return 1; } if n == 2 { return 1; } return fiv(n-2) + fiv(n-1); } fn main() { let n: i32 = 10; println!("fiv {} = {}", n, fiv(n)); }
true
46e057195356c8306090b1ed8421c82b91e491ba
Rust
spacemeshos/tytle
/tytle_core/src/vm/dummy_host.rs
UTF-8
3,231
2.953125
3
[ "Apache-2.0" ]
permissive
use crate::ast::statement::{Command, Direction}; use crate::vm::{Host, Pen, Turtle}; use std::cell::RefCell; #[derive(Debug)] pub struct DummyHost { pen: Pen, turtle: Turtle, log: RefCell<Vec<String>>, } impl Host for DummyHost { fn compilation_error(&mut self, _error: &str) {} fn exec_print(&mut self, value: isize) { let msg = format!("{}", value); self.append_log(msg); } fn exec_trap(&mut self, node_id: usize, ip: usize) { let msg = format!("trapping at ({}, {})", node_id, ip); self.append_log(msg); } fn exec_cmd(&mut self, cmd: &Command) { match cmd { Command::XCor => self.xcor(), Command::YCor => self.ycor(), Command::PenUp => self.pen_up(), Command::PenErase => self.pen_erase(), Command::Clean => self.clean(), Command::ClearScreen => self.clear_screen(), Command::ShowTurtle => self.show_turtle(), Command::HideTurtle => self.hide_turtle(), _ => unimplemented!(), }; } fn exec_direct(&mut self, direct: &Direction, count: isize) { self.turtle.exec_direct(direct, count); } } impl DummyHost { pub fn new() -> Self { Self { pen: Pen::new(), turtle: Turtle::new(), log: RefCell::new(Vec::new()), } } pub fn xcor(&self) { let x = self.turtle.xcor(); let line = format!("XCOR = {}", x); self.append_log(line); } pub fn ycor(&self) { let y = self.turtle.ycor(); let line = format!("YCOR = {}", y); self.append_log(line); } pub fn xycors(&self) -> (isize, isize) { let x = self.turtle.xcor(); let y = self.turtle.ycor(); let line = format!("XYCORS = ({}, {})", x, y); self.append_log(line); (x, y) } pub fn pen_up(&mut self) { self.append_log("PENUP".to_string()); self.pen.up() } pub fn pen_down(&mut self) { self.append_log("PENDOWN".to_string()); self.pen.down() } pub fn pen_erase(&mut self) { self.append_log("PENERASE".to_string()); self.pen.erase() } pub fn show_turtle(&mut self) { self.append_log("SHOWTURTLE".to_string()); self.turtle.show(); } pub fn hide_turtle(&mut self) { self.append_log("HIDETURTLE".to_string()); self.turtle.hide(); } pub fn clean(&mut self) { self.append_log("CLEAN".to_string()); } pub fn clear_screen(&mut self) { self.append_log("CLEARSCREEN".to_string()); } pub fn set_pen_color(&mut self, color: (u8, u8, u8)) { self.pen.set_color(color); } pub fn set_bg_color(&mut self) { unimplemented!() } pub fn wait(&mut self) {} pub fn stop(&mut self) { unimplemented!() } pub fn get_turtle(&self) -> &Turtle { &self.turtle } pub fn get_pen(&self) -> &Pen { &self.pen } pub fn get_log(&self) -> Vec<String> { self.log.borrow().clone() } fn append_log(&self, line: String) { self.log.borrow_mut().push(line); } }
true
a0b9a8c0aa9c324d078ae228c2dab51c85dbe743
Rust
BrainiumLLC/cargo-mobile
/src/target.rs
UTF-8
3,519
2.90625
3
[ "MIT", "Apache-2.0" ]
permissive
use crate::util; use once_cell_regex::exports::once_cell::sync::OnceCell; use std::{ collections::BTreeMap, fmt::{self, Debug, Display}, }; pub trait TargetTrait<'a>: Debug + Sized { const DEFAULT_KEY: &'static str; fn all() -> &'a BTreeMap<&'a str, Self>; fn name_list() -> &'static [&'a str] where Self: 'static, { static INSTANCE: OnceCell<Vec<&str>> = OnceCell::new(); INSTANCE.get_or_init(|| Self::all().keys().map(|key| *key).collect::<Vec<_>>()) } fn default_ref() -> &'a Self { Self::all() .get(Self::DEFAULT_KEY) .expect("developer error: no target matched `DEFAULT_KEY`") } fn for_name(name: &str) -> Option<&'a Self> { Self::all().get(name) } fn for_arch(arch: &str) -> Option<&'a Self> { Self::all().values().find(|target| target.arch() == arch) } fn triple(&'a self) -> &'a str; fn arch(&'a self) -> &'a str; fn install(&'a self) -> bossy::Result<bossy::ExitStatus> { util::rustup_add(self.triple()) } fn install_all() -> bossy::Result<()> where Self: 'a, { for target in Self::all().values() { target.install()?; } Ok(()) } } #[derive(Debug)] pub struct TargetInvalid { name: String, possible: Vec<String>, } impl Display for TargetInvalid { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Target {:?} is invalid; the possible targets are {:?}", self.name, self.possible, ) } } pub fn get_targets<'a, Iter, I, T, U>( targets: Iter, // we use `dyn` so the type doesn't need to be known when this is `None` fallback: Option<(&'a dyn Fn(U) -> Option<&'a T>, U)>, ) -> Result<Vec<&'a T>, TargetInvalid> where Iter: ExactSizeIterator<Item = &'a I>, I: AsRef<str> + 'a, T: TargetTrait<'a>, { let targets_empty = targets.len() == 0; Ok(if !targets_empty { targets .map(|name| { T::for_name(name.as_ref()).ok_or_else(|| TargetInvalid { name: name.as_ref().to_owned(), possible: T::all().keys().map(|key| key.to_string()).collect(), }) }) .collect::<Result<_, _>>()? } else { let target = fallback .and_then(|(get_target, arg)| get_target(arg)) .unwrap_or_else(|| { log::info!("falling back on default target ({})", T::DEFAULT_KEY); T::default_ref() }); vec![target] }) } pub fn call_for_targets_with_fallback<'a, Iter, I, T, U, E, F>( targets: Iter, fallback: &'a dyn Fn(U) -> Option<&'a T>, arg: U, f: F, ) -> Result<Result<(), E>, TargetInvalid> where Iter: ExactSizeIterator<Item = &'a I>, I: AsRef<str> + 'a, T: TargetTrait<'a>, F: Fn(&T) -> Result<(), E>, { get_targets(targets, Some((fallback, arg))).map(|targets| { for target in targets { f(target)?; } Ok(()) }) } pub fn call_for_targets<'a, Iter, I, T, E, F>( targets: Iter, f: F, ) -> Result<Result<(), E>, TargetInvalid> where Iter: ExactSizeIterator<Item = &'a I>, I: AsRef<str> + 'a, T: TargetTrait<'a> + 'a, F: Fn(&T) -> Result<(), E>, { get_targets::<_, _, _, ()>(targets, None).map(|targets| { for target in targets { f(target)?; } Ok(()) }) }
true
cb4512fc8eeb831f5fe15d4c959d04b4257e5846
Rust
mesalock-linux/crates-io
/vendor/structopt/examples/at_least_two.rs
UTF-8
308
2.890625
3
[ "Apache-2.0", "Unlicense", "BSD-3-Clause", "0BSD", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//! How to require presence of at least N values, //! like `val1 val2 ... valN ... valM`. use structopt::StructOpt; #[derive(StructOpt, Debug)] struct Opt { #[structopt(required = true, min_values = 2)] foos: Vec<String>, } fn main() { let opt = Opt::from_args(); println!("{:?}", opt); }
true
d1f5ce46845526da543b37a30e442d200ea24f35
Rust
cdespatie/advent-of-code
/2017/day-14/src/main.rs
UTF-8
4,351
2.8125
3
[]
no_license
extern crate petgraph; use petgraph::Graph; use petgraph::graph::NodeIndex; use petgraph::visit::Dfs; use std::collections::HashSet; fn main() { let input = "jxqlasbh"; solve(input); } fn solve(input: &str) { let base = input.to_string(); let mut counter = 0; let mut map: Vec<Vec<u32>> = Vec::new(); let mut graph = Graph::<(usize, usize), usize>::new(); let mut graph_nodes: Vec<Vec<Option<NodeIndex>>> = Vec::new(); let mut visited: HashSet<petgraph::prelude::NodeIndex> = HashSet::new(); for j in 0..128 { let string: String = format!("{}-{}", base, j.to_string()); let hash = knot_hash(string, 64); graph_nodes.push(Vec::new()); let bits = to_bits(hash); map.push(bits.chars().flat_map(|x| x.to_digit(10)).collect()); // Part 1 for c in bits.chars() { match c { '1' => counter += 1, _ => () }; } // Part 2 for (i, c) in bits.chars().enumerate() { if c == '1' { let node = graph.add_node((i, j)); graph_nodes[j].push(Some(node)); } else { graph_nodes[j].push(None); } } } for (j, row) in map.iter().enumerate() { for (i, entry) in row.iter().enumerate() { if *entry == 1 { if i > 0 && map[j][i - 1] == 1 { graph.add_edge(graph_nodes[j][i].unwrap(), graph_nodes[j][i - 1].unwrap(), 0); } if i < 127 && map[j][i + 1] == 1 { graph.add_edge(graph_nodes[j][i].unwrap(), graph_nodes[j][i + 1].unwrap(), 0); } if j > 0 && map[j - 1][i] == 1 { graph.add_edge(graph_nodes[j][i].unwrap(), graph_nodes[j - 1][i].unwrap(), 0); } if j < 127 && map[j + 1][i] == 1 { graph.add_edge(graph_nodes[j][i].unwrap(), graph_nodes[j + 1][i].unwrap(), 0); } } } } let mut components = 0; for row in graph_nodes.iter() { for node in row.iter() { match *node { Some(n) => { if !visited.contains(&n) { components += 1; let mut visitor = Dfs::new(&graph, n); while let Some(x) = visitor.next(&graph) { visited.insert(x); } } }, _ => () }; } } println!("{}", counter); println!("{}", components); } fn to_bits(input: String) -> String { let mut output = String::new(); for c in input.chars() { output += &format!("{:04b}", u32::from_str_radix(&c.to_string(), 16).unwrap()); } output } // Day 10 code fn knot_hash(input: String, reps: usize) -> String { let mut start: usize = 0; let mut skip: usize = 0; let mut vector: Vec<usize> = Vec::new(); let mut dense = Vec::new(); let mut const_chars: Vec<usize> = vec![17, 31, 73, 47, 23]; let mut parsed = Vec::new(); for i in input.chars() { parsed.push(i as usize); } parsed.append(&mut const_chars); let ascii_chars: String = parsed.iter().map(|x| x.to_string()) .collect::<Vec<String>>().join(","); for i in 0..256 { vector.push(i); } for _ in 0..reps { for n in ascii_chars.split(",") { let split = get_split(&vector, start, n.parse::<usize>().unwrap()); for (i, &x) in split.iter().rev().enumerate() { vector[(start + i) % 256] = x; } start = (start + split.len() + skip) % 256; skip += 1; } } for i in 0..16 { let mut temp = 0; for j in 0..16 { temp = temp ^ vector[(i * 16) + j]; } dense.push(temp); } convert_hex(dense) } fn convert_hex(input: Vec<usize>) -> String { input.iter().map(|x| format!("{:02x}", x)).collect::<Vec<_>>().join("") } fn get_split(input: &Vec<usize>, start: usize, len: usize) -> Vec<usize> { let mut out = Vec::new(); for i in 0..len { out.push(input[(start + i) % input.len()].clone()); } out }
true
276e18ded765fd981ae98f69a189eaf9f4d4653e
Rust
Ruin0x11/sabi
/src/renderer/ui/layers/input.rs
UTF-8
3,609
3.046875
3
[]
no_license
use glium::glutin::{VirtualKeyCode, ElementState}; use renderer::ui::*; use renderer::ui::elements::*; pub struct InputLayer { win: UiWindow, prompt: UiText, text: UiText, } impl InputLayer { pub fn new(prompt: &str) -> Self { InputLayer { win: UiWindow::new((100, 100)), prompt: UiText::new((120, 120), prompt), text: UiText::new((120, 140), &""), } } } impl UiElement for InputLayer { fn draw(&self, renderer: &mut UiRenderer) { self.win.draw(renderer); self.prompt.draw(renderer); self.text.draw(renderer); } } impl UiLayer for InputLayer { fn on_event(&mut self, event: glutin::Event) -> EventResult { match event { glutin::Event::KeyboardInput(ElementState::Pressed, _, Some(code)) => { match code { VirtualKeyCode::Escape => EventResult::Canceled, VirtualKeyCode::Return => EventResult::Done, VirtualKeyCode::Back => { let mut t = self.text.text(); if !t.is_empty() { t.pop(); } self.text.set(&t); EventResult::Consumed(None) }, keycode => match keycode_to_char(keycode) { Some(ch) => { let mut t = self.text.text(); t.push(ch); self.text.set(&t); EventResult::Consumed(None) }, None => EventResult::Ignored, } } }, _ => EventResult::Ignored, } } } impl UiQuery for InputLayer { type QueryResult = String; fn result(&self) -> Option<String> { Some(self.text.text()) } } fn keycode_to_char(keycode: VirtualKeyCode) -> Option<char> { match keycode { VirtualKeyCode::A => Some('a'), VirtualKeyCode::B => Some('b'), VirtualKeyCode::C => Some('c'), VirtualKeyCode::D => Some('d'), VirtualKeyCode::E => Some('e'), VirtualKeyCode::F => Some('f'), VirtualKeyCode::G => Some('g'), VirtualKeyCode::H => Some('h'), VirtualKeyCode::I => Some('i'), VirtualKeyCode::J => Some('j'), VirtualKeyCode::K => Some('k'), VirtualKeyCode::L => Some('l'), VirtualKeyCode::M => Some('m'), VirtualKeyCode::N => Some('n'), VirtualKeyCode::O => Some('o'), VirtualKeyCode::P => Some('p'), VirtualKeyCode::Q => Some('q'), VirtualKeyCode::R => Some('r'), VirtualKeyCode::S => Some('s'), VirtualKeyCode::T => Some('t'), VirtualKeyCode::U => Some('u'), VirtualKeyCode::V => Some('v'), VirtualKeyCode::W => Some('w'), VirtualKeyCode::X => Some('x'), VirtualKeyCode::Y => Some('y'), VirtualKeyCode::Z => Some('z'), VirtualKeyCode::Key0 => Some('0'), VirtualKeyCode::Key1 => Some('1'), VirtualKeyCode::Key2 => Some('2'), VirtualKeyCode::Key3 => Some('3'), VirtualKeyCode::Key4 => Some('4'), VirtualKeyCode::Key5 => Some('5'), VirtualKeyCode::Key6 => Some('6'), VirtualKeyCode::Key7 => Some('7'), VirtualKeyCode::Key8 => Some('8'), VirtualKeyCode::Key9 => Some('9'), _ => None, } }
true
a927b1c0741d8197f7d9688273bc9bc6461ce32f
Rust
oxalica/depend
/src/evaluator.rs
UTF-8
693
2.921875
3
[ "MIT" ]
permissive
use std::cell::Cell; use super::resolver::Require; pub trait Evaluator<'t>: 't { type Value: 't; fn eval(&self, r: &mut Require<'t>) -> Self::Value; } impl<'t, T: 't, F: Fn(&mut Require<'t>) -> T + 't> Evaluator<'t> for F { type Value = T; fn eval(&self, r: &mut Require<'t>) -> Self::Value { self(r) } } pub struct Value<T> { value: Cell<Option<T>>, } impl<T> Value<T> { pub fn new(value: T) -> Self { Value { value: Cell::new(Some(value)) } } } impl<'t, T: 't> Evaluator<'t> for Value<T> { type Value = T; fn eval(&self, _r: &mut Require<'t>) -> Self::Value { self.value.replace(None).unwrap() // Only run once } }
true
fe9c10f8539c39aa98c26cf45745caea1e44b868
Rust
JosefBertolini/RustTicTacToe
/src/input.rs
UTF-8
870
3.1875
3
[]
no_license
use crate::text_io; pub fn read_move() -> (i32, i32) { let mut row: char; let mut col: i32; let mut converted_row: i32; loop { text_io::scan!("{},{}\r\n", row, col); if row == 'A' || row == 'B' || row == 'C' { converted_row = match row { 'A' => 0, 'B' => 1, 'C' => 2, _ => 3, }; } else { ask_again(1); continue; } if col < 0 || col > 3 { ask_again(0); continue; } else { break; } } let converted_col = col - 1; (converted_row, converted_col) } fn ask_again(which: i32) { if which == 1 { println!("Invaild row, must be the character A, B, or C"); } else { println!("Invaild column, must be 1, 2, or 3"); } }
true
e98c8b4a7451c64fb83211f7e58c72c9c1641904
Rust
caibirdme/leetcode_rust
/src/prob_38.rs
UTF-8
1,419
3.703125
4
[ "MIT" ]
permissive
impl Solution { pub fn count_and_say(n: i32) -> String { let preset = vec!["1", "11", "21", "1211", "111221"]; if n <= 5 { return preset[n as usize-1].to_string(); } let mut pre = "111221".to_string(); for i in 6..=n { pre = Self::count(pre.as_bytes()); } pre } fn count(s: &[u8]) -> String { let mut res = String::new(); let n = s.len(); let mut i = 0; while i < n { let c = s[i]; if i == n-1 { res.push_str(format!("1{}",c as char).as_str()); return res; } let mut t = 1; let mut j = i+1; while j < n && s[j] == s[i]{ t+=1; j+=1; } res.push_str(format!("{}{}", t, c as char).as_str()); i = j; } res } } struct Solution; #[cfg(test)] mod tests { use super::Solution; #[test] fn test_count_and_say() { let test_cases = vec![ (6, "312211"), (7, "13112221"), (8, "1113213211"), (9, "31131211131221"), (10, "13211311123113112211"), (11, "11131221133112132113212221"), ]; for (n, expecpt) in test_cases { assert_eq!(Solution::count_and_say(n), expecpt, "n: {}", n); } } }
true
882c0658e31c551cb04b21e49a734a8707c48056
Rust
esplo/ackprinter-book-supplements
/src/bin/print_ary_no_prettier.rs
UTF-8
1,985
3.09375
3
[]
no_license
use std::collections::HashMap; use std::env; fn ary_prefixer(ary: &Vec<Vec<u32>>, v: u32) -> Vec<Vec<u32>> { ary.iter() .map(|e| [&[v], &e[..]].concat()) .collect() } fn ackermann(m: u32, n: u32) { fn work(m: u32, n: u32, memo: &mut HashMap<(u32, u32), Vec<Vec<u32>>>) -> Vec<Vec<u32>> { if let Some(memov) = memo.get(&(m, n)) { (*memov).clone() } else { let mut result = vec![vec![m, n]]; if m == 0 { result.push(vec![n + 1]); } else if n == 0 { let ary = work(m - 1, 1, memo); result.extend(ary); } else { let ary1 = work(m, n - 1, memo); let pref_ary1 = ary_prefixer(&ary1, m - 1); // 最後の行 [m-1, v] は次の計算用 result.extend_from_slice(&pref_ary1[0..pref_ary1.len() - 1]); let ary2 = work(m - 1, ary1[ary1.len() - 1][0], memo); result.extend(ary2); } memo.insert((m, n), result.clone()); result } } let mut memo = HashMap::new(); let ary = work(m, n, &mut memo); for e in ary.iter() { println!("{}", e.iter().map(|e| format!("{}", e)).collect::<Vec<String>>().join(",")) } } fn inputs(args: &Vec<String>) -> Result<(u32, u32), String> { fn read_int(s: &str) -> Result<u32, String> { s.parse::<u32>().map_err(|err| err.to_string()) } if args.len() != 3 { Err(format!("invalid number of arguments: {}", args.len())) } else { let u: Vec<u32> = args.iter().skip(1).flat_map(|s| read_int(s)).collect(); if u.len() != 2 { Err(format!("invalid digit found in string")) } else { Ok((u[0], u[1])) } } } fn main() { match inputs(&env::args().map(|s| s).collect()) { Ok((m, n)) => ackermann(m, n), Err(e) => { eprintln!("{}", e); } } }
true
7e4c4391aaa7afb10b9615d01d723003704e7c84
Rust
hikilaka/rust_opengl
/src/rsgl/texture.rs
UTF-8
2,519
2.734375
3
[]
no_license
use crate::rsgl::{Bindable, Deletable}; use gl; use gl::types::GLuint; use image; use image::GenericImageView; use std::ops::Drop; pub struct Texture { handle: GLuint, } impl Bindable for Texture { fn bind(&self) { unsafe { gl::BindTexture(gl::TEXTURE_2D, self.handle); } } fn unbind(&self) { unsafe { gl::BindTexture(gl::TEXTURE_2D, 0); } } } impl Deletable for Texture { fn delete(&mut self) { self.unbind(); if self.handle != 0 { unsafe { gl::DeleteTextures(1, &mut self.handle); } self.handle = 0; } } } impl Drop for Texture { fn drop(&mut self) { self.delete(); } } impl Texture { pub fn new(path: &str) -> Texture { let img = match image::open(path) { Ok(img) => img, Err(e) => panic!("Error loading texture '{}': {}", path, e), }; let data = img.raw_pixels(); let format = match img { image::ImageLuma8(_) => gl::RED, image::ImageLumaA8(_) => gl::RG, image::ImageRgb8(_) => gl::RGB, image::ImageRgba8(_) => gl::RGBA, image::ImageBgr8(_) => gl::BGR, image::ImageBgra8(_) => gl::BGRA, }; let mut handle: GLuint = 0; unsafe { gl::GenTextures(1, &mut handle); gl::BindTexture(gl::TEXTURE_2D, handle); gl::TexImage2D( gl::TEXTURE_2D, 0, format as i32, img.width() as i32, img.height() as i32, 0, format, gl::UNSIGNED_BYTE, &data[0] as *const u8 as *const std::os::raw::c_void, ); gl::GenerateMipmap(gl::TEXTURE_2D); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::REPEAT as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::REPEAT as i32); gl::TexParameteri( gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST_MIPMAP_LINEAR as i32, ); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as i32); gl::BindTexture(gl::TEXTURE_2D, 0); } Texture { handle } } pub fn activate_as(&self, index: u32) { unsafe { gl::ActiveTexture(gl::TEXTURE0 + index); } } }
true
3e0700a451930b82db639b79dd9f0e9cac995aaf
Rust
BuoyantIO/byte-channel-rs
/src/sync/sender.rs
UTF-8
3,767
3.125
3
[]
no_license
use bytes::Bytes; use super::{ChannelBuffer, SharedBuffer, SharedWindow, return_buffer_to_window}; use super::super::LostReceiver; pub fn new<E>(buffer: SharedBuffer<E>, window: SharedWindow) -> ByteSender<E> { ByteSender { buffer, window } } #[derive(Debug)] pub struct ByteSender<E> { buffer: SharedBuffer<E>, window: SharedWindow, } impl<E> ByteSender<E> { pub fn available_window(&self) -> usize { (*self.window.lock().expect("locking byte channel window")).advertised() } pub fn is_empty(&self) -> bool { (*self.buffer.lock().expect("locking byte channel buffer")) .as_ref() .map(|s| s.is_empty()) .unwrap_or(true) } pub fn len(&self) -> usize { (*self.buffer.lock().expect("locking byte channel buffer")) .as_ref() .map(|s| s.len()) .unwrap_or(0) } /// Causes the next receiver operation to fail with the provided error. pub fn reset(self, e: E) { let mut buffer = self.buffer.lock().expect("locking byte channel buffer"); return_buffer_to_window(&buffer, &self.window); *buffer = Some(ChannelBuffer::SenderFailed(e)); } /// Signals that no further data will be provided. The `ByteReceiver` may continue to /// read from this channel until it is empty. pub fn close(mut self) { self.do_close(); } fn do_close(&mut self) { let mut buffer = self.buffer.lock().expect("locking byte channel buffer"); if let Some(state) = (*buffer).take() { match state { ChannelBuffer::Sending { len, buffers, mut awaiting_chunk, .. } => { *buffer = Some(ChannelBuffer::SenderClosed { len, buffers }); // If the receiver is waiting for data, notify it so that the channel is // fully closed. if let Some(t) = awaiting_chunk.take() { t.notify(); } } state => { *buffer = Some(state); } } } } /// Pushes bytes into the channel. /// /// ## Panics /// /// Panics if `bytes` exceeds the advertised capacity of this channel. /// /// Panics if pub fn push_bytes(&mut self, bytes: Bytes) -> Result<(), LostReceiver> { let mut buffer = self.buffer.lock().expect("locking byte channel buffer"); if let Some(ChannelBuffer::LostReceiver) = *buffer { // If there's no receiver, drop the entire buffer and error. // The receiver has already returned the buffer to the window. *buffer = None; return Err(LostReceiver); } if let Some(ChannelBuffer::Sending { ref mut len, ref mut awaiting_chunk, ref mut buffers, .. }) = *buffer { let sz = bytes.len(); let mut window = self.window.lock().expect("locking byte channel window"); if sz <= (*window).advertised() { *len += sz; (*window).claim_advertised(sz); buffers.push_back(bytes); if let Some(t) = awaiting_chunk.take() { t.notify(); } return Ok(()); } panic!("byte channel overflow"); } panic!("ByteSender::push called in illegal buffer state"); } } impl<E> Drop for ByteSender<E> { fn drop(&mut self) { self.do_close(); } }
true
0b9acecbcba9310a87b0431f0bb3c3440f733085
Rust
rust-rosetta/rust-rosetta
/tasks/even-or-odd/src/main.rs
UTF-8
276
3.140625
3
[ "Unlicense" ]
permissive
#![allow(unused_variables)] fn main() { // Checking the last significant digit: let is_odd = |x: i32| x & 1 == 1; let is_even = |x: i32| x & 1 == 0; // Using modular congruences: let is_odd = |x: i32| x % 2 != 0; let is_even = |x: i32| x % 2 == 0; }
true
c2d70493a58b317ee1afc7ed94f344dfd041af79
Rust
brooks-builds/get_the_streamer_game
/src/splash.rs
UTF-8
1,072
2.890625
3
[ "CC0-1.0", "MIT" ]
permissive
use std::time::{Duration, Instant}; use ggez::{ graphics::{self, DrawParam, Font, Scale, Text}, nalgebra::Point2, Context, GameResult, }; pub struct Splash { text: Text, location: Point2<f32>, finished_at: Instant, } impl Splash { pub fn new(arena_size: (f32, f32), context: &mut Context, duration: Duration) -> Self { let mut text = Text::new("Starting Soon"); text.set_font(Font::default(), Scale::uniform(100.0)); let text_size = text.dimensions(context); let location = Point2::new( arena_size.0 / 2.0 - text_size.0 as f32 / 2.0, arena_size.1 / 2.0 - text_size.1 as f32 / 2.0, ); let finished_at = Instant::now() + duration; Self { text, location, finished_at, } } pub fn draw(&self, context: &mut Context) -> GameResult<()> { graphics::draw(context, &self.text, DrawParam::new().dest(self.location)) } pub fn is_done(&self) -> bool { Instant::now() >= self.finished_at } }
true
5f30f7afcb1f9c999c51b6150265fed7e598e5a9
Rust
guo-wn/intspan
/src/cmd_spanr/some.rs
UTF-8
1,803
2.984375
3
[ "MIT" ]
permissive
use clap::*; use intspan::*; use serde_yaml::Value; use std::collections::{BTreeMap, BTreeSet}; // Create clap subcommand arguments pub fn make_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("some") .about("Extract some records from a runlist yaml file") .arg( Arg::with_name("infile") .help("Sets the input file to use") .required(true) .index(1), ) .arg( Arg::with_name("list") .help("Sets the input file to use") .required(true) .index(2), ) .arg( Arg::with_name("outfile") .short("o") .long("outfile") .takes_value(true) .default_value("stdout") .empty_values(false) .help("Output filename. [stdout] for screen"), ) } // command implementation pub fn execute(args: &ArgMatches) -> std::result::Result<(), std::io::Error> { //---------------------------- // Loading //---------------------------- let yaml: BTreeMap<String, Value> = read_yaml(args.value_of("infile").unwrap()); let mut names: BTreeSet<String> = BTreeSet::new(); for line in read_lines(args.value_of("list").unwrap()) { names.insert(line); } //---------------------------- // Operating //---------------------------- let mut out_yaml: BTreeMap<String, Value> = BTreeMap::new(); for (key, value) in &yaml { if names.contains(key) { out_yaml.insert(key.into(), value.clone()); } } //---------------------------- // Output //---------------------------- write_yaml(args.value_of("outfile").unwrap(), &out_yaml)?; Ok(()) }
true
c6bd9d146fbf6b48dec01811957edb0ed6b02fc3
Rust
sportzer/scavenger2
/src/lib.rs
UTF-8
7,400
2.703125
3
[ "Apache-2.0" ]
permissive
use std::cell::{Cell, RefCell}; use std::rc::Rc; pub use cursive; use cursive::{ Cursive, Printer, direction::Orientation, event::{Event, EventResult, Key}, theme::{BaseColor, Color, ColorStyle}, vec::Vec2, view::View, views::{BoxView, LinearLayout}, }; mod game; use game::{ Action, ActorType, EntityType, Game, Obstruction, Tile, TileView, geometry::{Direction, Position}, }; #[derive(Copy, Clone)] struct Camera { screen_size: Vec2, screen_focus: Vec2, map_focus: Position, } impl Camera { fn centered(size: Vec2, pos: Position) -> Camera { Camera { screen_size: size, screen_focus: Vec2::new(size.x/2, size.y/2), map_focus: pos, } } fn map_position(&self, offset: Vec2) -> Position { Position { x: self.map_focus.x - self.screen_focus.x as i32 + offset.x as i32, y: self.map_focus.y - self.screen_focus.y as i32 + offset.y as i32, } } } struct GameMap { game: Rc<RefCell<Game>>, camera: Cell<Option<Camera>>, } impl GameMap { fn render_tile(view: TileView) -> (&'static str, ColorStyle) { // TODO: what if actor/object is embedded in a solid wall? let black_bg = |color| ColorStyle::new(color, Color::Dark(BaseColor::Black)); if let TileView::Visible { actor: Some(actor), .. } = view { return match actor { ActorType::Player => ("@", black_bg(Color::Light(BaseColor::White))), ActorType::Rat => ("r", black_bg(Color::Light(BaseColor::White))), ActorType::Wolf => ("w", black_bg(Color::Light(BaseColor::White))), ActorType::Crab => ("c", black_bg(Color::Light(BaseColor::Red))), ActorType::Beetle => ("b", black_bg(Color::Light(BaseColor::Cyan))), ActorType::BigJelly => ("J", black_bg(Color::Light(BaseColor::Magenta))), ActorType::LittleJelly => ("j", black_bg(Color::Light(BaseColor::Magenta))), ActorType::Ghost => ("g", black_bg(Color::Dark(BaseColor::White))), ActorType::Dragonfly => ("d", black_bg(Color::Light(BaseColor::Cyan))), }; } let (object, tile, vis) = match view { TileView::Visible { object, tile, .. } => (object, tile, true), TileView::Remembered { object, tile, .. } => (object, tile, false), TileView::Explorable => { return ("?", black_bg(Color::Dark(BaseColor::Magenta))); } TileView::Unknown => { return (" ", black_bg(Color::Dark(BaseColor::Black))); } }; if let Some(object) = object { let corpse = |c| black_bg(if vis { Color::Light(c) } else { Color::Light(BaseColor::Black) }); return match object { // TODO: handle Actor some other way? EntityType::Actor(_) => ("!", corpse(BaseColor::Red)), EntityType::Corpse(ActorType::BigJelly) | EntityType::Corpse(ActorType::LittleJelly) => ("%", corpse(BaseColor::Magenta)), EntityType::Corpse(ActorType::Beetle) | EntityType::Corpse(ActorType::Dragonfly) => ("%", corpse(BaseColor::Cyan)), EntityType::Corpse(_) => ("%", corpse(BaseColor::Red)), }; } let (ch, color) = match tile { Tile::Wall => ("#", Color::Dark(BaseColor::Yellow)), Tile::Tree => ("#", Color::Dark(BaseColor::Green)), Tile::Ground => (".", Color::Light(BaseColor::Yellow)), }; let color = if vis { color } else { Color::Light(BaseColor::Black) }; let color_style = if tile.obstruction() == Obstruction::Full { ColorStyle::new(Color::Dark(BaseColor::Black), color) } else { black_bg(color) }; (ch, color_style) } fn event_direction(ev: Event) -> Option<Direction> { Some(match ev { // arrow keys Event::Key(Key::Up) => Direction::North, Event::Key(Key::Down) => Direction::South, Event::Key(Key::Left) => Direction::West, Event::Key(Key::Right) => Direction::East, // number keys Event::Char('1') => Direction::SouthWest, Event::Char('2') => Direction::South, Event::Char('3') => Direction::SouthEast, Event::Char('4') => Direction::West, Event::Char('6') => Direction::East, Event::Char('7') => Direction::NorthWest, Event::Char('8') => Direction::North, Event::Char('9') => Direction::NorthEast, // vi keys Event::Char('h') => Direction::West, Event::Char('j') => Direction::South, Event::Char('k') => Direction::North, Event::Char('l') => Direction::East, Event::Char('y') => Direction::NorthWest, Event::Char('u') => Direction::NorthEast, Event::Char('b') => Direction::SouthWest, Event::Char('n') => Direction::SouthEast, _ => { return None; } }) } } impl View for GameMap { fn draw(&self, pr: &Printer) { let game = self.game.borrow(); let player_pos = match game.player_position() { Some(pos) => pos, None => { return; } }; // TODO: recenter camera if off screen // TODO: manage screen resize let camera = self.camera.get().unwrap_or_else(|| { Camera::centered(pr.size, player_pos) }); self.camera.set(Some(camera)); for x in 0..pr.size.x { for y in 0..pr.size.y { let pos = camera.map_position(Vec2 { x, y }); let (ch, color_style) = GameMap::render_tile(game.view(pos)); pr.with_color(color_style, |pr| { pr.print(Vec2::new(x, y), ch); }); } } } fn on_event(&mut self, ev: Event) -> EventResult { let do_action = |action| { let mut game = self.game.borrow_mut(); // TODO: log error? let _ = game.take_player_action(action); EventResult::Consumed(None) }; match ev { Event::Char('5') => do_action(Action::Wait), Event::Char('.') => do_action(Action::Wait), Event::Char('R') => { self.camera.set(None); self.game.borrow_mut().restart(); EventResult::Consumed(None) }, _ => GameMap::event_direction(ev).map(|dir| do_action(Action::MoveAttack(dir))) .unwrap_or(EventResult::Ignored), } } fn required_size(&mut self, _constraint: Vec2) -> Vec2 { Vec2::new(11, 11) } } pub fn build_ui(siv: &mut Cursive, seed: u64) { let game = Rc::new(RefCell::new(Game::new(seed))); siv.add_global_callback(Event::CtrlChar('q'), |s| s.quit()); siv.add_fullscreen_layer(BoxView::with_full_screen( LinearLayout::new(Orientation::Vertical) .child(BoxView::with_full_screen(GameMap { game: game.clone(), camera: Cell::new(None), })) )); }
true
e824cdab292d06291ced8aa7c53f41872bfe6d7b
Rust
robbystk/advent-of-code-2020
/18-operation-order/src/main.rs
UTF-8
6,890
3.40625
3
[]
no_license
use std::fmt; fn input() -> String { let input_filename = &std::env::args().collect::<Vec<String>>()[1]; std::fs::read_to_string(input_filename).unwrap() } #[derive(Clone, Copy, Debug)] enum Token { OParen, CParen, Operator(Operator), Value(u64) } fn tokenize_line(input: &str) -> Vec<Token> { let mut rv = Vec::new(); for c in input.chars() { match c { ' ' => {}, '(' => rv.push(Token::OParen), ')' => rv.push(Token::CParen), '+' => rv.push(Token::Operator(Operator::Plus)), '*' => rv.push(Token::Operator(Operator::Times)), '0'..='9' => rv.push(Token::Value(c as u64 - 0x30)), _ => panic!("invalid character: `{}`", c) } } return rv; } enum Expression { Value(u64), Operation(Box<Operation>) } impl Expression { fn eval(self: &Expression) -> u64 { use Expression::*; match self { Value(n) => *n, Operation(oper) => (*oper).eval() } } } impl fmt::Debug for Expression { fn fmt(&self, mut f: &mut fmt::Formatter<'_>) -> fmt::Result { use Expression::*; match self { Value(n) => write!(&mut f, "{:?}", n), Operation(oper) => write!(&mut f, "{:?}", oper) } } } #[derive(Clone, Copy)] enum Operator { Plus, Times } impl fmt::Debug for Operator { fn fmt(&self, mut f: &mut fmt::Formatter<'_>) -> fmt::Result { use Operator::*; match self { Plus => write!(&mut f, "+"), Times => write!(&mut f, "*") } } } struct Operation { operator: Operator, lhs: Expression, rhs: Expression } impl Operation { fn eval(self: &Operation) -> u64 { use Operator::*; match self.operator { Plus => self.lhs.eval() + self.rhs.eval(), Times => self.lhs.eval() * self.rhs.eval() } } } impl fmt::Debug for Operation { fn fmt(&self, mut f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(&mut f, "({:?} {:?} {:?})", self.operator, self.lhs, self.rhs) } } fn parse_expression(tokens: &Vec<Token>) -> Expression { let mut tokens = tokens.iter().peekable(); let mut next_token = tokens.peek(); let mut expression_stack = Vec::new(); let mut token_stack = Vec::new(); while next_token.is_some() { let current_token = tokens.next(); next_token = tokens.peek(); match current_token { Some(Token::Value(n)) => { expression_stack.push(Expression::Value(*n)); let mut last_token = token_stack.last().map(|t| *t); loop { match last_token { Some(Token::Operator(Operator::Plus)) => { token_stack.pop(); let rhs = expression_stack.pop().unwrap(); let lhs = expression_stack.pop().unwrap(); expression_stack.push(Expression::Operation(Box::new(Operation { operator: Operator::Plus, lhs: lhs, rhs: rhs }))); last_token = token_stack.last().map(|t| *t); }, _ => break } } } Some(Token::Operator(oper)) => { token_stack.push(Token::Operator(*oper)); }, Some(Token::OParen) => { token_stack.push(Token::OParen); }, Some(Token::CParen) => { let mut last_token = token_stack.last().map(|t| *t); // pop operators until we get to the corresponding parenthesis loop { match last_token { Some(Token::Operator(oper)) => { token_stack.pop(); let rhs = expression_stack.pop().unwrap(); let lhs = expression_stack.pop().unwrap(); expression_stack.push(Expression::Operation(Box::new(Operation { operator: oper, lhs: lhs, rhs: rhs }))); last_token = token_stack.last().map(|t| *t); }, Some(Token::OParen) => { token_stack.pop(); last_token = token_stack.last().map(|t| *t); break; }, _ => break } } // now pop only pluses loop { match last_token { Some(Token::Operator(Operator::Plus)) => { token_stack.pop(); let rhs = expression_stack.pop().unwrap(); let lhs = expression_stack.pop().unwrap(); expression_stack.push(Expression::Operation(Box::new(Operation { operator: Operator::Plus, lhs: lhs, rhs: rhs }))); last_token = token_stack.last().map(|t| *t); }, _ => break } } } None => panic!("this is actually impossible") } // println!("expr: {:?}, token: {:?}", expression_stack, token_stack); } while expression_stack.len() > 1 { match token_stack.pop() { Some(Token::Operator(oper)) => { let rhs = expression_stack.pop().unwrap(); let lhs = expression_stack.pop().unwrap(); expression_stack.push(Expression::Operation(Box::new(Operation { operator: oper, lhs: lhs, rhs: rhs }))); }, t => panic!("don't know how to handle {:?}", t) } } return expression_stack.pop().unwrap(); } fn main() { let input = input(); let mut expressions = Vec::new(); for line in input.lines() { expressions.push(tokenize_line(line)); } println!("{:?}", expressions); let parsed = expressions.iter().map(parse_expression).collect::<Vec<_>>(); println!("parsed: {:?}", parsed); let evaluated = parsed.iter().map(|e| e.eval()).collect::<Vec<_>>(); println!("evaluated: {:?}", evaluated); let sum: u64 = evaluated.iter().sum(); println!("sum: {}", sum); }
true
23b12f9100227ad4c90761e3a4cdec2c9546badb
Rust
jeffcarp/pkcs7
/tests/integration_test.rs
UTF-8
2,778
3.0625
3
[ "MIT" ]
permissive
extern crate pkcs7; use pkcs7::*; #[test] fn pkcs7_pads_short_input() { let mut actual: Vec<u8> = vec![8, 3, 4, 11, 4]; pad(&mut actual, 8); let expected: Vec<u8> = vec![8, 3, 4, 11, 4, 3, 3, 3]; assert_eq!(actual, expected); } #[test] fn pkcs7_un_pad_short_input() { let mut actual: Vec<u8> = vec![8, 3, 4, 11, 4, 3, 3, 3]; un_pad(&mut actual); let expected: Vec<u8> = vec![8, 3, 4, 11, 4]; assert_eq!(actual, expected); } #[test] fn pecs7_pad_perfect_input() { let mut actual: Vec<u8> = vec![0, 1, 2, 3]; pad(&mut actual, 4); let expected: Vec<u8> = vec![0, 1, 2, 3, 4, 4, 4, 4]; assert_eq!(actual, expected); } #[test] fn pkcs7_un_pad_perfect_input() { let mut actual: Vec<u8> = vec![0, 1, 2, 3, 4, 4, 4, 4]; un_pad(&mut actual); let expected: Vec<u8> = vec![0, 1, 2, 3]; assert_eq!(actual, expected); } #[test] fn pkcs7_u8_overflow() { const BLOCK_SIZE: usize = 11; let expected = vec![0; 1_000_000]; let mut actual = expected.clone(); pad(&mut actual, BLOCK_SIZE as u8); assert_eq!(actual.len() % BLOCK_SIZE, 0); un_pad(&mut actual); assert_eq!(actual, expected); } #[test] fn pkcs7_stackexchange_1() { let expected = [ 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21, ]; let mut buffer = expected.to_vec(); pad(&mut buffer, 16); assert_eq!( buffer.as_slice(), [ 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21, 0x03, 0x03, 0x03 ].as_ref() ); un_pad(&mut buffer); assert_eq!(buffer.as_slice(), expected.as_ref()); } #[test] fn pkcs7_stackexchange_2() { let expected = [ 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21, ]; let mut buffer = expected.to_vec(); pad(&mut buffer, 20); assert_eq!( buffer.as_slice(), [ 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07 ].as_ref() ); un_pad(&mut buffer); assert_eq!(buffer.as_slice(), expected.as_ref()); }
true
2e13bcbf2ff4a73edc2625e11cee5e25966727b9
Rust
shaqb4/rust-book
/variables/src/main.rs
UTF-8
963
3.46875
3
[ "MIT" ]
permissive
fn main() { const MAX_POINTS: u32 = 100_000; println!("The value of MAX_POINTS is {}", MAX_POINTS); let mut x = 5; println!("The value of x is {}", x); x = 6; println!("The value of x is {}", x); let f1: f32 = 0.23; let f2: f64 = 0.24; let f3 = 0.25; println!("The value of f1 is {}", f1); println!("The value of f2 is {}", f2); println!("The value of f3 is {}", f3); let spaces = " "; let spaces = spaces.len(); println!("spaces is {}", spaces); println!("43 % 5 = {}", 43 % 5); let tup: (i32, f64, u8) = (500, 6.4, 1); //let (x, y, z) = tup; println!("tup as string is {}, {}, {}", tup.0, tup.1, tup.2); let arr = [1, 2, 3, 4, 5, 6]; println!("arr as as string is {}", arr[0]); let arr2: [bool; 4] = [true, false, false, true]; println!("arr2 as as string is {}", arr2[0]); let arr3 = [123; 4]; println!("arr3 as as string is {}", arr3.len()); }
true
8e462bcdd5073d1bd8e7b0d2ba14da08f1f2d809
Rust
lilith645/octo-shot
/src/modules/scenes/character_creator_screen.rs
UTF-8
3,071
2.59375
3
[ "MIT" ]
permissive
use maat_graphics::DrawCall; use crate::modules::scenes::Scene; use crate::modules::scenes::SceneData; use crate::modules::scenes::{PlayScreen}; use crate::cgmath::{Vector2, Vector4}; pub struct CharacterCreatorScreen { data: SceneData, } impl CharacterCreatorScreen { pub fn new() -> CharacterCreatorScreen { CharacterCreatorScreen { data: SceneData::new_default(), } } } impl Scene for CharacterCreatorScreen { fn data(&self) -> &SceneData { &self.data } fn mut_data(&mut self) -> &mut SceneData { &mut self.data } fn future_scene(&mut self, _window_size: Vector2<f32>) -> Box<dyn Scene> { let dim = self.data().window_dim; Box::new(PlayScreen::new(dim)) } fn update(&mut self, _delta_time: f32) { if self.data().keys.m_pressed() { self.mut_data().next_scene = true; } } fn draw(&self, draw_calls: &mut Vec<DrawCall>) { let dim = self.data().window_dim; let (width, height) = (dim.x as f32, dim.y as f32); draw_calls.push(DrawCall::reset_ortho_camera()); draw_calls.push(DrawCall::draw_text_basic(Vector2::new(10.0, height-64.0), Vector2::new(128.0, 128.0), Vector4::new(1.0, 1.0, 1.0, 1.0), "Character Creator".to_string(), "Arial".to_string())); draw_calls.push(DrawCall::draw_text_basic_centered(Vector2::new(width*0.5, height*0.7), Vector2::new(128.0, 128.0), Vector4::new(1.0, 1.0, 1.0, 1.0), "Press R for Reload and Unjam, Left mouse for shoot".to_string(), "Arial".to_string())); draw_calls.push(DrawCall::draw_text_basic_centered(Vector2::new(width*0.5, height*0.6), Vector2::new(128.0, 128.0), Vector4::new(1.0, 1.0, 1.0, 1.0), "Space for dash".to_string(), "Arial".to_string())); draw_calls.push(DrawCall::draw_text_basic_centered(Vector2::new(width*0.5, height*0.4), Vector2::new(128.0, 128.0), Vector4::new(1.0, 1.0, 1.0, 1.0), "Press m to start game".to_string(), "Arial".to_string())); draw_calls.push(DrawCall::draw_text_basic_centered(Vector2::new(width*0.5, height*0.5), Vector2::new(128.0, 128.0), Vector4::new(1.0, 1.0, 1.0, 1.0), "Press escape to return to this screen".to_string(), "Arial".to_string())); } }
true
26372829f67b6fd4d7012a355385f461db042171
Rust
nervosnetwork/ckb-cli
/ckb-signer/src/keystore/error.rs
UTF-8
1,419
2.75
3
[ "MIT" ]
permissive
use std::io; use ckb_types::H160; use thiserror::Error; #[derive(Error, Debug, Eq, PartialEq)] pub enum Error { #[error("Account locked: {0:x}")] AccountLocked(H160), #[error("Account not found: {0:x}")] AccountNotFound(H160), #[error("Key mismatch, got {got:x}, expected: {expected:x}")] KeyMismatch { got: H160, expected: H160 }, #[error("Key already exists {0:x}")] KeyExists(H160), #[error("Wrong password for {0:x}")] WrongPassword(H160), #[error("Check password failed")] CheckPasswordFailed, #[error("Parse json failed: {0}")] ParseJsonFailed(String), #[error("Unsupported cipher: {0}")] UnsupportedCipher(String), #[error("Unsupported kdf: {0}")] UnsupportedKdf(String), #[error("Generate secp256k1 secret failed, tried: {0}")] GenSecpFailed(u16), #[error("Invalid secp256k1 secret key")] InvalidSecpSecret, #[error("Search derived address failed")] SearchDerivedAddrFailed, #[error("IO error: {0}")] Io(String), #[error("Other error: {0}")] Other(String), } impl From<String> for Error { fn from(err: String) -> Error { Error::Other(err) } } impl From<&str> for Error { fn from(err: &str) -> Error { Error::Other(err.to_owned()) } } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err.to_string()) } }
true
e6da8d2c424132ad69b79b16aa6dd3f94101b064
Rust
HerbLuo/query-pro-bg-rust
/src/helper/resp.rs
UTF-8
1,446
2.609375
3
[]
no_license
use rocket_contrib::json::Json; use crate::ec; use serde::Serialize; use rocket::http::Status; use rocket::response::{Responder, Response}; use rocket::request::Request; #[derive(Debug, Serialize)] pub struct Data<T> { pub ok: u8, // 0 false, 1 true pub data: T, } #[derive(Debug, Serialize)] pub struct HttpError { pub code: u16, pub serial: String, pub tip: Option<&'static str>, } #[derive(Debug, Clone, PartialEq)] pub struct WithStatus<R>(pub Status, pub R); impl<'r, R: Responder<'r>> Responder<'r> for WithStatus<R> { fn respond_to(self, req: &Request) -> Result<Response<'r>, Status> { Response::build_from(self.1.respond_to(req)?) .status(self.0) .ok() } } pub type HttpErrorData = WithStatus<Json<Data<HttpError>>>; pub type JsonResult<T> = Result<Json<Data<T>>, HttpErrorData>; // impl<T: Serialize + JsonSchema> OpenApiResponder<'_> for WithStatus<Json<T>> { // fn responses(gen: &mut OpenApiGenerator) -> Result<Responses, OpenApiError> { // let mut responses = Responses::default(); // let schema = gen.json_schema::<T>()?; // add_schema_response(&mut responses, 0, "application/json", schema)?; // Ok(responses) // } // } pub struct Rollback { pub reason: HttpErrorData } impl From<diesel::result::Error> for Rollback { fn from(e: diesel::result::Error) -> Self { rollback!(ec::ServerError, e) } }
true
f1dee979c9e44271436c1c9d8d50b77b113f783e
Rust
sonro/Ellie
/src/commands/search/github/repository.rs
UTF-8
7,213
2.6875
3
[ "MIT", "GPL-3.0-only" ]
permissive
use crate::commands::search::github::repository::repository::RepositoryRepositoryDefaultBranchRefTargetOn::Commit; use crate::utilities::color_utils; use crate::utilities::format_int; use byte_unit::Byte; use chrono::Utc; use graphql_client::{GraphQLQuery, Response}; use reqwest::blocking::Client; use serenity::client::Context; use serenity::framework::standard::macros::command; use serenity::framework::standard::Args; use serenity::framework::standard::CommandResult; use serenity::model::prelude::Message; use serenity::utils::Colour; type DateTime = chrono::DateTime<Utc>; type URI = String; #[derive(GraphQLQuery)] #[graphql( schema_path = "src/graphql/schemas/github.graphql", query_path = "src/graphql/queries/github/repository.graphql", response_derives = "Debug" )] struct Repository; #[command] #[description("Displays information about a specified GitHub repository")] #[aliases("repo", "repository")] #[min_args(2)] #[max_args(2)] pub fn repository(context: &mut Context, message: &Message, mut arguments: Args) -> CommandResult { if arguments.is_empty() { message.channel_id.send_message(&context, |message| { message.embed(|embed| { embed.title("Error: No repository details provided."); embed.description("You did not provide any repository details. Please provide them and then try again.") }) })?; return Ok(()); } let user_agent: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); let token: String = std::env::var("GITHUB_KEY").expect("No API key detected"); let mut color: Colour = Colour::new(0x0033_3333); let client = Client::builder().user_agent(user_agent).build()?; let endpoint = "https://api.github.com/graphql"; let query = Repository::build_query(repository::Variables { owner: arguments.single::<String>()?, name: arguments.single::<String>()?, }); let resp: Response<repository::ResponseData> = client.post(endpoint).bearer_auth(token).json(&query).send()?.json()?; let resp_data: repository::ResponseData = resp.data.expect("missing response data"); let repository = match resp_data.repository { Some(repository) => repository, None => { message.channel_id.send_message(&context, |message| { message.embed(|embed| { embed.title("Error: Repository Not Found."); embed.description( "I was unable to find a repository matching the terms you were looking for. \ Please try searching for a different repository.", ) }) })?; return Ok(()); } }; let repository_name = repository.name_with_owner; let repository_url = repository.url; let repository_stars = format_int(repository.stargazers.total_count as usize); let repository_forks = format_int(repository.fork_count as usize); let repository_creation_date = repository.created_at.format("%A, %B %e, %Y @ %l:%M %P"); let repository_modified_date = repository.updated_at.format("%A, %B %e, %Y @ %l:%M %P"); let repository_default_branch = repository.default_branch_ref.as_ref().unwrap(); let repository_default_branch_name = &repository_default_branch.name; let repository_default_branch_commits = match &repository_default_branch.target.on { Commit(c) => format_int(c.history.total_count as usize), _ => "".to_string(), }; let repository_website = match repository.homepage_url { Some(url) => { if url.is_empty() { "No website available.".to_string() } else { format!("[Click here]({})", url) } } None => "No website available.".to_string(), }; let repository_disk_usage = match repository.disk_usage { Some(usage) => { let bytes_in_kb = byte_unit::n_kb_bytes!(usage as u128); let bytes = Byte::from_bytes(bytes_in_kb); let friendly_bytes = bytes.get_appropriate_unit(false); friendly_bytes.format(2) } None => "No disk usage data is available.".to_string(), }; let repository_description = match repository.description { Some(description) => format!("{}\n\n", description), None => "".to_string(), }; let repository_language = match repository.primary_language { Some(language) => { let code: &str = language.color.as_ref().unwrap(); match color_utils::RGB::from_hex_code(&code) { Ok(rgb) => color = Colour::from_rgb(rgb.r, rgb.g, rgb.b), Err(_) => println!("{} isn't a valid color code...", code), } language.name } None => "No language is available.".to_string(), }; let repository_code_of_conduct = match repository.code_of_conduct { Some(conduct) => { if conduct.url.is_none() { conduct.name } else { format!("[{}]({})", conduct.name, conduct.url.unwrap()) } } None => "No code of conduct is available.".to_string(), }; let repository_owner = repository.owner.login; let repository_owner_url = repository.owner.url; let repository_owner_avatar = repository.owner.avatar_url; let repository_license = match repository.license_info { Some(license) => { if license.name == "Other" { license.name } else { format!("[{}]({})", license.name, license.url.unwrap()) } } None => "No license available.".to_string(), }; message.channel_id.send_message(&context, |message| { message.embed(|embed| { embed.title(repository_name); embed.url(repository_url); embed.thumbnail(repository_owner_avatar); embed.color(color); embed.description(format!( "{}\ **Owner**: [{}]({})\n\ **License**: {}\n\ **Language**: {}\n\ **Commits**: {} ({})\n\ **Website**: {}\n\ **Code of Conduct**: {}\n\ **Created on**: {}\n\ **Last updated**: {}\n\ **Disk usage**: {}\n\ **Star count**: {}\n\ **Fork count**: {}\n", repository_description, repository_owner, repository_owner_url, repository_license, repository_language, repository_default_branch_commits, repository_default_branch_name, repository_website, repository_code_of_conduct, repository_creation_date, repository_modified_date, repository_disk_usage, repository_stars, repository_forks )); embed.footer(|footer| footer.text("Powered by the GitHub GraphQL API.")) }) })?; Ok(()) }
true
c1e1c279dccbd41381eaf57dc5a448a15eb77b1a
Rust
DomNomNom/hashtorio
/src/main.rs
UTF-8
2,425
2.625
3
[]
no_license
// use std::time; use ggez::graphics::DrawParam; use ggez::*; struct State { dt: std::time::Duration, t: graphics::Text, dp: DrawParam, } impl ggez::event::EventHandler for State { fn update(&mut self, ctx: &mut Context) -> GameResult { while timer::check_update_time(ctx, 60) { // update_game_physics()?; } Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult { graphics::clear(ctx, graphics::BLACK); self.t.fragments_mut()[0].text = format!( "Hello ggez! {}Hz", 1.0 / (1e-9 * (self.dt.as_nanos() as f64)) ); self.dt = timer::delta(ctx); graphics::draw(ctx, &self.t, self.dp)?; graphics::present(ctx)?; timer::yield_now(); Ok(()) } fn mouse_button_down_event( &mut self, _ctx: &mut Context, _button: event::MouseButton, _x: f32, _y: f32, ) { } fn mouse_button_up_event( &mut self, _ctx: &mut Context, _button: event::MouseButton, _x: f32, _y: f32, ) { } fn mouse_motion_event(&mut self, _ctx: &mut Context, _x: f32, _y: f32, _dx: f32, _dy: f32) {} fn mouse_wheel_event(&mut self, _ctx: &mut Context, _x: f32, _y: f32) {} fn key_down_event( &mut self, ctx: &mut Context, keycode: event::KeyCode, _keymods: event::KeyMods, _repeat: bool, ) { if keycode == event::KeyCode::Escape { event::quit(ctx); } } fn key_up_event( &mut self, _ctx: &mut Context, _keycode: event::KeyCode, _keymods: event::KeyMods, ) { } fn focus_event(&mut self, _ctx: &mut Context, _gained: bool) {} fn resize_event(&mut self, _ctx: &mut Context, _width: f32, _height: f32) {} } fn main() { let state = &mut State { dt: std::time::Duration::new(0, 0), t: graphics::Text::new(graphics::TextFragment::from(format!( "Hello ggez! dt = {}ms", 0 ))), dp: DrawParam::default(), }; let mut c = conf::Conf::new(); c.window_setup.title = String::from("hashtorio!").to_owned(); let (ref mut ctx, ref mut event_loop) = ContextBuilder::new("hello_ggez", "DomNomNom") .conf(c) .build() .unwrap(); event::run(ctx, event_loop, state).unwrap(); }
true
2232d67c276c6798681812de5d210f73e490e61d
Rust
fonline-roleplay/rust_workspace
/web_server/core/src/web/meta/rank.rs
UTF-8
2,679
2.5625
3
[]
no_license
use super::*; use actix_session::SessionExt; use actix_web::web::Data; use std::sync::Arc; pub async fn get_ranks(data: Arc<AppState>, user_id: u64) -> Result<Vec<Rank>, &'static str> { data.mrhandy .as_ref() .expect("Discord config") .with_guild_member(user_id, |guild, member| { let mut ranks = mrhandy::MrHandy::get_roles( guild, member, role_to_rank(&data.config.discord.as_ref().expect("Discord config").roles), ); ranks.sort_by_key(|key| std::cmp::Reverse(*key)); ranks }) .await } pub async fn get_user_record(data: &AppState, user_id: u64) -> Result<UserRecord, &'static str> { data.mrhandy .as_ref() .expect("Discord config") .with_guild_member(user_id, |guild, member| { let mut ranks = mrhandy::MrHandy::get_roles( guild, member, role_to_rank(&data.config.discord.as_ref().expect("Discord config").roles), ); ranks.sort_by_key(|key| std::cmp::Reverse(*key)); let (name, nick) = mrhandy::MrHandy::get_name_nick(member); UserRecord { name, nick, ranks } }) .await } pub struct UserRecord { pub name: String, pub nick: Option<String>, pub ranks: Vec<Rank>, } #[derive(Debug, Clone, Copy, PartialOrd, PartialEq, Ord, Eq)] pub enum Rank { Unknown, Player, GameMaster, Developer, Admin, } fn role_to_rank<'b>(config: &'b crate::config::Roles) -> impl 'b + Fn(&mrhandy::Role) -> Rank { move |role| { if role.name == config.player { Rank::Player } else if role.name == config.gamemaster { Rank::GameMaster } else if role.name == config.developer { Rank::Developer } else if role.name == config.admin { Rank::Admin } else { Rank::Unknown } } } pub struct Member { pub id: u64, pub ranks: Vec<Rank>, } pub fn extract_member( req: &HttpRequest, ) -> impl Future<Output = Result<Option<Member>, actix_web::Error>> { let data = req .app_data() .cloned() .map(Data::<AppState>::into_inner) .ok_or("No AppState data") .map_err(internal_error); let session = req.get_session(); let user_id = get_user_id(&session); async move { match user_id { Some(id) => { let ranks = get_ranks(data?, id).await.map_err(internal_error)?; Ok(Some(Member { id, ranks })) } None => Ok(None), } } }
true
9c47dcb8b976f963d127a397b324ba7c2c56eb0a
Rust
coreylowman/projectEuler
/src/problems/problem017.rs
UTF-8
725
3.234375
3
[]
no_license
// http://en.wikipedia.org/wiki/English_numerals fn num_word_count(n: u64) -> u64 { let below_twenty = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8]; let tens_digit = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6]; if n < 20 { return below_twenty[n as usize]; } else if n < 100 { return tens_digit[(n / 10) as usize] + below_twenty[(n % 10) as usize]; } else if n % 100 == 0 { return below_twenty[(n / 100) as usize] + 7; } else { return below_twenty[(n / 100) as usize] + 7 + 3 + num_word_count(n % 100); } } fn go() -> String { let mut sum = 0; for i in 1..1000 { sum += num_word_count(i); } (sum + 11).to_string() } problem!(go, 21124);
true
1227232e42156da36a2947fc845e6849029b5f57
Rust
veaba/learn-rust
/src/type/type.rs
UTF-8
218
2.65625
3
[]
no_license
fn main(){ /**boolean*/ // let t = true; // let f =false; // let mut f_t =false; // println!("{}",t); // println!("{}",f); // f_t=t; // println!("{}",f); // println!("{}",f_t) /**/ }
true
821fdf5ef94b3b9c9ac97226ad53d6088f999261
Rust
arkoh/arkoh-cube3d
/src/main/callback.rs
UTF-8
3,141
2.671875
3
[]
no_license
use glfw; use std::libc; use event; use extra::arc::RWArc; pub struct ErrorContext; impl glfw::ErrorCallback for ErrorContext { fn call(&self, _: glfw::Error, description: ~str) { println!("GLFW Error: {:s}", description); } } // // Scroll Callback // pub struct ScrollCallback { collector: RWArc<~[event::Event]> } impl ScrollCallback { pub fn new(collector: RWArc<~[event::Event]>) -> ScrollCallback { ScrollCallback { collector: collector } } } impl glfw::ScrollCallback for ScrollCallback { fn call(&self, _: &glfw::Window, x: f64, y: f64) { self.collector.write(|c| c.push(event::Scroll(x as f32, y as f32))) } } // // Cursor Pos Callback // pub struct CursorPosCallback { collector: RWArc<~[event::Event]> } impl CursorPosCallback { pub fn new(collector: RWArc<~[event::Event]>) -> CursorPosCallback { CursorPosCallback { collector: collector } } } impl glfw::CursorPosCallback for CursorPosCallback { fn call(&self, _: &glfw::Window, x: f64, y: f64) { self.collector.write(|c| c.push(event::CursorPos(x as f32, y as f32))) } } // // Mouse Button Callback // pub struct MouseButtonCallback { collector: RWArc<~[event::Event]> } impl MouseButtonCallback { pub fn new(collector: RWArc<~[event::Event]>) -> MouseButtonCallback { MouseButtonCallback { collector: collector } } } impl glfw::MouseButtonCallback for MouseButtonCallback { fn call(&self, _: &glfw::Window, button: glfw::MouseButton, action: glfw::Action, mods: glfw::Modifiers) { if action == glfw::Press { self.collector.write(|c| c.push(event::ButtonPressed(button, mods))) } else { self.collector.write(|c| c.push(event::ButtonReleased(button, mods))) } } } // // Key callback // pub struct KeyCallback { collector: RWArc<~[event::Event]> } impl KeyCallback { pub fn new(collector: RWArc<~[event::Event]>) -> KeyCallback { KeyCallback { collector: collector } } } impl glfw::KeyCallback for KeyCallback { fn call(&self, _: &glfw::Window, key: glfw::Key, _: libc::c_int, action: glfw::Action, _: glfw::Modifiers) { if action == glfw::Press { self.collector.write(|c| c.push(event::KeyPressed(key))) } else { self.collector.write(|c| c.push(event::KeyReleased(key))) } } } // // Framebuffer callback // pub struct FramebufferSizeCallback { collector: RWArc<~[event::Event]> } impl FramebufferSizeCallback { pub fn new(collector: RWArc<~[event::Event]>) -> FramebufferSizeCallback { FramebufferSizeCallback { collector: collector } } } impl glfw::FramebufferSizeCallback for FramebufferSizeCallback { fn call(&self, _: &glfw::Window, w: i32, h: i32) { self.collector.write(|c| c.push(event::FramebufferSize(w as f32, h as f32))) } }
true
05262b80dfc528cde7910b415b72d5bf327e0bfd
Rust
warnp/coding_dojo_belote
/src/card_deck.rs
UTF-8
705
3.625
4
[]
no_license
use card::Card; pub struct CardDeck { cards:Vec<Card>, } impl CardDeck { pub fn new() -> CardDeck{ CardDeck{} } pub fn get_cards(&self) -> Vec<Card>{ let mut cards = Vec::new(); for i in 0..32 { cards.push(Card::new_with_pointers("jack", "toto")); } cards } } #[cfg(test)] mod tests{ use super::*; #[test] fn get_some_cards(){ let card_deck = CardDeck::new(); let cards = card_deck.get_cards(); assert!(cards.len()>0); } #[test] fn get_32_cards(){ let card_deck = CardDeck::new(); let cards = card_deck.get_cards(); assert!(cards.len() == 32); } }
true
bc7ca1f62640750c9c571fff0bd85a41b61dda26
Rust
nordsoyv/rust-mono
/rust-cdl-compiler/cdl-core/src/select/mod.rs
UTF-8
7,263
2.953125
3
[]
no_license
mod lex; mod parse; use parse::AstEntityNode; use parse::AstFieldNode; use select::lex::lex_selector; use select::parse::{SelectorParser, Selector}; use parse::ParseResult; pub fn select_entity<'a>(pr: &'a ParseResult, selector_string: &str) -> Vec<&'a AstEntityNode> { let tokens = lex_selector(selector_string); let parser = SelectorParser::new(tokens); let selector = parser.parse().unwrap(); let mut result = vec![]; for ent in &pr.entities { if matches_selector(&ent, &selector) { result.push(ent); } } let mut current_selector = selector; while current_selector.child.is_some() { current_selector = *current_selector.child.unwrap(); let sub_results = select_in_entities(result, &current_selector, pr); result = sub_results; } return result; } pub fn select_field<'a>(root: &'a ParseResult, selector_string: &str) -> Vec<&'a AstFieldNode> { let tokens = lex_selector(selector_string); let parser = SelectorParser::new(tokens); let mut selector = parser.parse().unwrap(); let mut current_set = Vec::new(); for e in &root.entities { current_set.push(e); } // first pass , check in root entities if selector.child.is_some() { let mut next_set = Vec::new(); for e in current_set { if matches_selector(e, &selector) { next_set.push(e); } } current_set = next_set; selector = *selector.child.unwrap(); } // pass 2 -> n , check in the current set while selector.child.is_some() { let next_set = select_in_entities(current_set, &selector, root); current_set = next_set; selector = *selector.child.unwrap(); } // got to the last selector , should be a field selector let mut result = Vec::new(); let mut fields = Vec::new(); for entity in current_set { for field_ref in &entity.fields { fields.push(root.get_field(*field_ref)); } } for field in fields { match selector.identifier { Some(ref id) => { if id == &field.identifier { result.push(field); } } None => {} } } return result; } fn select_in_entities<'a>(entities: Vec<&AstEntityNode>, selector: &Selector, pr: &'a ParseResult) -> Vec<&'a AstEntityNode> { let mut result = vec![]; for entity in entities { for child_id in &entity.children { let child = pr.get_entity(*child_id); if matches_selector(child, selector) { result.push(child); } let mut sub_results = select_in_entities(vec![child], selector, pr); if sub_results.len() > 0 { result.append(&mut sub_results); } } } return result; } fn matches_selector(header: &AstEntityNode, selector: &Selector) -> bool { let matches = true; match selector.main_type { Some(ref s) => { if &header.main_type != s { return false; } } None => {} } match selector.sub_type { Some(ref s) => { match header.sub_type { Some(ref hs) => { if hs != s { return false; } } None => { // matching on an sub_type, but entity has none, no match return false; } } } None => {} } match selector.identifier { Some(ref s) => { match header.identifier { Some(ref hi) => { if hi != s { return false; } } None => { // matching on an identifier, but entity has none, no match return false; } } } None => {} } return matches; } #[cfg(test)] mod test { use lex::Lexer; use parse::Parser; use select::select_entity; use select::select_field; #[test] fn select_entity_simple() { let cdl = " widget kpi { label : \"Label\" labels : \"Labels\" } widget kpi2 { label : \"Label\" labels : \"Labels\" } ".to_string(); let lexer = Lexer::new(cdl); let lex_items = lexer.lex().unwrap(); let parser = Parser::new(lex_items); let root = parser.parse().unwrap(); let result = select_entity(&root, "widget[kpi]"); assert_eq!(result.len(), 1); } #[test] fn select_entity_simple2() { let cdl = " page { widget kpi { label : \"Label\" labels : \"Labels\" } } page { widget kpi { label : \"Label\" labels : \"Labels\" } widget kpi2 { label : \"Label\" labels : \"Labels\" } widget kpi3 #kpiid { label : \"Label\" labels : \"Labels\" } } ".to_string(); let lexer = Lexer::new(cdl); let lex_items = lexer.lex().unwrap(); let parser = Parser::new(lex_items); let pr = parser.parse().unwrap(); assert_eq!(select_entity(&pr, "widget[kpi]").len(), 2); assert_eq!(select_entity(&pr, "widget[kpi2]").len(), 1); assert_eq!(select_entity(&pr, "widget").len(), 4); assert_eq!(select_entity(&pr, "widget.kpiid").len(), 1); } #[test] fn select_nested_entity() { let cdl = " page { widget kpi { label : \"Label\" labels : \"Labels\" } } page { widget kpi { label : \"Label\" labels : \"Labels\" } widget kpi2 { label : \"Label\" labels : \"Labels\" } widget kpi3 #kpiid { label : \"Label\" labels : \"Labels\" } } ".to_string(); let lexer = Lexer::new(cdl); let lex_items = lexer.lex().unwrap(); let parser = Parser::new(lex_items); let root = parser.parse().unwrap(); assert_eq!(select_entity(&root, "page > widget").len(), 4); assert_eq!(select_entity(&root, "page > widget[kpi]").len(), 2); assert_eq!(select_entity(&root, "page > widget[kpi2]").len(), 1); } #[test] fn select_field_simple() { let cdl = " page { widget kpi { label : \"Label\" labels : \"Labels\" } } page { widget kpi { label : \"Label\" labels : \"Labels\" } widget kpi2 { label : \"Label\" labels : \"Labels\" } widget kpi3 #kpiid { label : \"Label\" labels : \"Labels\" } } ".to_string(); let lexer = Lexer::new(cdl); let lex_items = lexer.lex().unwrap(); let parser = Parser::new(lex_items); let root = parser.parse().unwrap(); assert_eq!(select_field(&root, ".label").len(), 4); assert_eq!(select_field(&root, "page > widget[kpi3] > .label").len(), 1); assert_eq!(select_field(&root, "widget > .label").len(), 4); } }
true
b65a3c8d081db5caaac8e09869d4303ac72ac60e
Rust
chc4/gallium
/src/key.rs
UTF-8
3,274
2.90625
3
[]
no_license
use std::fmt::{Debug,Formatter,Result}; use std::str::from_utf8; use x11::xlib::{KeyCode,KeySym}; use xserver::{XServer,keysym_to_string}; bitflags! { #[allow(non_upper_case_globals)] flags KeyMod: u32 { const SHIFT = 0b000000001, const LOCK = 0b000000010, const CONTROL = 0b000000100, const MOD1 = 0b000001000, const MOD2 = 0b000010000, const MOD3 = 0b000100000, const MOD4 = 0b001000000, const MOD5 = 0b010000000, const KOMMAND = 0b100000000, } } #[derive(Eq,PartialEq,Clone,Copy)] pub struct Key { pub code: KeyCode, pub sym: KeySym, pub modifier: KeyMod, } const LOOKUP: [(&'static str, KeyMod); 9] = [("S-",SHIFT), ("Lock-",LOCK), ("C-",CONTROL), ("M-",MOD1), ("M2-",MOD2), ("M3-",MOD3), ("M4-",MOD4), ("M5-",MOD5), ("K-",KOMMAND)]; impl Debug for Key { fn fmt(&self, f: &mut Formatter) -> Result { let (pref,x) = self.chord(); write!(f,"{}{}",pref,x) } } impl Key { pub fn parse(code: KeyCode, modifier: u32, serv: &XServer) -> Key { let mut sym = 0; sym = serv.keycode_to_keysym(code); let mut mo = match KeyMod::from_bits(modifier) { Some(v) => v, None => KeyMod::empty() }; // Replace the KOMMAND bit with what it's set to if (mo & KOMMAND).bits() != 0 { println!("Replace KOMMAND pls"); mo = mo | serv.kommand_mod.borrow().unwrap(); mo = mo & !KOMMAND; } Key { code: code, sym: sym, modifier: mo } } pub fn create(s: String, serv: &XServer) -> Key { let mut flag = KeyMod::empty(); let mut key = ""; for mut m in s.split('-') { let mut full = m.to_string(); full.push_str("-"); if full == "K-" { flag = flag | serv.kommand_mod.borrow().unwrap(); } else { let mut found = false; for &(c,k) in LOOKUP.iter() { if full == c { flag = flag | k; found = true; } } if !found { key = m } } } let mut sym = serv.string_to_keysym(&mut key.to_string()); let code = serv.keysym_to_keycode(sym); Key { code: code as KeyCode, sym: sym, modifier: flag } } pub fn chord(&self) -> (String,&'static str) { let mut pref = "".to_string(); for b in 0..8 { if self.modifier.contains(LOOKUP[b].1) { pref.push_str(LOOKUP[b].0); } } let cs = keysym_to_string(self.sym); let x = from_utf8(cs.to_bytes()).unwrap(); (pref,x) } }
true
447b6c35ca60a5a9805714005e83773ff76159ab
Rust
TabbyML/tabby
/crates/tabby-common/src/config.rs
UTF-8
1,399
3
3
[ "Apache-2.0" ]
permissive
use std::{ io::{Error, ErrorKind}, path::PathBuf, }; use filenamify::filenamify; use serde::Deserialize; use crate::path::{config_file, repositories_dir}; #[derive(Deserialize, Default)] pub struct Config { #[serde(default)] pub repositories: Vec<Repository>, #[serde(default)] pub experimental: Experimental, } #[derive(Deserialize, Default)] pub struct Experimental { #[serde(default = "default_as_false")] pub enable_prompt_rewrite: bool, } impl Config { pub fn load() -> Result<Self, Error> { let file = serdeconv::from_toml_file(crate::path::config_file().as_path()); file.map_err(|err| { Error::new( ErrorKind::InvalidData, format!( "Config {:?} doesn't exist or is not valid: `{:?}`", config_file(), err ), ) }) } } #[derive(Deserialize)] pub struct Repository { pub git_url: String, } impl Repository { pub fn dir(&self) -> PathBuf { repositories_dir().join(filenamify(&self.git_url)) } } fn default_as_false() -> bool { false } #[cfg(test)] mod tests { use super::Config; #[test] fn it_parses_empty_config() { let config = serdeconv::from_toml_str::<Config>(""); debug_assert!(config.is_ok(), "{}", config.err().unwrap()); } }
true
3057873698a334dca20b4161831024afd3cfe83c
Rust
nikomatsakis/rust
/src/test/run-pass/task-comm.rs
UTF-8
2,997
3.015625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "bzip2-1.0.6", "BSD-1-Clause" ]
permissive
use std; import task; import task::task; import comm; import comm::chan; import comm::port; import comm::send; import comm::recv; fn main() { test00(); // test01(); test02(); test03(); test04(); test05(); test06(); } fn test00_start(ch: chan<int>, message: int, count: int) { #debug("Starting test00_start"); let i: int = 0; while i < count { #debug("Sending Message"); send(ch, message + 0); i = i + 1; } #debug("Ending test00_start"); } fn test00() { let number_of_tasks: int = 1; let number_of_messages: int = 4; #debug("Creating tasks"); let po = port(); let ch = chan(po); let i: int = 0; let tasks = []; while i < number_of_tasks { i = i + 1; tasks += [ task::spawn_joinable {|| test00_start(ch, i, number_of_messages);} ]; } let sum: int = 0; for t in tasks { i = 0; while i < number_of_messages { sum += recv(po); i = i + 1; } } for t in tasks { task::join(t); } #debug("Completed: Final number is: "); assert (sum == number_of_messages * (number_of_tasks * number_of_tasks + number_of_tasks) / 2); } fn test01() { let p = port(); #debug("Reading from a port that is never written to."); let value: int = recv(p); log(debug, value); } fn test02() { let p = port(); let c = chan(p); #debug("Writing to a local task channel."); send(c, 42); #debug("Reading from a local task port."); let value: int = recv(p); log(debug, value); } obj vector(mutable x: int, y: int) { fn length() -> int { x = x + 2; ret x + y; } } fn test03() { #debug("Creating object ..."); let v: vector = vector(1, 2); #debug("created object ..."); let t: vector = v; log(debug, v.length()); } fn test04_start() { #debug("Started task"); let i: int = 1024 * 1024; while i > 0 { i = i - 1; } #debug("Finished task"); } fn test04() { #debug("Spawning lots of tasks."); let i: int = 4; while i > 0 { i = i - 1; task::spawn {|| test04_start(); }; } #debug("Finishing up."); } fn test05_start(ch: chan<int>) { send(ch, 10); send(ch, 20); send(ch, 30); send(ch, 30); send(ch, 30); } fn test05() { let po = comm::port(); let ch = chan(po); task::spawn {|| test05_start(ch); }; let value: int; value = recv(po); value = recv(po); value = recv(po); log(debug, value); } fn test06_start(&&task_number: int) { #debug("Started task."); let i: int = 0; while i < 1000000 { i = i + 1; } #debug("Finished task."); } fn test06() { let number_of_tasks: int = 4; #debug("Creating tasks"); let i: int = 0; let tasks = []; while i < number_of_tasks { i = i + 1; tasks += [task::spawn_joinable {|| test06_start(i);}]; } for t in tasks { task::join(t); } }
true
fb749d78931386c115eb5480cd7f8704068ce51d
Rust
yagince/math-puzzle-rs
/src/bin/q05.rs
UTF-8
681
3.125
3
[]
no_license
// struct Money { // amount: i32, // } // fn change(orig: i32, coins: Vec<Money>, max_count: i32) -> Vec<Money> { // if coins.len() == 0 { // return vec![]; // } // match coins.split_at(1) { // (Some(m), tail) => { // let tmp_coins = vec![head]; // if tail.len() == 0 { // return tmp_coins // } else { // change(orig - head.amount, tail, max_count - 1) // } // }, // } // } fn main() { let a: Vec<i32> = vec![1]; match a.split_first() { Some((head, tail)) => println!("{:?}, {:?}", head, tail), None => println!("hoge"), } }
true
f1b6b546f70191534e14a70c341db43e390973e4
Rust
ymtdzzz/mini-ssl-rs
/src/http.rs
UTF-8
9,159
3.28125
3
[]
no_license
use std::{ io::{BufReader, BufWriter, Read, Write}, net::TcpStream, }; use anyhow::{anyhow, Error, Result}; const HTTP_PORT: u32 = 80; #[derive(Debug, PartialEq)] pub struct ParsedUrl { pub host: String, pub path: String, } impl ParsedUrl { /// new returns a parsed url from given uri pub fn new(uri: &str) -> Option<Self> { let mut uri = uri.to_string(); if uri.chars().last()? != '/' { uri = format!("{0}{1}", uri, "/"); } let host_start_pos = uri.find("//")?.saturating_add(2); let host_and_path = &uri[host_start_pos..]; let path_start_pos = host_and_path.find("/")?.saturating_add(host_start_pos); let host = &uri[host_start_pos..path_start_pos]; let path = &uri[path_start_pos..]; Some(Self { host: String::from(host), path: String::from(path), }) } } #[derive(Debug, PartialEq)] pub struct ParsedProxyUrl { pub host: String, pub port: String, pub username: Option<String>, pub password: Option<String>, } impl ParsedProxyUrl { /// new returns a parsed proxy url from given uri /// It's forgiven not to start with 'http://' /// uri format: http://[username:password@]hostname[:port]/ pub fn new(uri: &str) -> Result<Self, Error> { let host: String; let mut port = HTTP_PORT.to_string(); let mut username: Option<String> = None; let mut password: Option<String> = None; // skipping 'http://' let protocol_pos = uri.find("http://"); let mut uri = if let Some(pos) = protocol_pos { &uri[pos.saturating_add(7)..] } else { &uri }; // login info parsing if let Some(login_info_pos) = uri.find("@") { let login_info = &uri[..login_info_pos]; let username_pos = login_info.find(":"); if username_pos.is_none() { return Err(anyhow!("Supplied login info is malformed: {}", login_info)); } let username_pos = username_pos.unwrap(); if username_pos == 0 { return Err(anyhow!("Expected username in {}", login_info)); } if login_info.len().saturating_sub(1) == username_pos { return Err(anyhow!("Expected password in {}", login_info)); } username = Some(String::from(&login_info[..username_pos])); password = Some(String::from(&login_info[username_pos.saturating_add(1)..])); uri = &uri[login_info_pos.saturating_add(1)..]; } // truncate '/' at the end of uri if let Some(slash_pos) = uri.find("/") { uri = &uri[..slash_pos]; } // port parsing if let Some(colon_pos) = uri.find(":") { if colon_pos == uri.len().saturating_sub(1) { return Err(anyhow!("Expected port: {}", uri)); } let p = &uri[colon_pos.saturating_add(1)..]; if p == "0" { return Err(anyhow!("Port 0 is invalid: {}", uri)); } host = format!("{}", &uri[..colon_pos]); port = format!("{}", p); } else { host = format!("{}", uri); } Ok(Self { host, port, username, password, }) } } pub fn http_get( tcp_stream: &TcpStream, parsed_url: &ParsedUrl, parsed_proxy_url: &Option<ParsedProxyUrl>, ) { println!("Retrieving document: '{}'", parsed_url.path); let mut reader = BufReader::new(tcp_stream); let mut writer = BufWriter::new(tcp_stream); // format HTTP request let mut header = String::new(); if let Some(proxy) = parsed_proxy_url { header = format!( "{}GET http://{}{} HTTP/1.1\r\n", header, parsed_url.host, parsed_url.path ); if let (Some(username), Some(password)) = (proxy.username.as_ref(), proxy.password.as_ref()) { let auth = base64::encode(format!("{}:{}", username, password)); header = format!("{}Proxy-Authorization: BASIC {}\r\n", header, auth); header = format!("{}Authorization: BASIC {}\r\n", header, auth); } } else { header = format!("{}GET {} HTTP/1.1\r\n", header, parsed_url.path); } let header = format!( "{}HOST: {}\r\nConnection: close\r\n\r\n", header, parsed_url.host ); println!("GET request sending..."); println!("-- Request --\n{}", header); tcp_write(&mut writer, &header); print!("{}", tcp_read(&mut reader)); } fn tcp_read(reader: &mut BufReader<&TcpStream>) -> String { let mut msg = String::new(); reader .read_to_string(&mut msg) .expect("Failed to read lines from tcp stream"); msg } fn tcp_write(writer: &mut BufWriter<&TcpStream>, msg: &str) { writer .write(msg.as_bytes()) .expect("Failed to send message to tcp stream"); writer.flush().unwrap(); } #[cfg(test)] mod tests { use super::*; #[test] fn test_can_parse_valid_uri() { let actual = ParsedUrl::new("http://www.example.com/this/is/path"); let expected = Some(ParsedUrl { host: String::from("www.example.com"), path: String::from("/this/is/path/"), }); assert_eq!(actual, expected); } #[test] fn test_can_parse_valid_uri_without_path() { let actual = ParsedUrl::new("http://www.example.com/"); let expected = Some(ParsedUrl { host: String::from("www.example.com"), path: String::from("/"), }); assert_eq!(actual, expected); let actual = ParsedUrl::new("http://www.example.com"); let expected = Some(ParsedUrl { host: String::from("www.example.com"), path: String::from("/"), }); assert_eq!(actual, expected); } #[test] fn test_can_return_none_with_invalid_uri() { let result = ParsedUrl::new("thisisinvaliduri.com"); assert!(result.is_none()); } #[test] fn test_can_parse_valid_full_proxy_uri() { let actual = ParsedProxyUrl::new("http://username:[email protected]:8888/").unwrap(); let expected = ParsedProxyUrl { host: String::from("example.com"), port: String::from("8888"), username: Some(String::from("username")), password: Some(String::from("password")), }; assert_eq!(expected, actual); } #[test] fn test_can_parse_valid_proxy_uri_without_some_part() { let actual = ParsedProxyUrl::new("username:[email protected]").unwrap(); let expected = ParsedProxyUrl { host: String::from("example.com"), port: String::from(format!("{}", HTTP_PORT)), username: Some(String::from("username")), password: Some(String::from("password")), }; assert_eq!(expected, actual); } #[test] fn test_can_return_error_username_is_not_supplied() { let actual = ParsedProxyUrl::new("http://:[email protected]:8888"); let expected_err_msg = "Expected username in"; assert!(actual.is_err(), "ParsedProxyUrl should be error"); let err_msg = format!("{}", actual.unwrap_err()); assert!( err_msg.contains(expected_err_msg), "error message should contain: {}, but actual is: {}", expected_err_msg, err_msg ); } #[test] fn test_can_return_error_password_is_not_supplied() { let actual = ParsedProxyUrl::new("http://username:@example.com:8888"); let expected_err_msg = "Expected password in"; assert!(actual.is_err(), "ParsedProxyUrl should be error"); let err_msg = format!("{}", actual.unwrap_err()); assert!( err_msg.contains(expected_err_msg), "error message should contain: {}, but actual is: {}", expected_err_msg, err_msg ); } #[test] fn test_can_return_error_port_is_not_supplied() { let actual = ParsedProxyUrl::new("http://username:[email protected]:"); let expected_err_msg = "Expected port"; assert!(actual.is_err(), "ParsedProxyUrl should be error"); let err_msg = format!("{}", actual.unwrap_err()); assert!( err_msg.contains(expected_err_msg), "error message should contain: {}, but actual is: {}", expected_err_msg, err_msg ); } #[test] fn test_can_return_error_invalid_port() { let actual = ParsedProxyUrl::new("http://username:[email protected]:0"); let expected_err_msg = "Port 0 is invalid"; assert!(actual.is_err(), "ParsedProxyUrl should be error"); let err_msg = format!("{}", actual.unwrap_err()); assert!( err_msg.contains(expected_err_msg), "error message should contain: {}, but actual is: {}", expected_err_msg, err_msg ); } }
true
e149b73cd532c73576254663b31f09eae584f37f
Rust
qinxiaoguang/rs-lc
/src/solution/l008.rs
UTF-8
2,797
3.59375
4
[]
no_license
pub struct Solution {} impl Solution { // 整数转换 // 1. 去掉前边的空格 // 2. 若第一个有效字符不是数字或者负号,则返回0 // 3. 找到前几个有效数字并转换。 #![allow(dead_code)] pub fn my_atoi(str: String) -> i32 { let mut prefix_trim = true; let mut is_neg = false; let mut always_false = false; let s = str .chars() .filter(|&c| { if always_false { return false; } if prefix_trim && c == ' ' { return false; } if c != ' ' { if c == '-' && prefix_trim { is_neg = true; prefix_trim = false; return true; } if c == '+' && prefix_trim { is_neg = false; prefix_trim = false; return true; } prefix_trim = false; if (c as i32 >= '0' as i32) && (c as i32 <= '9' as i32) { return true; } } always_false = true; return false; }) .collect::<String>(); //println!("{}", s); let v: i64; if s.len() == 0 { return 0; } if s.len() == 1 && (s == "+" || s == "-") { return 0; } if is_neg { v = s.parse::<i64>().unwrap_or(std::i32::MIN as i64); } else { v = s.parse::<i64>().unwrap_or(std::i32::MAX as i64); } if v <= (std::i32::MIN) as i64 { std::i32::MIN } else if v >= (std::i32::MAX) as i64 { std::i32::MAX } else { v as i32 } } } #[cfg(test)] mod test { use super::*; #[test] fn test_l008() { assert_eq!(42, Solution::my_atoi("42".to_string())); assert_eq!(-42, Solution::my_atoi("-42".to_string())); assert_eq!(-42, Solution::my_atoi(" -42".to_string())); assert_eq!(-42, Solution::my_atoi(" -42 a 7".to_string())); assert_eq!(4193, Solution::my_atoi("4193 with a".to_string())); assert_eq!(0, Solution::my_atoi("words and 987".to_string())); assert_eq!(-2147483648, Solution::my_atoi("-91283472332".to_string())); assert_eq!(1, Solution::my_atoi("+1".to_string())); assert_eq!(0, Solution::my_atoi("++1".to_string())); assert_eq!(1, Solution::my_atoi("1+1".to_string())); assert_eq!( 2147483647, Solution::my_atoi("20000000000000000000".to_string()) ); } }
true
cc95f614a2fa85bd8b754f553afe1c16a1a71d62
Rust
pnaranja/rustbook
/match_patterns/src/main.rs
UTF-8
4,422
4.0625
4
[]
no_license
fn main() { // Matching Name Variables let x = Some (5); let y = 10; // Some(y) will match ANY value in Some and assign it to the local y in match{} match x{ Some (50) => println! ("Should not match this"), Some (y) => println! ("Matched in inside scope y={}", y), _ => println! ("Should not match this") } println! ("After match x: x.unrapped={}, y={}", x.unwrap(), y); // Multiple Patterns match y{ 1 | 2 | 3 => println! ("Should not match this"), 4 | 20 | 10 => println! ("Matched y using 4 | 20 | 10"), _ => println! ("Should not match this"), } // Match ranges match y{ 1...9 => println! ("Should not match this"), 10...20 => println! ("Matched y using 10..20"), _ => println! ("Should not match this"), } // Destructuring Structs struct Point{ x : i32, y: i32 } let p = Point{x : 5, y: 9}; let Point{x , y} = p; println! ("Point destructed: x = {}, y = {}", x, y); match p { Point {x , y: 0} => println!("On the x axis {}", x), Point {x : 0 , y} => println!("On the y axis {}", y), Point {x , y} => println!("On neither axis {} {}", x, y), } // Destructuring Enums enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } let msg = Message::ChangeColor(0, 106, 255); match msg { Message::Quit => println!("I Quit!"), Message::Move { x, y } => println!("Move direction x: {}, y: {}", x, y), Message::Write(x) => println!("Writing string: {}", x), Message::ChangeColor(x, y, z) => println!("Changing color rgb: {}, {}, {}", x, y, z) } // Destructuring References let points = vec![ Point { x: 0, y: 0 }, Point { x: 1, y: 5 }, Point { x: 10, y: -3 }, ]; // Rust 1.27 allows Point {x,y} to not need to explicitly show reference in the iter let sum_of_squares: i32 = points.iter().map(|Point { x, y }| x * x + y * y).sum(); println!("Sum of squares of the points: {}", sum_of_squares); // Destructuring Structs and Tuples let ((feet, inches), Point { x, y }) = ((3, 10), Point { x: 3, y: 10 }); println!("Feet: {}, Inches: {}, Points x: {}, y: {}", feet, inches, x, y); // Ignore Values in a pattern let something = Some(5); let something2 = Some(10); match (something, something2) { (Some(_), Some(_)) => println!("There was SOMETHING!"), _ => println!("There was NOTHING!") } struct Point2 { x: i32, y: i32, z: i32 } let origin = Point2 { x: 1, y: 2, z: 3 }; match origin { Point2 { x, .. } => println!("Here's just x: {}", x), _ => println!("There's no Point!") } let nums = (1, 2, 3, 4, 5); match nums { (first, .., last) => println!("Here the first and last nums: {}, {}", first, last) } // Create reference patterns let robot_name = Some(String::from("Bors")); // Match the reference (&) instead, so robot_name can be printed after match &robot_name { Some(name) => println!("Found a name: {}", name), None => (), } let mut robot_name2 = Some(String::from("Cors")); println!("robot_name2 is: {:?}", robot_name2); match &mut robot_name2{ Some(name) => *name = String::from ("Boris"), None => () } println!("robot_name2 is now: {:?}", robot_name2); // Extra conditionals with Match Guards let num = Some (4); match num{ Some (x) if x > 5 => println! ("x is greater than 5"), Some (x) => println! ("x is less than or equal to 5"), None => println! ("x is nothing!") } let num2 = Some (7); match num2{ Some (3) | Some (4) |Some (5) => println! ("x is 3 to 5"), Some (6) | Some (7) |Some (8) => println! ("x is 6 to 8"), Some (_) => println! ("x is something"), None => println! ("x is nothing!") } // Bindings using @ enum Message2{ Hello {id:i32} } let msg = Message2::Hello{id : 5}; match msg{ Message2::Hello{id: id_var @ 1...4} => println! ("id is between 1-4: {}", id_var), Message2::Hello{id: id_var @ 5...7} => println! ("id is between 5-7: {}", id_var), _ => println! ("No idea what the id is") } }
true
9032b11ac7434b4cca2b3b68c8440ed7b0b9d571
Rust
ducc/RustBot
/src/main.rs
UTF-8
2,845
3.15625
3
[]
no_license
mod handler; extern crate discord; use discord::{Discord, State}; use discord::model::*; use discord::ChannelRef; use std::{env}; use handler::{Handler, Context}; const COMMAND_PREFIX: &str = "rs"; fn main() { let mut handler = Handler::new(); handler.add("help", help); handler.add("test", test); let token = env::var("DISCORD_TOKEN").expect("lol set DISCORD_TOKEN environment variable"); let discord = Discord::from_bot_token(&token).expect("couldnt login lol"); 'connect: loop { println!("connecting..."); let (mut conn, ready) = discord.connect().expect("couldn't connect lol"); let mut state = State::new(ready); println!("connected!"); 'event: loop { let event = match conn.recv_event() { Ok(event) => event, Err(err) => { println!("[ws err {:?}", err); if let discord::Error::WebSocket(..) = err { continue 'connect; } if let discord::Error::Closed(..) = err { break 'connect; } continue; } }; state.update(&event); match event { Event::MessageCreate(msg) => { on_message(&discord, &state, &handler, msg); } _ => {} } } } } fn on_message(discord: &Discord, state: &State, handler: &Handler, msg: Message) { if !msg.content.starts_with(COMMAND_PREFIX) { return; } let (server, channel) = match state.find_channel(msg.channel_id) { Some(ChannelRef::Public(server, channel)) => (server, channel), _ => { println!("channel not found"); return; } }; println!("[{} #{}] {}: {}", server.name, channel.name, msg.author.name, msg.content); let mut args: Vec<&str> = (&msg.content[COMMAND_PREFIX.len()..]).split_whitespace().collect::<Vec<&str>>(); let name = shift(&mut args).unwrap(); if let Some(cmd) = handler.commands.get(name) { let member = server.members.iter() .find(|m| m.user.id == msg.author.id) .expect("could not find member"); let ctx = Context{ discord: discord, state: state, server: server, channel: channel, member: member, message: &msg, args: &args }; cmd(ctx); } } fn shift<T>(vec: &mut Vec<T>) -> Option<T> { if !vec.is_empty() { Some(vec.remove(0)) } else { None } } fn help(ctx: Context) { let _ = ctx.reply("help me lol"); } fn test(ctx: Context) { let _ = ctx.reply(format!("ur args: {:?}", ctx.args).as_ref()); }
true
9df10d520582fce6cbbe1980abb40053072a1fde
Rust
awsdocs/aws-doc-sdk-examples
/rust_dev_preview/cross_service/photo_asset_management/src/chunked_uploader.rs
UTF-8
7,712
2.640625
3
[ "Apache-2.0", "MIT" ]
permissive
use std::io::Read; use anyhow::anyhow; use aws_sdk_dynamodb::primitives::DateTime; use aws_sdk_s3::{operation::get_object::GetObjectOutput, types::CompletedPart}; use aws_smithy_types_convert::date_time::DateTimeExt; use chrono::NaiveDateTime; use futures::TryStreamExt; use pipe::{pipe, PipeReader, PipeWriter}; use streaming_zip::{Archive, CompressionMode}; use uuid::Uuid; use crate::common::Common; // Pipe will read up to 10MB at a time. Each multipart upload will therefore also // be in the 10MB range. Multipart uploads have a maximum part count of 10,000, // so this imposes an effective limit on the size of the upload. Increasing this // limit uses more memory but allows larger files. JPEGs are typically 8MB, so this // could be tuned but generally should allow ~10,000 images. // // (Multipart uploads also have a minimum size of 5MB.) const READ_SIZE: usize = 1_048_578; // ZipUploader is a struct to manage streaming a number of files into a single zip, // that is itself streamed to an Amazon S3 object. It reads from a source bucket, to a // bucket and key for the zip. pub struct ZipUpload<'a> { part: i32, pipe: PipeReader, zip_writer: Archive<PipeWriter>, upload_parts: Vec<CompletedPart>, upload_id: String, key: String, bucket: String, source_bucket: String, s3_client: &'a aws_sdk_s3::Client, } impl<'a> std::fmt::Debug for ZipUpload<'a> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ZipUpload") .field("key", &self.key) .field("bucket", &self.bucket) .field("source_bucket", &self.source_bucket) .field("part", &self.part) .field("upload_id", &self.upload_id) .finish() } } pub struct ZipUploadBuilder<'a> { source_bucket: Option<String>, bucket: Option<String>, key: Option<String>, common: &'a Common, } impl<'a> ZipUploadBuilder<'a> { pub fn key(&mut self, key: String) -> &Self { self.key = Some(key); self } pub fn source_bucket(&mut self, bucket: String) -> &Self { self.source_bucket = Some(bucket); self } pub fn bucket(&mut self, bucket: String) -> &Self { self.bucket = Some(bucket); self } pub async fn build(self) -> Result<ZipUpload<'a>, anyhow::Error> { let s3_client = self.common.s3_client(); let part = 0; let upload_parts: Vec<CompletedPart> = Vec::new(); let pipe = pipe(); let zip_writer = Archive::new(pipe.1); let pipe = pipe.0; let key = self.key.unwrap_or_else(|| Uuid::new_v4().to_string()); let source_bucket = self .source_bucket .unwrap_or_else(|| self.common.storage_bucket().clone()); let bucket = self .bucket .unwrap_or_else(|| self.common.working_bucket().clone()); // Start the multipart upload... let upload = s3_client .create_multipart_upload() .bucket(&bucket) .key(&key) .content_type("application/zip") .send() .await?; // ... and keep its ID. let upload_id = upload .upload_id() .ok_or_else(|| anyhow!("Cannot start upload"))? .to_string(); Ok(ZipUpload { part, pipe, zip_writer, upload_parts, key, bucket, source_bucket, upload_id, s3_client, }) } } impl<'a> ZipUpload<'a> { // Start a builder for the ZipUpload. pub fn builder(common: &'a Common) -> ZipUploadBuilder { ZipUploadBuilder { key: None, bucket: None, source_bucket: None, common, } } // Read from the pipe until it has less than READ_SIZE, and write those to the // multipart upload in READ_SIZE chunks. async fn write_body_bytes(&mut self) -> Result<(), anyhow::Error> { let mut body = [0u8; READ_SIZE]; while self.pipe.read(&mut body)? > 0 { let body = Vec::from(body); let upload_part_response = self .s3_client .upload_part() .bucket(&self.bucket) .key(self.key.to_string()) .body(body.into()) .part_number(self.part) .upload_id(self.upload_id.clone()) .send() .await?; self.upload_parts.push( CompletedPart::builder() .e_tag(upload_part_response.e_tag().unwrap_or_default()) .part_number(self.part) .build(), ); self.part += 1; } Ok(()) } // Add an object to the archive. Reads the key from the source_bucket, passes it // through a new file entry in the archive, and writes the parts to the multipart // upload. pub async fn add_object(&mut self, key: String) -> Result<(), anyhow::Error> { let mut object = self.next_object(key).await?; while let Some(bytes) = object.body.try_next().await? { self.next_part(&bytes).await?; } self.finish_object().await?; Ok(()) } // Move to the next object. This starts the object download from s3, as well as a new entry // in the Zip archive. It returns the GetObjectOutput to iterate the download's body. async fn next_object(&mut self, key: String) -> Result<GetObjectOutput, anyhow::Error> { let object = self .s3_client .get_object() .bucket(&self.source_bucket) .key(&key) .send() .await?; let last_modified: NaiveDateTime = object .last_modified .unwrap_or_else(|| DateTime::from_millis(0)) .to_chrono_utc()? .naive_utc(); self.zip_writer.start_new_file( key.into_bytes(), last_modified, CompressionMode::Deflate(8), false, )?; Ok(object) } // Write one sequence of bytes through the zip_writer and upload the part. async fn next_part(&mut self, bytes: &bytes::Bytes) -> Result<(), anyhow::Error> { self.zip_writer.append_data(bytes)?; self.write_body_bytes().await?; Ok(()) } // Finish the current object and flush the part. async fn finish_object(&mut self) -> Result<(), anyhow::Error> { self.zip_writer.finish_file()?; self.write_body_bytes().await?; Ok(()) } // Finish the entire operation. Takes ownership of itself to invalidate future operations // with this uploader. pub async fn finish(mut self) -> Result<(String, String), anyhow::Error> { // Swap out the Archive so that it can get finalized (and the new empty one dropped). // Without this, zip_writer.finish takes ownership of self, and effectively ends // the method early. let mut zip_writer = Archive::new(pipe().1); std::mem::swap(&mut self.zip_writer, &mut zip_writer); zip_writer.finish()?; self.write_body_bytes().await?; let upload = self .s3_client .complete_multipart_upload() .bucket(&self.bucket) .key(&self.key) .upload_id(self.upload_id.clone()) .send() .await?; tracing::trace!(?upload, "Finished upload"); // After taking ownership of `self`, return the owned bucket and key strings. Ok((self.bucket, self.key)) } }
true
7db85a09ece656871f1cd7e4708874b19ffc67b5
Rust
TheWaWaR/simple-http-server
/src/util.rs
UTF-8
4,513
2.546875
3
[ "MIT" ]
permissive
use std::error::Error; use std::fmt; use std::io; use std::ops::Deref; use std::time::{SystemTime, UNIX_EPOCH}; use chrono::{DateTime, Local, TimeZone}; use iron::headers; use iron::status; use iron::{IronError, Response}; use percent_encoding::{utf8_percent_encode, AsciiSet}; /// https://url.spec.whatwg.org/#fragment-percent-encode-set const FRAGMENT_ENCODE_SET: &AsciiSet = &percent_encoding::CONTROLS .add(b' ') .add(b'"') .add(b'<') .add(b'>') .add(b'`'); /// https://url.spec.whatwg.org/#path-percent-encode-set const PATH_ENCODE_SET: &AsciiSet = &FRAGMENT_ENCODE_SET.add(b'#').add(b'?').add(b'{').add(b'}'); const PATH_SEGMENT_ENCODE_SET: &AsciiSet = &PATH_ENCODE_SET.add(b'/').add(b'%'); pub const ROOT_LINK: &str = r#"<a href="/"><strong>[Root]</strong></a>"#; #[derive(Debug)] pub struct StringError(pub String); impl fmt::Display for StringError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } impl Error for StringError { fn description(&self) -> &str { &self.0 } } impl Deref for StringError { type Target = str; fn deref(&self) -> &Self::Target { &*self.0 } } pub fn enable_string(value: bool) -> String { (if value { "enabled" } else { "disabled" }).to_owned() } pub fn encode_link_path(path: &[String]) -> String { path.iter() .map(|s| utf8_percent_encode(s, PATH_SEGMENT_ENCODE_SET).to_string()) .collect::<Vec<String>>() .join("/") } pub fn error_io2iron(err: io::Error) -> IronError { let status = match err.kind() { io::ErrorKind::PermissionDenied => status::Forbidden, io::ErrorKind::NotFound => status::NotFound, _ => status::InternalServerError, }; IronError::new(err, status) } /* TODO: may not used use iron::headers::{Range, ByteRangeSpec}; #[allow(dead_code)] pub fn parse_range(ranges: &Vec<ByteRangeSpec>, total: u64) -> Result<Option<(u64, u64)>, IronError> { if let Some(range) = ranges.get(0) { let (offset, length) = match range { &ByteRangeSpec::FromTo(x, mut y) => { // "x-y" if x >= total || x > y { return Err(IronError::new( StringError(format!("Invalid range(x={}, y={})", x, y)), status::RangeNotSatisfiable )); } if y >= total { y = total - 1; } (x, y - x + 1) } &ByteRangeSpec::AllFrom(x) => { // "x-" if x >= total { return Err(IronError::new( StringError(format!( "Range::AllFrom to large (x={}), Content-Length: {})", x, total)), status::RangeNotSatisfiable )); } (x, total - x) } &ByteRangeSpec::Last(mut x) => { // "-x" if x > total { x = total; } (total - x, x) } }; Ok(Some((offset, length))) } else { return Err(IronError::new( StringError("Empty range set".to_owned()), status::RangeNotSatisfiable )); } } */ pub fn now_string() -> String { Local::now().format("%Y-%m-%d %H:%M:%S").to_string() } pub fn system_time_to_date_time(t: SystemTime) -> DateTime<Local> { let (sec, nsec) = match t.duration_since(UNIX_EPOCH) { Ok(dur) => (dur.as_secs() as i64, dur.subsec_nanos()), Err(e) => { // unlikely but should be handled let dur = e.duration(); let (sec, nsec) = (dur.as_secs() as i64, dur.subsec_nanos()); if nsec == 0 { (-sec, 0) } else { (-sec - 1, 1_000_000_000 - nsec) } } }; Local.timestamp(sec, nsec) } pub fn error_resp(s: status::Status, msg: &str) -> Response { let mut resp = Response::with(( s, format!( r#"<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> {root_link} <hr /> <div>[<strong style=color:red;>ERROR {code}</strong>]: {msg}</div> </body> </html> "#, root_link = ROOT_LINK, code = s.to_u16(), msg = msg ), )); resp.headers.set(headers::ContentType::html()); resp }
true
819704e6173ae6b4ae33a8c6260086c26682f477
Rust
dansoper/adventofcode
/2021/day24/src/main.rs
UTF-8
1,990
3.265625
3
[]
no_license
use derive_new::new; const DATA: &str = include_str!("input.txt"); // WOW I need to get to know what this does! // Credit: https://github.com/Crazytieguy/advent-2021/blob/master/src/bin/day24/main.rs // I got my answer, and the plan was to try and understand it, but then I ran out of time fn main() { println!("part a: {}", part_a(DATA)); println!("part b: {}", part_b(DATA)); } #[derive(Debug, Clone, Copy)] struct StepParams { do_cmp: bool, cmp_now: i8, cmp_later: i8, } #[allow(clippy::needless_range_loop)] fn parse(data: &'static str) -> [StepParams; 14] { let lines: Vec<_> = data.lines().collect(); let mut params = [None; 14]; let get_param = |line_id: usize| lines[line_id].rsplit_once(' ').unwrap().1.parse().unwrap(); for i in 0..14 { params[i] = Some(StepParams { do_cmp: get_param(i * 18 + 4) == 26, cmp_now: get_param(i * 18 + 5), cmp_later: get_param(i * 18 + 15), }) } params.map(Option::unwrap) } #[derive(Debug, new, Clone, Copy)] struct Rule { cmp_to: usize, val: i8, } fn get_rules(params: [StepParams; 14]) -> [Rule; 14] { let mut cmp_stack = Vec::new(); let mut rules = [None; 14]; for (i, step_params) in params.iter().enumerate() { if step_params.do_cmp { let Rule { cmp_to, val } = cmp_stack.pop().unwrap(); rules[i] = Some(Rule::new(cmp_to, val + step_params.cmp_now)); rules[cmp_to] = Some(Rule::new(i, -val - step_params.cmp_now)); } else { cmp_stack.push(Rule::new(i, step_params.cmp_later)) } } rules.map(Option::unwrap) } fn part_a(data: &'static str) -> String { let params = parse(data); let rules = get_rules(params); rules.map(|r| 9.min(9 + r.val).to_string()).concat() } fn part_b(data: &'static str) -> String { let params = parse(data); let rules = get_rules(params); rules.map(|r| 1.max(1 + r.val).to_string()).concat() }
true
3a7abda85426083b2a64cd438ee19eb541fe6b4d
Rust
nymtech/nym
/common/bin-common/src/version_checker/mod.rs
UTF-8
2,435
2.84375
3
[ "CC0-1.0", "Apache-2.0" ]
permissive
// Copyright 2021 - Nym Technologies SA <[email protected]> // SPDX-License-Identifier: Apache-2.0 use semver::SemVerError; pub use semver::Version; /// Checks whether given `version` is compatible with a given semantic version requirement `req` /// according to major-minor semver rules. The semantic version requirement can be passed as a full, /// concrete version number, because that's what we'll have in our Cargo.toml files (e.g. 0.3.2). /// The patch number in the requirement gets dropped and replaced with a wildcard (0.3.*) as all /// minor versions should be compatible with each other. pub fn is_minor_version_compatible(version: &str, req: &str) -> bool { let expected_version = match Version::parse(version) { Ok(v) => v, Err(_) => return false, }; let req_version = match Version::parse(req) { Ok(v) => v, Err(_) => return false, }; expected_version.major == req_version.major && expected_version.minor == req_version.minor } pub fn parse_version(raw_version: &str) -> Result<Version, SemVerError> { Version::parse(raw_version) } #[cfg(test)] mod tests { use super::*; #[test] fn version_0_3_0_is_compatible_with_requirement_0_3_x() { assert!(is_minor_version_compatible("0.3.0", "0.3.2")); } #[test] fn version_0_3_1_is_compatible_with_minimum_requirement_0_3_x() { assert!(is_minor_version_compatible("0.3.1", "0.3.2")); } #[test] fn version_0_3_2_is_compatible_with_minimum_requirement_0_3_x() { assert!(is_minor_version_compatible("0.3.2", "0.3.0")); } #[test] fn version_0_2_0_is_not_compatible_with_requirement_0_3_x() { assert!(!is_minor_version_compatible("0.2.0", "0.3.2")); } #[test] fn version_0_4_0_is_not_compatible_with_requirement_0_3_x() { assert!(!is_minor_version_compatible("0.4.0", "0.3.2")); } #[test] fn version_1_3_2_is_not_compatible_with_requirement_0_3_x() { assert!(!is_minor_version_compatible("1.3.2", "0.3.2")); } #[test] fn version_0_4_0_rc_1_is_compatible_with_version_0_4_0_rc_1() { assert!(is_minor_version_compatible("0.4.0-rc.1", "0.4.0-rc.1")); } #[test] fn returns_false_on_foo_version() { assert!(!is_minor_version_compatible("foo", "0.3.2")); } #[test] fn returns_false_on_bar_version() { assert!(!is_minor_version_compatible("0.3.2", "bar")); } }
true
b7b38b4a0ce376f633701c711996102dc82d7acd
Rust
Robbe7730/MCRust
/src/server/entity.rs
UTF-8
442
3.125
3
[]
no_license
use crate::player::Player; use crate::error_type::ErrorType; #[derive(Clone)] pub enum Entity { PlayerEntity(Player), } impl Entity { pub fn as_player(&self) -> Result<&Player, ErrorType> { match self { Entity::PlayerEntity(p) => Ok(p), } } pub fn as_player_mut(&mut self) -> Result<&mut Player, ErrorType> { match self { Entity::PlayerEntity(p) => Ok(p), } } }
true
b4b9db9178604f55632ef7613060f5664fe56d1c
Rust
Ale0x78/rust-minecraft-proxy
/src/config.rs
UTF-8
2,828
3
3
[ "MIT" ]
permissive
use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::default::Default; use std::fs; use std::path::Path; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct MOTD { text: String, protocol_name: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Server { pub(crate) ip: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct UnknownHost { kick_message: String, motd: MOTD } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Config { listen_addr: String, unknown_host: UnknownHost, hosts: BTreeMap<String, Server> } impl Default for Config { fn default() -> Self { let unknown_host = UnknownHost { kick_message: "§bRust Minecraft Proxy\n\n§cInvalid Address".to_string(), motd: MOTD { text: "§cUnknown host!\n§7Please use a valid address to connect.".to_string(), protocol_name: "§crust-minecraft-proxy".to_string() } }; let mut hosts: BTreeMap<String, Server> = BTreeMap::new(); hosts.insert("hub.example.com".to_string(), Server { ip: "127.0.0.1:35560".to_string() }); hosts.insert("minigame.example.com".to_string(), Server { ip: "127.0.0.1:25561".to_string() }); Self { listen_addr: "0.0.0.0:25565".to_string(), unknown_host, hosts } } } impl Config { pub fn load_or_init(path: &Path) -> Config { if path.exists() { serde_yaml::from_str(&fs::read_to_string(path).unwrap()).unwrap() } else { info!("Configuration file does not exist. Use defaults."); let default = Config::default(); trace!("Default configuration: {:?}", default); let string = serde_yaml::to_string(&default).unwrap(); fs::write(path, &string).unwrap(); default } } pub fn get_unknown_host_kick_msg(&self) -> String { let mut message: String = "{\"text\":\"".to_owned(); message.push_str(&self.unknown_host.kick_message); message.push_str("\"}"); message } pub fn get_unknown_host_motd(&self) -> String { let mut motd: String = "{\"version\": {\"name\": \"".to_owned(); motd.push_str(&self.unknown_host.motd.protocol_name); motd.push_str("\", \"protocol\": -1 }, \"players\": {\"max\": 0, \"online\": 0, \"sample\": [] }, \"description\": { \"text\": \""); motd.push_str(&self.unknown_host.motd.text); motd.push_str("\" }}"); motd } pub fn get_listen_addr(&self) -> &str { &self.listen_addr } pub fn get_hosts(&self) -> &BTreeMap<String, Server> { &self.hosts } pub fn get_addr_by_host(&self, host: &str) -> Option<&Server> { self.hosts.get(host) } }
true
4414fd05d1601c2fffc98389983f15eea08d0773
Rust
Krishnacore/move-tools
/lang/decompiler/src/types.rs
UTF-8
4,911
2.84375
3
[ "MIT" ]
permissive
use crate::generics::Generic; use crate::Encode; use std::fmt::Write; use anyhow::Error; use crate::imports::{Import, Imports}; use move_binary_format::file_format::*; use crate::unit::UnitAccess; /// Extract type signature. pub fn extract_type_signature<'a>( unit: &'a impl UnitAccess, signature: &'a SignatureToken, imports: &'a Imports, type_params: &[Generic], ) -> FType<'a> { match signature { SignatureToken::U8 => FType::Primitive("u8"), SignatureToken::Bool => FType::Primitive("bool"), SignatureToken::U64 => FType::Primitive("u64"), SignatureToken::U128 => FType::Primitive("u128"), SignatureToken::Address => FType::Primitive("address"), SignatureToken::Signer => FType::Primitive("signer"), SignatureToken::Vector(sign) => FType::Vec(Box::new(extract_type_signature( unit, sign.as_ref(), imports, type_params, ))), SignatureToken::Struct(struct_index) => { FType::Struct(extract_struct_name(unit, struct_index, imports)) } SignatureToken::StructInstantiation(struct_index, typed) => FType::StructInst( extract_struct_name(unit, struct_index, imports), typed .iter() .map(|t| extract_type_signature(unit, t, imports, type_params)) .collect::<Vec<_>>(), ), SignatureToken::Reference(sign) => FType::Ref(Box::new(extract_type_signature( unit, sign.as_ref(), imports, type_params, ))), SignatureToken::MutableReference(sign) => FType::RefMut(Box::new( extract_type_signature(unit, sign.as_ref(), imports, type_params), )), SignatureToken::TypeParameter(index) => { FType::Generic(type_params[*index as usize].clone()) } } } /// Extract struct name. pub fn extract_struct_name<'a>( unit: &'a impl UnitAccess, struct_index: &'a StructHandleIndex, imports: &'a Imports, ) -> FullStructName<'a> { let handler = unit.struct_handle(*struct_index); let module_handler = unit.module_handle(handler.module); let module_name = unit.identifier(module_handler.name); let address = unit.address(module_handler.address); let type_name = unit.identifier(handler.name); imports .get_import(address, module_name) .map(|import| FullStructName { name: type_name, import: Some(import), }) .unwrap_or_else(|| FullStructName { name: type_name, import: None, }) } /// Type. #[derive(Debug)] pub enum FType<'a> { /// Generic type. Generic(Generic), /// Primitive type. Primitive(&'static str), /// Reference type. Ref(Box<FType<'a>>), /// Mutable reference type. RefMut(Box<FType<'a>>), /// Vector type. Vec(Box<FType<'a>>), /// Struct type. Struct(FullStructName<'a>), /// Struct instantiation instance. StructInst(FullStructName<'a>, Vec<FType<'a>>), } impl<'a> Encode for FType<'a> { fn encode<W: Write>(&self, w: &mut W, indent: usize) -> Result<(), Error> { match self { FType::Primitive(name) => { w.write_str(name)?; } FType::Generic(type_param) => { type_param.as_name().encode(w, indent)?; } FType::Ref(t) => { w.write_str("&")?; t.encode(w, indent)?; } FType::RefMut(t) => { w.write_str("&mut ")?; t.encode(w, indent)?; } FType::Vec(t) => { w.write_str("vector<")?; t.encode(w, indent)?; w.write_str(">")?; } FType::Struct(name) => { name.encode(w, indent)?; } FType::StructInst(name, generics) => { name.encode(w, indent)?; if !generics.is_empty() { write!(w, "<")?; for (index, generic) in generics.iter().enumerate() { generic.encode(w, 0)?; if index != generics.len() - 1 { w.write_str(", ")?; } } write!(w, ">")?; } } } Ok(()) } } /// Full structure name. #[derive(Debug)] pub struct FullStructName<'a> { name: &'a str, import: Option<Import<'a>>, } impl<'a> Encode for FullStructName<'a> { fn encode<W: Write>(&self, w: &mut W, indent: usize) -> Result<(), Error> { if let Some(import) = &self.import { import.encode(w, indent)?; w.write_str("::")?; } w.write_str(self.name)?; Ok(()) } }
true