Parsing CSV

Walking a line

A CSV line is bytes in a buffer. Parse it with two pointers: one walks the buffer, one marks the start of the current field. The loop ends at the newline or the NUL:

mov rsi, line ; walker mov rdi, line ; field start loop: mov al, [rsi] cmp al, 0 je done

Splitting fields

When the walker hits a comma, the field runs from the field-start pointer to the walker. Copy it, print it, or store its length, then move the field-start pointer past the comma:

cmp al, "," jne next ; field = [rdi, rsi) lea rdi, [rsi+1] ; next field starts after the comma

Quoted fields

Real CSV quotes fields that contain commas or newlines. A quoted field starts with a double quote, keeps commas as data, and ends at the closing quote. Handle that state machine, or accept only unquoted input and say so in the program's docs.

The code on this page was assembled with NASM 3.01 and linked with GNU ld 2.45.1, and the program was run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev