hare

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

load.ha (1284B)


      1 // SPDX-License-Identifier: MPL-2.0
      2 // (c) Hare authors <https://harelang.org>
      3 
      4 use bufio;
      5 use io;
      6 use memio;
      7 use net::ip;
      8 use os;
      9 use strings;
     10 
     11 let cache: []ip::addr = [];
     12 
     13 @fini fn fini() void = {
     14 	free(cache);
     15 };
     16 
     17 // Reads a list of nameservers from resolv.conf. Aborts the program if the file
     18 // does not exist, is written in an invalid format, or if any other error
     19 // occurs.
     20 export fn load() []ip::addr = {
     21 	// XXX: Would be cool if we could do this without allocating anything
     22 	if (len(cache) != 0) {
     23 		return cache;
     24 	};
     25 
     26 	const file = os::open(PATH)!;
     27 	defer io::close(file)!;
     28 
     29 	for (true) {
     30 		const line = match (bufio::read_line(file)) {
     31 		case io::EOF =>
     32 			break;
     33 		case let line: []u8 =>
     34 			yield line;
     35 		};
     36 		defer free(line);
     37 		if (len(line) == 0 || line[0] == '#') {
     38 			continue;
     39 		};
     40 
     41 		const scanner = memio::fixed(line);
     42 		const tok = match (bufio::read_tok(&scanner, ' ', '\t')!) {
     43 		case io::EOF =>
     44 			break;
     45 		case let tok: []u8 =>
     46 			yield tok;
     47 		};
     48 		defer free(tok);
     49 		if (strings::fromutf8(tok)! != "nameserver") {
     50 			continue;
     51 		};
     52 
     53 		const tok = match (bufio::read_tok(&scanner, ' ')!) {
     54 		case io::EOF =>
     55 			break;
     56 		case let tok: []u8 =>
     57 			yield tok;
     58 		};
     59 		defer free(tok);
     60 		append(cache, ip::parse(strings::fromutf8(tok)!)!);
     61 	};
     62 
     63 	return cache;
     64 };