/* * Copyright (C) 2023 Patrick McDermott * * This file is part of opkg-opk. * * opkg-opk is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * opkg-opk is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with opkg-opk. If not, see . */ #include #include #include #include "defs.h" #include "dirent.h" static int _opkg_opk_dirent_name_prefix(struct opkg_opk_dirent *dirent, char **name_buf, size_t *name_buf_len, char **pref_buf, size_t *pref_buf_len, size_t *name_len, size_t *pref_len) { size_t len; char **buf; len = strlen(dirent->name); if (*name_len + len <= *name_buf_len) { buf = name_buf; if (*buf == NULL) { return OPKG_OPK_ERROR; } if (**buf != '\0') { ++len; } *name_buf_len -= len; } else if (*pref_len + len <= *pref_buf_len) { buf = pref_buf; if (*buf == NULL) { return OPKG_OPK_ERROR; } if (**buf != '\0') { ++len; } *pref_buf_len -= len; } else { return OPKG_OPK_ERROR; } if (dirent->parent != NULL && _opkg_opk_dirent_name_prefix(dirent->parent, name_buf, name_buf_len, pref_buf, pref_buf_len, name_len, pref_len) == OPKG_OPK_ERROR) { return OPKG_OPK_ERROR; } if (**buf != '\0') { **buf = '/'; *buf += 1; --len; } memcpy(*buf, dirent->name, len); *buf += len; return OPKG_OPK_OK; } int opkg_opk_dirent_name_prefix(struct opkg_opk_dirent *dirent, char *name_buf, size_t name_buf_len, char *pref_buf, size_t pref_buf_len) { size_t name_len = 0; size_t pref_len = 0; name_buf[0] = '\0'; pref_buf[0] = '\0'; if (_opkg_opk_dirent_name_prefix(dirent, &name_buf, &name_buf_len, &pref_buf, &pref_buf_len, &name_len, &pref_len) == OPKG_OPK_ERROR) { return OPKG_OPK_ERROR; } name_buf[name_len] = '\0'; pref_buf[pref_len] = '\0'; return OPKG_OPK_OK; } int main() { struct opkg_opk_dirent foo = { .name = "foo", .parent = NULL, }; struct opkg_opk_dirent bar = { .name = "bar", .parent = &foo, }; struct opkg_opk_dirent baz = { .name = "baz", .parent = &bar, }; char name[8]; char pref[5]; if (opkg_opk_dirent_name_prefix(&baz, name, 8, pref, 5) != OPKG_OPK_OK) { puts("Error building name parts"); return EXIT_FAILURE; } puts(name); puts(pref); return EXIT_SUCCESS; }