blob: 42e13c5422daf472693c477d5348ff8be9de70a4 [file] [log] [blame]
henrike@webrtc.orgcd9adf72012-09-29 03:49:36 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "system_wrappers/interface/aligned_malloc.h"
12
13#if _WIN32
14#include <windows.h>
15#else
16#include <stdint.h>
17#endif
18
19#include "typedefs.h" // NOLINT
20
21#include "gtest/gtest.h"
22
23// Returns true if |size| and |alignment| are valid combinations.
24bool CorrectUsage(size_t size, size_t alignment) {
25 webrtc::Allocator<char>::scoped_ptr_aligned scoped(
henrike@webrtc.org46d40732012-10-03 16:50:37 +000026 webrtc::AlignedMalloc<char>(size, alignment));
henrike@webrtc.orgcd9adf72012-09-29 03:49:36 +000027 if (scoped.get() == NULL) {
28 return false;
29 }
30 const uintptr_t scoped_address = reinterpret_cast<uintptr_t> (scoped.get());
31 return 0u == scoped_address % alignment;
32}
33
34TEST(AlignedMalloc, GetRightAlign) {
35 const size_t size = 100;
36 const size_t alignment = 32;
37 const size_t left_missalignment = 8;
38 webrtc::Allocator<char>::scoped_ptr_aligned scoped(
henrike@webrtc.org46d40732012-10-03 16:50:37 +000039 webrtc::AlignedMalloc<char>(size, alignment));
henrike@webrtc.orgcd9adf72012-09-29 03:49:36 +000040 EXPECT_TRUE(scoped.get() != NULL);
41 const uintptr_t aligned_address = reinterpret_cast<uintptr_t> (scoped.get());
42 const uintptr_t missaligned_address = aligned_address - left_missalignment;
henrike@webrtc.org46d40732012-10-03 16:50:37 +000043 const char* missaligned_ptr = reinterpret_cast<const char*>(
44 missaligned_address);
45 const char* realigned_ptr = webrtc::GetRightAlign(
46 missaligned_ptr, alignment);
47 EXPECT_EQ(scoped.get(), realigned_ptr);
henrike@webrtc.orgcd9adf72012-09-29 03:49:36 +000048}
49
50TEST(AlignedMalloc, IncorrectSize) {
51 const size_t incorrect_size = 0;
52 const size_t alignment = 64;
53 EXPECT_FALSE(CorrectUsage(incorrect_size, alignment));
54}
55
56TEST(AlignedMalloc, IncorrectAlignment) {
57 const size_t size = 100;
58 const size_t incorrect_alignment = 63;
59 EXPECT_FALSE(CorrectUsage(size, incorrect_alignment));
60}
61
62TEST(AlignedMalloc, AlignTo2Bytes) {
63 size_t size = 100;
64 size_t alignment = 2;
65 EXPECT_TRUE(CorrectUsage(size, alignment));
66}
67
68TEST(AlignedMalloc, AlignTo32Bytes) {
69 size_t size = 100;
70 size_t alignment = 32;
71 EXPECT_TRUE(CorrectUsage(size, alignment));
72}
73
74TEST(AlignedMalloc, AlignTo128Bytes) {
75 size_t size = 100;
76 size_t alignment = 128;
77 EXPECT_TRUE(CorrectUsage(size, alignment));
78}