| 1 | // be_local.c reads the version with fscanf("%zu"); conversion policy stays in V. |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | module engine |
| 4 | |
| 5 | import os |
| 6 | |
| 7 | #include <ctype.h> |
| 8 | |
| 9 | fn C.fputs(&char, &C.FILE) i32 |
| 10 | fn C.isspace(i32) i32 |
| 11 | |
| 12 | fn local_version_byte(stream &C.FILE) !i32 { |
| 13 | value := C.getc(stream) |
| 14 | if value == C.EOF && C.ferror(stream) != 0 { return os.last_error() } |
| 15 | return value |
| 16 | } |
| 17 | |
| 18 | fn read_local_version(stream &C.FILE) !u64 { |
| 19 | mut current := local_version_byte(stream)! |
| 20 | for C.isspace(current) != 0 { |
| 21 | current = local_version_byte(stream)! |
| 22 | } |
| 23 | negative := current == `-` |
| 24 | if current in [i32(`+`), `-`] { current = local_version_byte(stream)! } |
| 25 | if current < `0` || current > `9` { return error('invalid local database version') } |
| 26 | limit := u64(C.SIZE_MAX) |
| 27 | mut number := u64(0) |
| 28 | mut overflow := false |
| 29 | for current >= `0` && current <= `9` { |
| 30 | digit := u64(current - `0`) |
| 31 | if !overflow { |
| 32 | if number > limit / 10 || (number == limit / 10 && digit > limit % 10) { |
| 33 | number = limit |
| 34 | overflow = true |
| 35 | } else { |
| 36 | number = number * 10 + digit |
| 37 | } |
| 38 | } |
| 39 | current = local_version_byte(stream)! |
| 40 | } |
| 41 | return if negative && !overflow { (u64(0) - number) & limit } else { number } |
| 42 | } |
| 43 | |
| 44 | fn read_and_close_local_version(stream &C.FILE) !u64 { |
| 45 | version := read_local_version(stream) or { |
| 46 | if C.fclose(stream) != 0 { |
| 47 | return error_with_code('${err.msg()}; could not close version file: ${os.last_error().msg()}', err.code()) |
| 48 | } |
| 49 | return err |
| 50 | } |
| 51 | if C.fclose(stream) != 0 { return os.last_error() } |
| 52 | return version |
| 53 | } |
| 54 | |
| 55 | fn validate_local_version(path string) ! { |
| 56 | filename := os.join_path(path, 'ALPM_DB_VERSION') |
| 57 | stream := C.fopen(unsafe { &char(filename.str) }, c'r') |
| 58 | if stream == unsafe { nil } { return os.last_error() } |
| 59 | version := read_and_close_local_version(stream)! |
| 60 | if version != 9 { return error('unsupported local database version: ${version}') } |
| 61 | } |
| 62 | |
| 63 | fn write_local_version(path string) ! { |
| 64 | filename := os.join_path(path, 'ALPM_DB_VERSION') |
| 65 | stream := C.fopen(unsafe { &char(filename.str) }, c'w') |
| 66 | if stream == unsafe { nil } { return os.last_error() } |
| 67 | status := C.fputs(c'9\n', stream) |
| 68 | problem := os.last_error() |
| 69 | closed := C.fclose(stream) |
| 70 | if status < 0 { return problem } |
| 71 | if closed != 0 { return os.last_error() } |
| 72 | } |
| 73 | |