1 // license:GPL-2.0+
2 // copyright-holders:Couriersud
3 
4 #include "putil.h"
5 #include "penum.h"
6 #include "pstream.h"
7 #include "pstrutil.h"
8 #include "ptypes.h"
9 
10 #include <algorithm>
11 // needed for getenv ...
12 #include <initializer_list>
13 
14 namespace plib
15 {
16 	namespace util
17 	{
18 		static constexpr const char PATH_SEP = compile_info::win32::value ? '\\' : '/';
19 		static constexpr const char *PATH_SEPS = compile_info::win32::value ? "\\/" :"/";
20 
basename(const pstring & filename,const pstring & suffix)21 		pstring basename(const pstring &filename, const pstring &suffix)
22 		{
23 			auto p=find_last_of(filename, pstring(PATH_SEPS));
24 			pstring ret = (p == pstring::npos) ? filename : filename.substr(p+1);
25 			if (!suffix.empty() && endsWith(ret, suffix))
26 				return ret.substr(0, ret.length() - suffix.length());
27 			return ret;
28 		}
29 
path(const pstring & filename)30 		pstring path(const pstring &filename)
31 		{
32 			auto p=find_last_of(filename, pstring(1, PATH_SEP));
33 			if (p == pstring::npos)
34 				return "";
35 			if (p == 0) // root case
36 				return filename.substr(0, 1);
37 
38 			return filename.substr(0, p);
39 		}
40 
exists(const pstring & filename)41 		bool exists (const pstring &filename)
42 		{
43 			plib::ifstream f(filename);
44 			return f.good();
45 		}
46 
buildpath(std::initializer_list<pstring> list)47 		pstring buildpath(std::initializer_list<pstring> list )
48 		{
49 			pstring ret = "";
50 			for( const auto &elem : list )
51 			{
52 				if (ret.empty())
53 					ret = elem;
54 				else
55 					ret += (PATH_SEP + elem);
56 			}
57 			return ret;
58 		}
59 
environment(const pstring & var,const pstring & default_val)60 		pstring environment(const pstring &var, const pstring &default_val)
61 		{
62 			putf8string varu8(var);
63 			return (std::getenv(varu8.c_str()) == nullptr) ? default_val
64 				: pstring(std::getenv(varu8.c_str()));
65 		}
66 	} // namespace util
67 
from_string_int(const pstring & str,const pstring & x)68 	int penum_base::from_string_int(const pstring &str, const pstring &x)
69 	{
70 		int cnt = 0;
71 		for (auto &s : psplit(str, ',', false))
72 		{
73 			if (trim(s) == x)
74 				return cnt;
75 			cnt++;
76 		}
77 		return -1;
78 	}
79 
nthstr(std::size_t n,const pstring & str)80 	pstring penum_base::nthstr(std::size_t n, const pstring &str)
81 	{
82 		return psplit(str, ',', false)[n];
83 	}
84 } // namespace plib
85