Skip to content

Instantly share code, notes, and snippets.

@foxcpp
Created August 19, 2019 15:48
Show Gist options
  • Save foxcpp/df9cb331f1a129e0f2d00c054c2e71b6 to your computer and use it in GitHub Desktop.
Save foxcpp/df9cb331f1a129e0f2d00c054c2e71b6 to your computer and use it in GitHub Desktop.
The fastest Longest Line Length finding code in the West.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
void find_longest(const char *file, unsigned file_length,
const char **longest_start, unsigned *longest_len) {
const char *cur_start = file;
const char *cur = cur_start;
unsigned file_off = 0;
const char *longest_start_l;
unsigned longest_len_l = 0;
for (; file_off < file_length; ++cur, ++file_off) {
if (__builtin_expect(*cur == '\n', 0)) {
unsigned cur_length = cur - cur_start;
if (cur_length > longest_len_l) {
longest_start_l = cur_start;
longest_len_l = cur_length;
}
cur_start = cur+1;
}
}
unsigned cur_length = cur - cur_start;
if (cur_length > *longest_len) {
longest_start_l = cur_start;
longest_len_l = cur_length;
}
*longest_len = longest_len_l;
*longest_start = longest_start_l;
}
int main(int argc, char** argv) {
if (argc != 2) {
printf("Usage: %s <file>\n", argv[0]);
return 2;
}
struct stat finfo;
if (stat(argv[1], &finfo) < 0) {
perror("stat");
return 1;
}
int fd = open(argv[1], O_RDONLY);
if (fd < 0) {
perror("open");
return 1;
}
char* filebuf = mmap(0, finfo.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (filebuf == MAP_FAILED) {
perror("mmap");
return 1;
}
if (madvise(filebuf, finfo.st_size, MADV_SEQUENTIAL) < 0) {
perror("madvise");
return 1;
}
unsigned longest_len = 0;
const char *longest_start = 0;
find_longest(filebuf, finfo.st_size, &longest_start, &longest_len);
printf("Longest line length: %d\n", longest_len);
char *linebuffer = malloc(longest_len + 1);
memcpy(linebuffer, longest_start, longest_len);
linebuffer[longest_len] = '\0';
printf("Line: %s\n", linebuffer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment