惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News and Events Feed by Topic
GbyAI
GbyAI
博客园 - Franky
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
Google DeepMind News
Google DeepMind News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
InfoQ
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
F
Full Disclosure
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
博客园 - 【当耐特】
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Project Zero
Project Zero
量子位
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
美团技术团队
Attack and Defense Labs
Attack and Defense Labs
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
P
Proofpoint News Feed
Schneier on Security
Schneier on Security
Spread Privacy
Spread Privacy
S
SegmentFault 最新的问题
L
LINUX DO - 最新话题
Simon Willison's Weblog
Simon Willison's Weblog
爱范儿
爱范儿
博客园 - 聂微东
A
About on SuperTechFans
PCI Perspectives
PCI Perspectives
D
Docker

oida.dev | TypeScript, Rust

TypeScript's `erasableSyntaxOnly` Flag Unsafe for work Tokio: Macros Tokio: Channels Tokio: Getting Started Network Applications on the Tokio Stack Remake, Remodel, Reduce. The `never` type and error handling in TypeScript 5 Inconvenient Truths about TypeScript Refactoring in Rust: Introducing Traits Refactoring in Rust: Abstraction with the Newtype Pattern Announcing the TypeScript Cookbook TypeScript: Iterating over objects The road to universal JavaScript 10 years of oida.dev The TypeScript converging point How not to learn TypeScript Getting started with Rust Introducing Slides and Coverage TypeScript: The humble function overload TypeScript + React: Children types are broken TypeScript: In defense of any Rust: Enums to wrap multiple errors Dissecting Deno Error handling in Rust TypeScript: Unexpected intersections Upgrading Node.js dependencies after a yarn audit TypeScript: Array.includes on narrow types TypeScript + React: Typing Generic forwardRefs shared, util, core: Schroedinger's module names Learning Rust and Go TypeScript: Narrow types in catch clauses TypeScript: Low maintenance types Tidy TypeScript: Name your generics Tidy TypeScript: Avoid traditional OOP patterns Tidy TypeScript: Prefer type aliases over interfaces Tidy TypeScript: Prefer union types over enums My new book: TypeScript in 50 Lessons Go Preact! ❤️ this in JavaScript and TypeScript TypeScript and ECMAScript Modules TypeScript + React: Why I don't use React.FC TypeScript + React: Component patterns TypeScript: Augmenting global and lib.dom.d.ts Vite with Preact and TypeScript TypeScript: Union to intersection type 11ty: Generate Twitter cards automatically Are large node module dependencies an issue? TypeScript: Variadic Tuple Types Preview TypeScript: Improving Object.keys Remake, Remodel. Part 4. TypeScript + React: Typing custom hooks with tuple types TypeScript: Assertion signatures and Object.defineProperty TypeScript: Check for object properties and narrow down type Boolean in JavaScript and TypeScript void in JavaScript and TypeScript Symbols in JavaScript and TypeScript Why I use TypeScript TypeScript + React: Extending JSX Elements TypeScript: Validate mapped types and const context TypeScript: Match the exact object shape TypeScript: The constructor interface pattern Streaming your Meetup - Part 4: Directing and Streaming with OBS Streaming your Meetup - Part 3: Speaker audio Streaming your Meetup - Part 2: Speaker video Streaming your Meetup - Part 1: Basics and Projector TypeScript and React Guide: Added a new styles chapter TypeScript and React Guide: Added a new render props chapter TypeScript and React: Styles and CSS TypeScript and React TypeScript and React Guide: Added a new prop types chapter TypeScript without TypeScript -- JSDoc superpowers TypeScript: Mapped types for type maps JAMStack vs serverless web apps The Unsung Benefits of JAMStack Sites TypeScript: Ambient modules for Webpack loaders My most favourite talks in 2018 TypeScript and React Guide: Added a new context chapter TypeScript: Built-in generic types TypeScript: Type predicates JSX is syntactic sugar TypeScript and React Guide: Added a new hooks chapter Getting your CfP application right FAQ on our Angular Connect Talk: Automating UI development TypeScript and Substitutability Debugging Node.js apps in TypeScript with Visual Studio Code From Medium: Deconfusing Pre- and Post-processing From Medium: PostCSS misconceptions Saving and scraping a website with Puppeteer Cutting the mustard - 2018 edition Wordpress as CMS for your JAMStack sites My most favourite podcast episodes in 2017 My most favourite talks in 2017 My most favourite books in 2017 The Best Request Is No Request, Revisited Not so hidden figures - Organizing ScriptConf My podcast journey to ScriptCast Grid layout, grid layout everywhere! #scriptconf and #devone Object streams in Node.js
Rust: Tiny little traits
2022-04-15 · via oida.dev | TypeScript, Rust

