view C++/Base64.cpp @ 269:44dcc198bf0c

Dynlib (test): Add dl library for Linux
author David Demelier <markand@malikania.fr>
date Fri, 17 Oct 2014 14:20:00 +0200
parents b97d75a78e22
children
line wrap: on
line source

/*
 * Base64.cpp -- base64 encoding and decoding
 *
 * Copyright (c) 2013, 2014 David Demelier <markand@malikania.fr>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <iterator>
#include <sstream>

#include "Base64.h"

char Base64::lookup(int value) noexcept
{
	static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

	return table[value];
}

int Base64::rlookup(char ch)
{
	if (ch == '+')
		return 62;
	if (ch == '/')
		return 63;

	if (ch >= '0' && ch <= '9')
		return ch + 4;
	if (ch >= 'A' && ch <= 'Z')
		return ch - 65;
	if (ch >= 'a' && ch <= 'z')
		return ch - 71;

	throw std::invalid_argument("not a valid base64 string");
}

std::string Base64::encode(const std::string &input)
{
	std::string result;
	std::istringstream iss(input, std::istringstream::in);

	encode(std::istreambuf_iterator<char>(iss), std::istreambuf_iterator<char>(), std::back_inserter(result));

	return result;
}

std::string Base64::decode(const std::string &input)
{
	std::string result;
	std::istringstream iss(input, std::istringstream::in);

	decode(std::istreambuf_iterator<char>(iss), std::istreambuf_iterator<char>(), std::back_inserter(result));

	return result;
}