1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/spdy/hpack/hpack_string_util.h"
10 #include "base/basictypes.h"
11 #include "base/logging.h"
12 #include "base/strings/string_piece.h"
13 #include "testing/gtest/include/gtest/gtest.h"
21 // Make sure StringPiecesEqualConstantTime() behaves like the regular
22 // string equality operator.
23 TEST(HpackStringUtilTest
, StringPiecesEqualConstantTime
) {
24 EXPECT_TRUE(StringPiecesEqualConstantTime("foo", "foo"));
25 EXPECT_FALSE(StringPiecesEqualConstantTime("foo", "foox"));
26 EXPECT_FALSE(StringPiecesEqualConstantTime("foo", "bar"));
29 // TODO(jgraettinger): Support this benchmark.
31 enum BM_StringPieceEqualityType {
33 STRCMP_FIRST_CHAR_DIFFERS,
34 STRING_PIECES_EQUAL_CONSTANT_TIME_EQUAL,
35 STRING_PIECES_EQUAL_CONSTANT_TIME_FIRST_CHAR_DIFFERS,
38 void BM_StringPieceEquality(int iters, int size, int type_int) {
39 BM_StringPieceEqualityType type =
40 static_cast<BM_StringPieceEqualityType>(type_int);
41 string str_a(size, 'x');
42 string str_b(size, 'x');
46 for (int i = 0; i < iters; ++i) {
47 result |= std::strcmp(str_a.c_str(), str_b.c_str());
52 case STRCMP_FIRST_CHAR_DIFFERS:
54 for (int i = 0; i < iters; ++i) {
55 result |= std::strcmp(str_a.c_str(), str_b.c_str());
60 case STRING_PIECES_EQUAL_CONSTANT_TIME_EQUAL:
61 for (int i = 0; i < iters; ++i) {
62 result |= StringPiecesEqualConstantTime(str_a, str_b);
67 case STRING_PIECES_EQUAL_CONSTANT_TIME_FIRST_CHAR_DIFFERS:
69 for (int i = 0; i < iters; ++i) {
70 result |= StringPiecesEqualConstantTime(str_a, str_b);
79 // Results should resemble the table below, where 0 and 1 are clearly
80 // different (STRCMP), but 2 and 3 are roughly the same
81 // (STRING_PIECES_EQUAL_CONSTANT_TIME).
83 // DEBUG: Benchmark Time(ns) CPU(ns) Iterations
84 // -------------------------------------------------------------------
85 // DEBUG: BM_StringPieceEquality/1M/0 77796 77141 7778
86 // DEBUG: BM_StringPieceEquality/1M/1 10 10 70000000
87 // DEBUG: BM_StringPieceEquality/1M/2 7729735 7700000 100
88 // DEBUG: BM_StringPieceEquality/1M/3 7803051 7800000 100
89 BENCHMARK(BM_StringPieceEquality)
90 ->ArgPair(1<<20, STRCMP_EQUAL)
91 ->ArgPair(1<<20, STRCMP_FIRST_CHAR_DIFFERS)
92 ->ArgPair(1<<20, STRING_PIECES_EQUAL_CONSTANT_TIME_EQUAL)
93 ->ArgPair(1<<20, STRING_PIECES_EQUAL_CONSTANT_TIME_FIRST_CHAR_DIFFERS);