Rust’s trait system has a feature that is often talked about, but which I don’t see used that often in application code: Implementing your traits for types that are not yours. You can see this a lot in the standard library, and also in some libraries (hello itertools), but I see developers shy away from doing that when writing applications. It’s so much fun and so useful, though!

I’ve started defining and implementing traits for other types a lot more and I have the feeling that my code has become a lot clearer and more intentional. Let’s see what I did.

One-liner traits #

I was tasked to write a DNS resolver that blocks HTTP calls to localhost. Since I build upon hyper (as you all should), I implemented a Tower service that serves as a middleware. In this middleware, I do the actual check for resolved IP addresses:

let addr = req.as_str();
let addr = (addr, 0).to_socket_addrs();

if let Ok(addresses) = addr {
for a in addresses {
if a.ip().eq(&Ipv4Addr::new(127, 0, 0, 1)) {
return Box::pin(async { Err(io::Error::from(ErrorKind::Other)) });
}
}
}

It’s not bad, but there’s room for potential confusion, and it’s mostly in the conditional:

  • We might want to check for more IPs that could resolve to localhost, e.g. the IP 0.0.0.0. to_socket_addr might not resolve to 0.0.0.0, but the same piece of code might end up at some other place where this might be troublesome.
  • Maybe we want to exclude other IPs as well which aren’t localhost. This conditional would be ambiguous.
  • We forgot that an IP v6 address exists 🫢

So, while it’s fine, I want to have something where I’m more prepared for things in the future.

I create an IsLocalhost trait. It defines one function is_localhost that takes a reference of itself and returns a bool.

pub(crate) trait IsLocalhost {
fn is_localhost(&self) -> bool;
}

In Rust’s std::net, there are exactly two structs where you can directly check if the IP addresses are localhost or not. The Ipv4Addr and Ipv6Addr structs.

impl IsLocalhost for Ipv4Addr {
fn is_localhost(&self) -> bool {
Ipv4Addr::new(127, 0, 0, 1).eq(self) || Ipv4Addr::new(0, 0, 0, 0).eq(self)
}
}

impl IsLocalhost for Ipv6Addr {
fn is_localhost(&self) -> bool {
Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).eq(self)
}
}

Checking if an IP is localhost happens exactly where the IP is defined. std::net has an enum IpAddr to distinguish between V4, and V6. Let’s implement IsLocalhost for IpAddr as well.

impl IsLocalhost for IpAddr {
fn is_localhost(&self) -> bool {
match self {
IpAddr::V4(ref a) => a.is_localhost(),
IpAddr::V6(ref a) => a.is_localhost(),
}
}
}

With the enum, we’re making sure that we don’t forget about V6 IP addresses. Phew. On to SocketAddr, the original struct we get from to_socket_addr. Let’s implement IsLocalhost for that as well.

impl IsLocalhost for SocketAddr {
fn is_localhost(&self) -> bool {
self.ip().is_localhost()
}
}

Great! Turtles all the way down. And it doesn’t matter which struct we’re dealing with. We can check for localhost everywhere.

When calling to_socket_addr we’re not getting a SocketAddr directly, but rather an IntoIter<SocketAddr>, going down the entire route of IP addresses until we reach the actual server. We want to check if any of those is_localhost, so we see if the collection we get from the iterator has localhost. Another trait!

pub(crate) trait HasLocalhost {
fn has_localhost(&mut self) -> bool;
}

impl HasLocalhost for IntoIter<SocketAddr> {
fn has_localhost(&mut self) -> bool {
self.any(|el| el.is_localhost())
}
}

And that’s it. I like the last implementation a lot because it makes use of iterator methods and closures. In this one-liner, this becomes so wonderfully readable.

Let’s change the original code:

let addr = req.as_str();
let addr = (addr, 0).to_socket_addrs();

if let Ok(true) = addr.map(|mut el| el.has_localhost()) {
return Box::pin(async { Err(io::Error::from(ErrorKind::Other)) });
}

Not that much of a change, but it becomes so obvious what’s happening. It says in the conditional that we’re checking for localhost, and for nothing else. The problem we’re solving becomes clear. Plus, we can do localhost checks at other places as well because the structs give us this information. ❤️

The lazy printer #

I’m using one-liner traits with implementations on other types a lot. This is one utility trait I use a lot when developing. I’m coming from JavaScript, so my most reliable debugger was stdout. I do Debug prints a lot, but I’m always very clumsy writing println!("{:?}", whatever);. This calls for a new trait!

trait Print {
fn print(&self);
}

… which I implement for every type that implements Debug.

impl<T: std::fmt::Debug> Print for T {
fn print(&self) {
println!("{:?}", self);
}
}

Fantastic!

"Hello, world".print();
vec![0, 1, 2, 3, 4].print();
"You get the idea".print()

What a nice utility. Tiny, little traits to make my life easier.

Related Articles