1/* 2 * Copyright 2008 Haiku, Inc. All rights reserved. 3 * Distributed under the terms of the MIT License. 4 * 5 * Authors: 6 * Axel D��rfler, axeld@pinc-software.de 7 */ 8 9 10#include "PathList.h" 11 12#include <new> 13#include <stdlib.h> 14#include <string.h> 15 16 17struct PathList::path_entry { 18 path_entry(const char* _path) 19 : 20 ref_count(1) 21 { 22 path = strdup(_path); 23 } 24 25 ~path_entry() 26 { 27 free((char*)path); 28 } 29 30 const char* path; 31 int32 ref_count; 32}; 33 34 35PathList::PathList() 36 : 37 fPaths(10, true) 38{ 39} 40 41 42PathList::~PathList() 43{ 44} 45 46 47bool 48PathList::HasPath(const char* path, int32* _index) const 49{ 50 for (int32 i = fPaths.CountItems(); i-- > 0;) { 51 if (!strcmp(fPaths.ItemAt(i)->path, path)) { 52 if (_index != NULL) 53 *_index = i; 54 return true; 55 } 56 } 57 58 return false; 59} 60 61 62status_t 63PathList::AddPath(const char* path) 64{ 65 if (path == NULL) 66 return B_BAD_VALUE; 67 68 int32 index; 69 if (HasPath(path, &index)) { 70 fPaths.ItemAt(index)->ref_count++; 71 return B_OK; 72 } 73 74 path_entry* entry = new(std::nothrow) path_entry(path); 75 if (entry == NULL || entry->path == NULL || !fPaths.AddItem(entry)) { 76 delete entry; 77 return B_NO_MEMORY; 78 } 79 80 return B_OK; 81} 82 83 84status_t 85PathList::RemovePath(const char* path) 86{ 87 int32 index; 88 if (!HasPath(path, &index)) 89 return B_ENTRY_NOT_FOUND; 90 91 if (--fPaths.ItemAt(index)->ref_count == 0) 92 delete fPaths.RemoveItemAt(index); 93 94 return B_OK; 95} 96 97 98int32 99PathList::CountPaths() const 100{ 101 return fPaths.CountItems(); 102} 103 104 105const char* 106PathList::PathAt(int32 index) const 107{ 108 path_entry* entry = fPaths.ItemAt(index); 109 if (entry == NULL) 110 return NULL; 111 112 return entry->path; 113} 114