hare

[hare] The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

lookup.ha (1355B)


      1 // License: MPL-2.0
      2 // (c) 2022 Alexey Yerin <yyp@disroot.org>
      3 // (c) 2021 Drew DeVault <sir@cmpwn.com>
      4 // (c) 2021 Ember Sawady <ecs@d2evs.net>
      5 use bufio;
      6 use io;
      7 use net::ip;
      8 use os;
      9 use strings;
     10 
     11 // Looks up a host from /etc/hosts. Aborts the program if the file does not
     12 // exist, is written in an invalid format, or if any other error occurs.
     13 export fn lookup(name: str) []ip::addr = {
     14 	// XXX: Would be cool if we could do this without allocating anything
     15 	// XXX: Would be cool to have meaningful error handling(?)
     16 	const file = os::open(PATH)!;
     17 	defer io::close(file)!;
     18 
     19 	let addrs: []ip::addr = [];
     20 	for (true) {
     21 		const line = match (bufio::scanline(file)) {
     22 		case io::EOF =>
     23 			break;
     24 		case let line: []u8 =>
     25 			yield line;
     26 		};
     27 		defer free(line);
     28 		if (len(line) == 0 || line[0] == '#') {
     29 			continue;
     30 		};
     31 
     32 		const scanner = bufio::fixed(line, io::mode::READ);
     33 		const tok = match (bufio::scantok(&scanner, ' ', '\t')!) {
     34 		case io::EOF =>
     35 			break;
     36 		case let tok: []u8 =>
     37 			yield tok;
     38 		};
     39 		defer free(tok);
     40 		const addr = ip::parse(strings::fromutf8(tok)!)!;
     41 
     42 		for (true) {
     43 			const tok = match (bufio::scantok(&scanner, ' ', '\t')!) {
     44 			case io::EOF =>
     45 				break;
     46 			case let tok: []u8 =>
     47 				yield tok;
     48 			};
     49 			defer free(tok);
     50 
     51 			if (strings::fromutf8(tok)! == name) {
     52 				append(addrs, addr);
     53 			};
     54 		};
     55 	};
     56 	return addrs;
     57 };