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

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
V
Visual Studio Blog
The GitHub Blog
The GitHub Blog
Apple Machine Learning Research
Apple Machine Learning Research
J
Java Code Geeks
T
Tailwind CSS Blog
大猫的无限游戏
大猫的无限游戏
Jina AI
Jina AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
罗磊的独立博客
人人都是产品经理
人人都是产品经理
H
Heimdal Security Blog
Last Week in AI
Last Week in AI
博客园 - 【当耐特】
Cyberwarzone
Cyberwarzone
Google DeepMind News
Google DeepMind News
雷峰网
雷峰网
Hacker News: Ask HN
Hacker News: Ask HN
Webroot Blog
Webroot Blog
Microsoft Azure Blog
Microsoft Azure Blog
MyScale Blog
MyScale Blog
A
About on SuperTechFans
V2EX - 技术
V2EX - 技术
小众软件
小众软件
博客园 - Franky
博客园 - 司徒正美
P
Privacy International News Feed
爱范儿
爱范儿
U
Unit 42
博客园 - 叶小钗
The Hacker News
The Hacker News
C
Check Point Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Simon Willison's Weblog
Simon Willison's Weblog
N
News and Events Feed by Topic
D
Docker
T
Threatpost
MongoDB | Blog
MongoDB | Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
H
Help Net Security
L
LINUX DO - 最新话题
Security Latest
Security Latest
T
The Exploit Database - CXSecurity.com
S
SegmentFault 最新的问题
A
Arctic Wolf
Spread Privacy
Spread Privacy

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
csv-peek — A 700-Line Rust CLI That Pretty-Prints CSV in the Terminal With a Hand-Rolled RFC 4180 Parser, Type Inference, and One Dependency
SEN LLC · 2026-05-09 · via DEV Community

cat customers.csv and the columns slide off the right edge of your terminal. You don't really want to open a spreadsheet just to spot-check eight rows. csv-peek customers.csv prints an aligned table in 1 ms — numbers right-aligned in cyan, dates in yellow, booleans in magenta, the embedded comma in "hello, world" not breaking alignment because the parser actually understands quoting. Single dependency (clap), sub-1 MB stripped binary, 51 tests.

csv-peek rendering an 8-row sample CSV in a terminal: id (cyan, right-aligned), name, email, signup_date (yellow), active (magenta), balance (cyan, right-aligned), note. Box-drawing borders enclose the table. Below:

📦 GitHub: https://github.com/sen-ltd/csv-peek

$ cat customers.csv
id,name,email,signup_date,active,balance,note
1,Alice Suzuki,alice@example.com,2024-01-15,true,1280.50,"first 10 customers"
2,Bob Tanaka,bob@example.com,2024-02-03,true,42.00,
…

$ csv-peek customers.csv
┌────┬──────────────┬───────────────────┬─────────────┬────────┬─────────┬────────────────────┐
│ id │ name         │ email             │ signup_date │ active │ balance │ note               │
├────┼──────────────┼───────────────────┼─────────────┼────────┼─────────┼────────────────────┤
│  1 │ Alice Suzuki │ alice@example.com │ 2024-01-15  │ true   │ 1280.50 │ first 10 customers │
│  2 │ Bob Tanaka   │ bob@example.com   │ 2024-02-03  │ true   │   42.00 │                    │
…

Enter fullscreen mode Exit fullscreen mode

Why hand-roll the parser

Rust has a mature csv crate. For real production work, that's the answer. Two reasons to hand-roll anyway:

  1. The dependency tree stays at one entry. cargo build --release finishes in 9 seconds, the stripped Alpine binary is ~600 KB, and the CI matrix is one cell wide.
  2. The state machine is the article. RFC 4180 is short — four rules — and walking through what "", \r\n, and "foo\nbar" actually mean in a CSV is more useful than csv::Reader::from_path() is.

The whole parser is 200 lines in src/csv.rs. I'll quote the core machine and the bits that I find most often misimplemented.

The four-state machine

enum State {
    Start,         // between fields
    Unquoted,      // inside an unquoted field
    Quoted,        // inside a "..." field
    QuotedQuote,   // saw a `"` inside a quoted field
}

Enter fullscreen mode Exit fullscreen mode

