Rust正则表达式实践

正则表达式是一种强大的文本处理工具。在 Rust 中,我们主要通过 regex crate 来使用正则表达式。让我们通过实际案例来学习。 1. 基础匹配 use regex::Regex; fn main() { // 创建正则表达式对象 let re = Regex::new(r"\d+").unwrap(); // 测试匹配 let text = "The year is 2024"; if re.is_match(text) { println!("Found a number!"); } // 提取匹配内容 if let Some(matched) = re.find(text) { println!("Found number: {}", matched.as_str()); } } 2. 处理重复单词 根据文章中提到的一个常见问题 - 查找重复单词: use regex::Regex; fn remove_duplicate_words(text: &str) -> String { // (\w+) 捕获一个单词,\s+匹配空白字符,\1 回引用前面捕获的单词 let re = Regex::new(r"(\w+)\s+\1").unwrap(); re.replace_all(text, "$1").to_string() } fn main() { let text = "the little cat cat in the hat hat."; let result = remove_duplicate_words(text); println!("Original: {}", text); println!("Fixed: {}", result); } 3. 使用断言优化匹配 use regex::Regex; fn find_word_boundaries() { // \b 表示单词边界 let re = Regex::new(r"\b\w+\b").unwrap(); let text = "hello, world!"; for word in re.find_iter(text) { println!("Found word: {}", word.as_str()); } } 4. 性能优化 使用 lazy_static 预编译正则表达式: ...

2024-11-26 · 3 分钟 · czyt

一些任天堂switch资源

最近整了个硬破的Switch,整理了下相关资源方便查找。 固件和系统 软破 新版本都是硬破了 TegraRCM: https://github.com/eliboa/TegraRcmGUI/releases 大气层 设备需要硬破 大气层系统 https://github.com/Atmosphere-NX/Atmosphere ak大气层整合包 https://github.com/AK478BB/AK-Atmosphere/releases 大气层集成sys-patch插件破解包 https://github.com/laila509/Atmosphere-syspatch Hekate引导: https://github.com/CTCaer/hekate/releases Switch固件 模拟器固件和key https://prodkeys.net/ Ryujinx 模拟器 Retroarch Switch官方固件分享下载 https://github.com/THZoria/NX_Firmware/ 其他 Check If Your Switch Is Patched: https://ismyswitchpatched.com/ Sig Patches: https://sigmapatches.su https://rentry.org/EristaEmuNAND Sig Patches: https://gbatemp.net/threads/sigpatches-for-atmosphere-hekate-fss0-fusee-package3.571543/ EaseUs Partition: https://www.easeus.com/partition-manager/epm-free.html switch主题 https://themezer.net 游戏下载 网盘资源 switch游戏下载 https://www.123pan.com/s/sl82jv-6JVV3.html 网站或论坛 悠游任天堂 2cyshare Switch520 rutracker的switch板块 上游世界 nsw2u Game中文网 switch主题 相关文章及博客 Switch 软破、硬破总结 ...

2024-11-20 · 1 分钟 · czyt

Connect Rpc快速上手

入门 ConnectRPC(原 Connect)是一组用于构建浏览器和 gRPC 兼容 HTTP API 的库:编写简短的 Protocol Buffer schema 并实现业务逻辑,Connect 会生成代码来处理序列化、路由、压缩和内容协商,并为所有受支持的语言生成惯用、类型安全的客户端。在 Go 中,Connect 只有一个包(connect-go),短到可以一个下午读完。 多协议支持 Connect 服务器和客户端支持三种协议: gRPC:完全支持,包括流式、trailers 和错误详情。任何语言的 gRPC 客户端都可以调用 Connect 服务器,Connect 客户端也可以调用任何 gRPC 服务器(官方用扩展版的 Google 互操作性测试验证兼容性) gRPC-Web:直接支持,无需依赖 Envoy 之类的转换代理 Connect 协议:基于 HTTP 的简单协议,可运行在 HTTP/1.1、HTTP/2 和 HTTP/3 上,默认同时支持 JSON 和二进制 Protobuf 编码 服务器默认接受全部三种协议的入口;客户端默认使用 Connect 协议,通过配置即可切换到 gRPC 或 gRPC-Web,无需修改其他代码。错误、header、trailer 和流式 API 都是协议无关的。 可以用 cURL 直接体验官方 demo 服务(Eliza 聊天机器人): curl \ --header "Content-Type: application/json" \ --data '{"sentence": "I feel happy."}' \ https://demo.connectrpc.com/connectrpc.eliza.v1.ElizaService/Say 压缩和序列化 Connect 支持多种压缩和序列化选项,协议层支持 identity、gzip、br、zstd 四种 Content-Encoding。默认情况下,Connect 处理程序使用标准库的 compress/gzip 提供 gzip 压缩。Connect 客户端默认发送未压缩的请求并请求 gzip 压缩的响应。如果您知道服务器支持 gzip,则还可以在客户端构建期间使用 WithSendGzip 选项来压缩请求。 ...

2024-11-06 · 4 分钟 · czyt

Go Ble开发实战

⚠️代码仅最后部分进行了测试,前面的暂未测试 1. 简介 BLE (Bluetooth Low Energy) 是一种低功耗蓝牙技术。Go-BLE 是 Go 语言的 BLE 库,提供了简单易用的 API 来开发 BLE 应用。本文将通过一个完整的示例来展示如何使用 Go-BLE 创建一个蓝牙服务器。 Go-BLE 主要支持 Linux 和 macOS 平台(1 ),但需要注意 macOS 部分目前并未被积极维护。 2. 环境准备 2.1 安装依赖 # 安装 go-ble go get -u github.com/go-ble/ble # 安装设备支持库 go get -u github.com/go-ble/ble/examples/lib/dev # Linux系统需要设置权限 sudo setcap 'cap_net_raw,cap_net_admin+eip' ./your_program 3. BLE基础概念 3.1 核心概念 Peripheral (外围设备):提供服务的设备 Central (中心设备):连接外围设备的设备(如手机) Service (服务):功能的集合 Characteristic (特征):具体的数据点 Descriptor (描述符):特征的元数据 3.2 常见的 UUID 标准服务 UUID: 电池服务:0x180F 设备信息服务:0x180A 心率务:0x180D 标准特征 UUID: 电池电量:0x2A19 设备名称:0x2A00 制造商名称:0x2A29 型号名称:0x2A24 序列号:0x2A25 固件版本:0x2A26 信号强度:0x2A1C 自定义 UUID 生成: // 使用在线工具生成 UUID v4 svcUUID := ble.MustParse("19B10000-E8F2-537E-4F6C-D104768A1214") 3.3 设备类型 BLE 设备类型通过 GAP (Generic Access Profile) 广播数据中的 Flags 字段指定: ...

2024-11-02 · 15 分钟 · czyt

使用 Suture在Go中实现可靠的监督树

简介 在构建复杂的分布式系统时,我们常常需要面对各种意外情况,如服务崩溃、网络中断等。为了提高系统的可靠性和容错能力,监督树模式应运而生。Suture 是一个受 Erlang OTP 框架启发的 Go 语言监督树库,它为 Go 开发者提供了一种优雅的方式来管理和监控长时间运行的服务。 监督树的核心思想是将系统组织成一个树状结构,其中父节点(监督者)负责监控和管理子节点(工作者)。当子节点发生故障时,父节点可以根据预定策略进行重启或其他恢复操作,从而提高系统的整体稳定性。 Suture 的核心概念 Suture 的设计围绕以下几个核心概念: Service 接口: 定义了可被监督的服务应该实现的方法。 Supervisor 结构体: 代表一个监督者,负责管理一组服务。 重启策略: 定义了当服务失败时,监督者应该如何响应。 安装和基本使用 首先,通过以下命令安装 Suture: go get github.com/thejerf/suture/v4 然后,在你的 Go 代码中导入 Suture: import "github.com/thejerf/suture/v4" 创建一个简单的 Service: type MyService struct{} var _ suture.Service = (*MyService)(nil) func (s *MyService) Serve(ctx context.Context) error { for { select { case <-ctx.Done(): return nil default: // 执行服务逻辑 time.Sleep(time.Second) fmt.Println("Service is running") } } } 设置 Supervisor 并添加 Service: ...

2024-10-25 · 4 分钟 · czyt

rust中map_error的用法

Rust中的map_err方法是Result类型的一个方法,用于转换错误类型。它允许你在保持Ok值不变的情况下,修改Err值。这在错误处理和类型转换中非常有用。 以下是map_err的详细用法和一些例子: 基本用法 fn main() -> Result<(), String> { let result: Result<i32, &str> = Err("原始错误"); let mapped = result.map_err(|e| e.to_string()); mapped } 在这个例子中,我们将&str类型的错误转换为String类型。 链式调用 use std::num::ParseIntError; fn parse_and_multiply(s: &str) -> Result<i32, String> { s.parse::<i32>() .map_err(|e: ParseIntError| e.to_string()) .map(|n| n * 2) } fn main() { match parse_and_multiply("10") { Ok(n) => println!("结果: {}", n), Err(e) => println!("错误: {}", e), } match parse_and_multiply("abc") { Ok(n) => println!("结果: {}", n), Err(e) => println!("错误: {}", e), } } 这个例子展示了如何在解析字符串并进行计算的过程中使用map_err转换错误类型。 ...

2024-09-10 · 2 分钟 · czyt

Rust derive_builder快速使用参考

derive_builder是 简化Rust结构体构建的强大工具,本文使用claude 3.5 生成 1. 引言 在Rust编程中,创建复杂的结构体实例常常需要大量的样板代码。derive_builder 是一个强大的过程宏库,它可以自动为结构体生成 builder 模式的实现,大大简化了结构体的创建过程。本文将深入介绍 derive_builder 的使用方法、特性和最佳实践。 2. 基本用法 2.1 安装 首先,在你的 Cargo.toml 文件中添加 derive_builder 依赖: [dependencies] derive_builder = "0.20.0" 2.2 简单示例 让我们从一个简单的例子开始: use derive_builder::Builder; #[derive(Builder, Debug)] struct Server { host: String, port: u16, } fn main() { let server = ServerBuilder::default() .host("localhost".to_string()) .port(8080) .build() .unwrap(); println!("{:?}", server); } 在这个例子中,我们为 Server 结构体派生了 Builder 特征。这会自动生成一个 ServerBuilder 结构体,它提供了流畅的 API 来构建 Server 实例。 ...

2024-09-05 · 4 分钟 · czyt

Rust serde_with快速参考

serde_with 是 Rust 中 serde 序列化/反序列化库的一个扩展,提供了许多有用的自定义序列化和反序列化方法。以下是一些常用的功能和适用场景: 字符串格式化 use serde_with::rust::display_fromstr; #[derive(Serialize, Deserialize)] struct Foo { #[serde_with(as = "display_fromstr")] bar: u32, } 适用于需要将数字类型序列化为字符串的场景。 时间格式化 use serde_with::chrono::datetime_utc_ts_seconds_from_any; #[derive(Serialize, Deserialize)] struct Foo { #[serde_with(as = "datetime_utc_ts_seconds_from_any")] time: DateTime<Utc>, } 适用于需要自定义时间格式的场景。 枚举字符串表示 use serde_with::{serde_as, DisplayFromStr}; #[serde_as] #[derive(Serialize, Deserialize)] struct Foo { #[serde_as(as = "DisplayFromStr")] bar: MyEnum, } 适用于将枚举序列化为字符串的场景。 跳过序列化默认值 use serde_with::skip_serializing_none; #[skip_serializing_none] #[derive(Serialize)] struct Foo { bar: Option<String>, } 适用于需要在序列化时忽略 None 值的场景。 ...

2024-09-01 · 1 分钟 · czyt

在rust中使用protobuf

常规方式 安装必要工具 # 安装 protoc # 在 macOS 上: brew install protobuf # 在 Ubuntu 上: sudo apt-get install protobuf-compiler # 安装 Rust protobuf 代码生成器 cargo install protobuf-codegen 示例 创建一个protobuf的文件: message.proto syntax = "proto3"; package mypackage; message Person { string name = 1; int32 age = 2; string email = 3; } 然后执行命令 protoc --rust_out=. message.proto 如果是在项目中,在你的 Rust 项目中,添加必要的依赖到 Cargo.toml: [dependencies] protobuf = "2.27.1" 然后可以在代码中访问生成的内容 use protobuf::Message; mod message; // 引入生成的模块 use message::Person; fn main() { let mut person = Person::new(); person.set_name("Alice".to_string()); person.set_age(30); person.set_email("alice@example.com".to_string()); // 序列化 let encoded: Vec<u8> = person.write_to_bytes().unwrap(); // 反序列化 let decoded = Person::parse_from_bytes(&encoded).unwrap(); println!("Name: {}", decoded.get_name()); println!("Age: {}", decoded.get_age()); println!("Email: {}", decoded.get_email()); } 可以借助build.rs来自动化这一步骤: ...

2024-08-29 · 2 分钟 · czyt

在go中使用Connect rpc

准备 参考 https://zenn.dev/7oh/articles/3b944f9b744932

2024-08-28 · 1 分钟 · czyt