Botan  1.11.15
src/lib/utils/mem_ops.h
Go to the documentation of this file.
00001 /*
00002 * Memory Operations
00003 * (C) 1999-2009,2012 Jack Lloyd
00004 *
00005 * Botan is released under the Simplified BSD License (see license.txt)
00006 */
00007 
00008 #ifndef BOTAN_MEMORY_OPS_H__
00009 #define BOTAN_MEMORY_OPS_H__
00010 
00011 #include <botan/types.h>
00012 #include <cstring>
00013 
00014 namespace Botan {
00015 
00016 /**
00017 * Zeroize memory
00018 * @param ptr a pointer to memory to zero out
00019 * @param n the number of bytes pointed to by ptr
00020 */
00021 BOTAN_DLL void zero_mem(void* ptr, size_t n);
00022 
00023 /**
00024 * Zeroize memory
00025 * @param ptr a pointer to an array
00026 * @param n the number of Ts pointed to by ptr
00027 */
00028 template<typename T> inline void clear_mem(T* ptr, size_t n)
00029    {
00030    std::memset(ptr, 0, sizeof(T)*n);
00031    }
00032 
00033 /**
00034 * Copy memory
00035 * @param out the destination array
00036 * @param in the source array
00037 * @param n the number of elements of in/out
00038 */
00039 template<typename T> inline void copy_mem(T* out, const T* in, size_t n)
00040    {
00041    std::memmove(out, in, sizeof(T)*n);
00042    }
00043 
00044 /**
00045 * Set memory to a fixed value
00046 * @param ptr a pointer to an array
00047 * @param n the number of Ts pointed to by ptr
00048 * @param val the value to set each byte to
00049 */
00050 template<typename T>
00051 inline void set_mem(T* ptr, size_t n, byte val)
00052    {
00053    std::memset(ptr, val, sizeof(T)*n);
00054    }
00055 
00056 /**
00057 * Memory comparison, input insensitive
00058 * @param p1 a pointer to an array
00059 * @param p2 a pointer to another array
00060 * @param n the number of Ts in p1 and p2
00061 * @return true iff p1[i] == p2[i] forall i in [0...n)
00062 */
00063 template<typename T> inline bool same_mem(const T* p1, const T* p2, size_t n)
00064    {
00065    volatile T difference = 0;
00066 
00067    for(size_t i = 0; i != n; ++i)
00068       difference |= (p1[i] ^ p2[i]);
00069 
00070    return difference == 0;
00071    }
00072 
00073 }
00074 
00075 #endif