QuotedQuote is the interesting one. Once you've seen a " inside a quoted field, you can't tell yet whether it was the closing quote or the first half of an escaped pair (""). You need the next byte to decide:

State::QuotedQuote => match b {
    b'"' => {
        // It was `""` — emit a literal `"` and stay in Quoted.
        field.push(b'"');
        state = State::Quoted;
    }
    c if c == self.delim => {
        // Closing quote followed by delimiter — field ends here.
        fields.push(...);
        state = State::Start;
    }
    b'\r' | b'\n' => {
        // Closing quote followed by newline — record ends here.
        return Ok(Some(...));
    }
    other => {
        // Malformed input like `"foo"bar`. Strict parsers Err here;
        // we'd rather render *something*, so we recover by appending
        // the byte and falling back to Unquoted.
        field.push(other);
        state = State::Unquoted;
    }
}

Enter fullscreen mode Exit fullscreen mode

The recovery branch matters because csv-peek's job is to let you see what's there, even when "what's there" is broken. "foo"bar\n parses to foobar. A strict parser would refuse the line and the user would never see what was wrong with it.

CRLF / LF / CR — sometimes mixed in the same file

CSV inherits the OS-line-ending mess: classic Mac (\r), Unix (\n), Windows (\r\n), and Excel-on-Mac will sometimes mix them in a single file. The parser needs one-byte lookahead:

b'\r' => {
    fields.push(...);
    if let Some(nb) = self.next_byte()? {
        if nb != b'\n' {
            self.pos -= 1;   // peek failed; push it back
        }
    }
    return Ok(Some(...));
}

Enter fullscreen mode Exit fullscreen mode

Implementing peek over a streaming BufReader was the part of the parser I rewrote three times. The version that shipped is a manual circular-ish buffer (Vec<u8> + pos) inside Reader<R: Read>, refilled in 64 KB chunks. The lookahead is just pos -= 1.

Per-column type inference

Each column gets one of Empty / Bool / Int / Float / Date / Text by widening across the body sample. The hierarchy is Empty < Bool < Int < Float < Date < Text — once any value forces Text, the column is Text for good.

fn widen(a: ColType, b: ColType) -> ColType {
    if matches!(a, Empty) { return b; }
    if matches!(b, Empty) { return a; }
    if (a == Int && b == Float) || (a == Float && b == Int) {
        return Float;
    }
    if a == b { a } else { Text }
}

Enter fullscreen mode Exit fullscreen mode

So:

  • [1, 2, 3]Int
  • [1, 2.5, 3]Float (Int promotes to Float)
  • ["", 1, "", 2]Int (Empty is absorbed)
  • [1, "alice", 3]Text (mixed → bail)

Each value gets classified by classify(v):

fn classify(v: &str) -> ColType {
    let s = v.trim();
    if s.is_empty()                    { return Empty; }
    if matches_bool(s)                 { return Bool; }
    if s.parse::<i64>().is_ok()        { return Int; }
    if s.parse::<f64>().is_ok() && !s.eq_ignore_ascii_case("nan") {
        return Float;
    }
    if matches_date(s)                 { return Date; }
    Text
}

Enter fullscreen mode Exit fullscreen mode

The NaN exclusion is deliberate: f64::parse accepts "NaN", but a column containing the literal string NaN mixed with numbers is almost certainly not numeric data, and aligning it like a number makes the table look broken.

Date detection is a cheap shape check, not a calendar:

fn matches_date(s: &str) -> bool {
    let bytes = s.as_bytes();
    if bytes.len() < 10 { return false; }
    let dash_or_slash = |b| b == b'-' || b == b'/';
    bytes[0..4].iter().all(|b| b.is_ascii_digit())
        && dash_or_slash(bytes[4])
        && bytes[5..7].iter().all(|b| b.is_ascii_digit())
        && dash_or_slash(bytes[7])
        && bytes[8..10].iter().all(|b| b.is_ascii_digit())
        && (bytes.len() == 10 || matches!(bytes[10], b' ' | b'T'))
}

Enter fullscreen mode Exit fullscreen mode

2024-13-99 is "a date" by this function. That's fine — type inference runs in microseconds, doesn't have to be right, and the wrong answer for a date-shaped string is still better than rendering it as text.

