DOLFIN
DOLFIN C++ interface
Encoder.h
1// Copyright (C) 2009 Garth N. Wells
2//
3// This file is part of DOLFIN.
4//
5// DOLFIN is free software: you can redistribute it and/or modify
6// it under the terms of the GNU Lesser General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// DOLFIN is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU Lesser General Public License for more details.
14//
15// You should have received a copy of the GNU Lesser General Public License
16// along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
17//
18// Modified by Anders Logg 2011
19//
20// First added: 2009-08-11
21// Last changed: 2011-11-14
22
23#ifndef __ENCODER_H
24#define __ENCODER_H
25
26#ifdef HAS_ZLIB
27#include <zlib.h>
28extern "C"
29{
30 int compress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);
31}
32#endif
33
34#include <sstream>
35#include <vector>
36#include <utility>
37#include "base64.h"
38
39namespace dolfin
40{
41
44
47
48 namespace Encoder
49 {
50 template<typename T>
51 static void encode_base64(const T* data, std::size_t length,
52 std::stringstream& encoded_data)
53 {
54 encoded_data << base64_encode((const unsigned char*) &data[0],
55 length*sizeof(T));
56 }
57
58 template<typename T>
59 static void encode_base64(const std::vector<T>& data,
60 std::stringstream& encoded_data)
61 {
62 encoded_data << base64_encode((const unsigned char*) &data[0],
63 data.size()*sizeof(T));
64 }
65
66 #ifdef HAS_ZLIB
67 template<typename T>
68 static std::vector<unsigned char> compress_data(const std::vector<T>& data)
69 {
70 // Compute length of uncompressed data
71 const unsigned long uncompressed_size = data.size()*sizeof(T);
72
73 // Compute maximum length of compressed data
74 unsigned long compressed_size = (uncompressed_size + (((uncompressed_size)/1000)+1)+12);;
75
76 // Allocate space for compressed data
77 std::vector<unsigned char> compressed_data(compressed_size);
78
79 // Compress data
80 if (compress((Bytef*) compressed_data.data(), &compressed_size,
81 (const Bytef*) data.data(), uncompressed_size) != Z_OK)
82 {
83 dolfin_error("Encoder.h",
84 "compress data when writing file",
85 "Zlib error while compressing data");
86 }
87
88 // Return data
89 return compressed_data;
90 }
91 #endif
92
93 }
94}
95
96#endif
Definition: adapt.h:30
void dolfin_error(std::string location, std::string task, std::string reason,...)
Definition: log.cpp:129