/* * Copyright (C) 2006-2007 Toni Corvera * * This program 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 2 of the License, or * (at your option) any later version. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // $Id: str_utils.cc 726 2007-05-20 14:27:08Z $ #include "str_utils.h" #include // std::transform #include // std::toupper #include #include namespace net_outlyer { namespace str_utils { using std::string; using std::transform; using std::vector; inline static string copy_transform(const string & s, int(*callback)(int)) { string cp(s); transform(s.begin(), s.end(), cp.begin(), callback); return cp; } const string to_upper(const string & s) { return copy_transform(s, std::toupper); } const string to_lower(const string & s) { return copy_transform(s, std::tolower); } const string to_hex(int n) { return to_string(n, std::hex); } // FIXME: isn't this standardly defined somewhere? #define MAX(a,b) ( (a)>(b) ? (a) : (b) ) const string pad(const string & s, size_t pad_to, const string & pad, const pad_direction & p) { if (s.length() >= pad_to) return s; string cp; cp.reserve(pad_to); size_t diff = pad_to - s.length(); assert( diff > 0 ); switch (p) { case PAD_RIGHT: case PAD_LEFT: { string padding(pad); while (padding.length() < diff) { padding.append(pad); } if (PAD_RIGHT == p) { cp = s + padding.substr(0, diff); } else { assert( PAD_LEFT == p ); cp = padding.substr(0, diff) + s; } } break; case PAD_BOTH: { size_t llen = diff / 2; size_t rlen = diff - llen; string padding(pad); while (padding.length() < MAX(llen, rlen)) { padding.append(pad); } cp = padding.substr(0, llen) + s + padding.substr(0, rlen); } break; default: assert( false ); } // switch return cp; } // string_pad bool ends_in(const string & s, const string & end) { assert( end.length() > 0 ); if (end.length() > s.length()) return false; return s.substr(s.length() - end.length()) == end; } } // namespace str_utils } // namespace net_outlyer /* vim:set ts=4 et ai: */