ANSI palette without per-cell branches

Palette accessors return &'static str. When color is disabled, every accessor returns "". The hot loop never branches on a flag — it just write!s zero-length escape codes that the terminal sees as nothing:

pub struct Palette { enabled: bool }

impl Palette {
    pub fn cyan(&self) -> &'static str {
        if self.enabled { "\x1b[36m" } else { "" }
    }
    pub fn reset(&self) -> &'static str {
        if self.enabled { "\x1b[0m" } else { "" }
    }
}

// Render path
write!(w, " {}{}{} {}", palette.cyan(), value, palette.reset(), border)?;

Enter fullscreen mode Exit fullscreen mode

rustc folds the empty &str writes away and the binary ends up branch-free. The pattern came from #137 hexview (the first Rust entry in this portfolio) and has been the house style ever since.

TTY detection without the atty crate

atty is deprecated in favour of std::io::IsTerminal:

use std::io::IsTerminal;

let stdout_is_tty = io::stdout().is_terminal();
let no_color = args.no_color
    || std::env::var_os("NO_COLOR").is_some()
    || !stdout_is_tty;

Enter fullscreen mode Exit fullscreen mode

That's the entire color-detection logic. Pipe to less and color disappears automatically; set NO_COLOR=1 and color disappears manually; pass --no-color and color disappears explicitly. All three converge into one boolean and the Palette fans out from there.

Sniffing the delimiter

When --delim isn't passed, the first line gets scanned for , \t ; |, and whichever appears most often wins:

pub fn guess_delimiter(sample: &str) -> u8 {
    let candidates = [b',', b'\t', b';', b'|'];
    let line = sample.lines().next().unwrap_or("");
    let mut best = (b',', 0usize);
    for &c in &candidates {
        let count = line.bytes().filter(|&b| b == c).count();
        if count > best.1 {
            best = (c, count);
        }
    }
    best.0
}

Enter fullscreen mode Exit fullscreen mode

Ties default to ,. A single-column file (zero of any of the candidates) also defaults to , and just renders as one column. Tab-separated and semicolon-separated files Just Work.

51 tests

$ cargo test
running 34 tests
test csv::tests::quoted_field_with_comma ... ok
test csv::tests::escaped_quote_inside_quoted_field ... ok
test csv::tests::quoted_field_with_newline ... ok
…
test result: ok. 34 passed; 0 failed
running 17 tests
test renders_basic_csv ... ok
test no_color_env_disables_escape_sequences ... ok
test handles_unicode_data ... ok
…
test result: ok. 17 passed; 0 failed

Enter fullscreen mode Exit fullscreen mode

The unit half of the test suite covers the parser edge cases (every quoted-field scenario, the recovery path, CRLF/LF/CR mixing), the type-inference widening rules, and the padding / truncate helpers including unicode width.

The integration half uses assert_cmd + predicates to drive the actual binary against fixture CSV files. Every CLI flag has at least one test; NO_COLOR=1, piping detection, ASCII vs Unicode borders, --no-header synthesizing column names, --delim overriding the sniffer, etc.

#[test]
fn handles_quoted_fields_with_commas() {
    let f = fixture("name,bio\nAlice,\"hello, world\"\n");
    cli().arg(f.path()).arg("--ascii").assert()
        .success()
        .stdout(predicate::str::contains("hello, world"));
}

Enter fullscreen mode Exit fullscreen mode

Try it

git clone https://github.com/sen-ltd/csv-peek
cd csv-peek
cargo build --release
./target/release/csv-peek sample.csv

Enter fullscreen mode Exit fullscreen mode

Or via Docker (no Rust toolchain needed):

docker build -t csv-peek .
docker run --rm -v "$(pwd)":/data -t csv-peek customers.csv

Enter fullscreen mode Exit fullscreen mode

The -t flag is necessary so the container sees a TTY and IsTerminal returns true; without it, csv-peek auto-disables color (the same path that fires when you pipe to less).

Source: https://github.com/sen-ltd/csv-peek — MIT, ~700 lines, single dependency, 51 tests, sub-1 MB stripped binary.


🛠 Built by SEN LLC as part of an ongoing series of small, focused developer tools. Browse the full portfolio for more.