iobuf_unittest.cpp 51.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
17 18 19 20 21 22

#include <gtest/gtest.h>
#include <sys/types.h>
#include <sys/socket.h>                // socketpair
#include <errno.h>                     // errno
#include <fcntl.h>                     // O_RDONLY
23 24 25 26 27 28 29 30 31 32
#include <butil/files/temp_file.h>      // TempFile
#include <butil/containers/flat_map.h>
#include <butil/macros.h>
#include <butil/time.h>                 // Timer
#include <butil/fd_utility.h>           // make_non_blocking
#include <butil/iobuf.h>
#include <butil/logging.h>
#include <butil/fd_guard.h>
#include <butil/errno.h>
#include <butil/fast_rand.h>
33 34 35
#if BAZEL_TEST
#include "test/iobuf.pb.h"
#else
36
#include "iobuf.pb.h"
37
#endif   // BAZEL_TEST
38

39
namespace butil {
40 41 42 43
namespace iobuf {
extern void* (*blockmem_allocate)(size_t);
extern void (*blockmem_deallocate)(void*);
extern void reset_blockmem_allocate_and_deallocate();
44 45
extern int32_t block_shared_count(butil::IOBuf::Block const* b);
extern uint32_t block_cap(butil::IOBuf::Block const* b);
46 47 48
extern IOBuf::Block* get_tls_block_head();
extern int get_tls_block_count();
extern void remove_tls_block_chain();
李磊's avatar
李磊 committed
49 50 51 52 53
extern IOBuf::Block* acquire_tls_block();
extern void release_tls_block_chain(IOBuf::Block* b);
extern uint32_t block_cap(IOBuf::Block const* b);
extern uint32_t block_size(IOBuf::Block const* b);
extern IOBuf::Block* get_portal_next(IOBuf::Block const* b);
54 55 56 57
}
}

namespace {
58 59 60 61

const size_t BLOCK_OVERHEAD = 32; //impl dependent
const size_t DEFAULT_PAYLOAD = butil::IOBuf::DEFAULT_BLOCK_SIZE - BLOCK_OVERHEAD;

62
void check_tls_block() {
63 64
    ASSERT_EQ((butil::IOBuf::Block*)NULL, butil::iobuf::get_tls_block_head());
    printf("tls_block of butil::IOBuf was deleted\n");
65
}
66
const int ALLOW_UNUSED check_dummy = butil::thread_atexit(check_tls_block);
67

68
static butil::FlatSet<void*> s_set;
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

void* debug_block_allocate(size_t block_size) {
    void* b = operator new (block_size, std::nothrow);
    s_set.insert(b);
    return b;
}

void debug_block_deallocate(void* b) {
    if (1ul != s_set.erase(b)) {
        ASSERT_TRUE(false) << "Bad block=" << b;
    } else {
        operator delete(b);
    }
}

inline bool is_debug_allocator_enabled() {
85
    return (butil::iobuf::blockmem_allocate == debug_block_allocate);
86 87 88 89
}

void install_debug_allocator() {
    if (!is_debug_allocator_enabled()) {
90
        butil::iobuf::remove_tls_block_chain();
91
        s_set.init(1024);
92 93
        butil::iobuf::blockmem_allocate = debug_block_allocate;
        butil::iobuf::blockmem_deallocate = debug_block_deallocate;
94 95 96 97 98 99 100 101 102 103 104
        LOG(INFO) << "<Installed debug create/destroy>";
    }
}

void show_prof_and_rm(const char* bin_name, const char* filename, size_t topn) {
    char cmd[1024];
    if (topn != 0) {
        snprintf(cmd, sizeof(cmd), "if [ -e %s ] ; then CPUPROFILE_FREQUENCY=1000 ./pprof --text %s %s | head -%lu; rm -f %s; fi", filename, bin_name, filename, topn+1, filename);
    } else {
        snprintf(cmd, sizeof(cmd), "if [ -e %s ] ; then CPUPROFILE_FREQUENCY=1000 ./pprof --text %s %s; rm -f %s; fi", filename, bin_name, filename, filename);
    }
gejun's avatar
gejun committed
105
    ASSERT_EQ(0, system(cmd));
106 107 108 109
}

static void check_memory_leak() {
    if (is_debug_allocator_enabled()) {
110
        butil::IOBuf::Block* p = butil::iobuf::get_tls_block_head();
111 112 113
        size_t n = 0;
        while (p) {
            ASSERT_TRUE(s_set.seek(p)) << "Memory leak: " << p;
114
            p = butil::iobuf::get_portal_next(p);
115 116 117
            ++n;
        }
        ASSERT_EQ(n, s_set.size());
gejun's avatar
gejun committed
118
        ASSERT_EQ(n, (size_t)butil::iobuf::get_tls_block_count());
119 120 121 122 123 124 125 126 127 128 129 130 131 132
    }
}

class IOBufTest : public ::testing::Test{
protected:
    IOBufTest(){};
    virtual ~IOBufTest(){};
    virtual void SetUp() {
    };
    virtual void TearDown() {
        check_memory_leak();
    };
};

133
std::string to_str(const butil::IOBuf& p) {
134 135 136 137 138 139
    return p.to_string();
}

TEST_F(IOBufTest, append_zero) {
    int fds[2];
    ASSERT_EQ(0, pipe(fds));
140
    butil::IOPortal p;
141 142 143 144 145 146 147 148
    ASSERT_EQ(0, p.append_from_file_descriptor(fds[0], 0));
    ASSERT_EQ(0, close(fds[0]));
    ASSERT_EQ(0, close(fds[1]));
}

TEST_F(IOBufTest, pop_front) {
    install_debug_allocator();

149
    butil::IOBuf buf;
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    ASSERT_EQ(0UL, buf.pop_front(1));   // nothing happened

    std::string s = "hello";
    buf.append(s);
    ASSERT_EQ(s, to_str(buf));
    ASSERT_EQ(0UL, buf.pop_front(0));   // nothing happened
    ASSERT_EQ(s, to_str(buf));

    ASSERT_EQ(1UL, buf.pop_front(1));
    s.erase(0, 1);
    ASSERT_EQ(s, to_str(buf));
    ASSERT_EQ(s.length(), buf.length());
    ASSERT_FALSE(buf.empty());

    ASSERT_EQ(s.length(), buf.pop_front(INT_MAX));
    s.clear();
    ASSERT_EQ(s, to_str(buf));
    ASSERT_EQ(0UL, buf.length());
    ASSERT_TRUE(buf.empty());

170
    for (size_t i = 0; i < DEFAULT_PAYLOAD * 3/2; ++i) {
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
        s.push_back(i);
    }
    buf.append(s);
    ASSERT_EQ(1UL, buf.pop_front(1));
    s.erase(0, 1);
    ASSERT_EQ(s, to_str(buf));
    ASSERT_EQ(s.length(), buf.length());
    ASSERT_FALSE(buf.empty());

    ASSERT_EQ(s.length(), buf.pop_front(INT_MAX));
    s.clear();
    ASSERT_EQ(s, to_str(buf));
    ASSERT_EQ(0UL, buf.length());
    ASSERT_TRUE(buf.empty());
}

TEST_F(IOBufTest, pop_back) {
    install_debug_allocator();

190
    butil::IOBuf buf;
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
    ASSERT_EQ(0UL, buf.pop_back(1));   // nothing happened

    std::string s = "hello";
    buf.append(s);
    ASSERT_EQ(s, to_str(buf));
    ASSERT_EQ(0UL, buf.pop_back(0));   // nothing happened
    ASSERT_EQ(s, to_str(buf));

    ASSERT_EQ(1UL, buf.pop_back(1));
    s.resize(s.size() - 1);
    ASSERT_EQ(s, to_str(buf));
    ASSERT_EQ(s.length(), buf.length());
    ASSERT_FALSE(buf.empty());

    ASSERT_EQ(s.length(), buf.pop_back(INT_MAX));
    s.clear();
    ASSERT_EQ(s, to_str(buf));
    ASSERT_EQ(0UL, buf.length());
    ASSERT_TRUE(buf.empty());

211
    for (size_t i = 0; i < DEFAULT_PAYLOAD * 3/2; ++i) {
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        s.push_back(i);
    }
    buf.append(s);
    ASSERT_EQ(1UL, buf.pop_back(1));
    s.resize(s.size() - 1);
    ASSERT_EQ(s, to_str(buf));
    ASSERT_EQ(s.length(), buf.length());
    ASSERT_FALSE(buf.empty());

    ASSERT_EQ(s.length(), buf.pop_back(INT_MAX));
    s.clear();
    ASSERT_EQ(s, to_str(buf));
    ASSERT_EQ(0UL, buf.length());
    ASSERT_TRUE(buf.empty());
}

TEST_F(IOBufTest, append) {
    install_debug_allocator();

231
    butil::IOBuf b;
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
    ASSERT_EQ(0UL, b.length());
    ASSERT_TRUE(b.empty());
    ASSERT_EQ(-1, b.append(NULL));
    ASSERT_EQ(0, b.append(""));
    ASSERT_EQ(0, b.append(std::string()));
    ASSERT_EQ(-1, b.append(NULL, 1));
    ASSERT_EQ(0, b.append("dummy", 0));
    ASSERT_EQ(0UL, b.length());
    ASSERT_TRUE(b.empty());
    ASSERT_EQ(0, b.append("1"));
    ASSERT_EQ(1UL, b.length());
    ASSERT_FALSE(b.empty());
    ASSERT_EQ("1", to_str(b));
    const std::string s = "22";
    ASSERT_EQ(0, b.append(s));
    ASSERT_EQ(3UL, b.length());
    ASSERT_FALSE(b.empty());
    ASSERT_EQ("122", to_str(b));
}

TEST_F(IOBufTest, appendv) {
    install_debug_allocator();

255
    butil::IOBuf b;
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
    const_iovec vec[] = { {"hello1", 6}, {" world1", 7},
                          {"hello2", 6}, {" world2", 7},
                          {"hello3", 6}, {" world3", 7},
                          {"hello4", 6}, {" world4", 7},
                          {"hello5", 6}, {" world5", 7} };
    ASSERT_EQ(0, b.appendv(vec, arraysize(vec)));
    ASSERT_EQ("hello1 world1hello2 world2hello3 world3hello4 world4hello5 world5",
              b.to_string());

    // Make some iov_len shorter to test if iov_len works.
    vec[2].iov_len = 4;  // "hello2"
    vec[5].iov_len = 3;  // " world3"
    b.clear();
    ASSERT_EQ(0, b.appendv(vec, arraysize(vec)));
    ASSERT_EQ("hello1 world1hell world2hello3 wohello4 world4hello5 world5",
              b.to_string());

    // Append some long stuff.
274
    const size_t full_len = DEFAULT_PAYLOAD * 9;
275 276 277 278 279
    char* str = (char*)malloc(full_len);
    ASSERT_TRUE(str);
    const size_t len1 = full_len / 6;
    const size_t len2 = full_len / 3;
    const size_t len3 = full_len - len1 - len2;
280 281 282
    ASSERT_GT(len1, (size_t)DEFAULT_PAYLOAD);
    ASSERT_GT(len2, (size_t)DEFAULT_PAYLOAD);
    ASSERT_GT(len3, (size_t)DEFAULT_PAYLOAD);
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    ASSERT_EQ(full_len, len1 + len2 + len3);

    for (size_t i = 0; i < full_len; ++i) {
        str[i] = i * 7;
    }
    const_iovec vec2[] = {{str, len1},
                          {str + len1, len2},
                          {str + len1 + len2, len3}};
    b.clear();
    ASSERT_EQ(0, b.appendv(vec2, arraysize(vec2)));
    ASSERT_EQ(full_len, b.size());
    ASSERT_EQ(0, memcmp(str, b.to_string().data(), full_len));
}

TEST_F(IOBufTest, reserve) {
298 299
    butil::IOBuf b;
    ASSERT_EQ(butil::IOBuf::INVALID_AREA, b.reserve(0));
300
    const size_t NRESERVED1 = 5;
301 302
    const butil::IOBuf::Area a1 = b.reserve(NRESERVED1);
    ASSERT_TRUE(a1 != butil::IOBuf::INVALID_AREA);
303 304 305 306
    ASSERT_EQ(NRESERVED1, b.size());
    b.append("hello world");
    ASSERT_EQ(0, b.unsafe_assign(a1, "prefix")); // `x' will not be copied
    ASSERT_EQ("prefihello world", b.to_string());
gejun's avatar
gejun committed
307
    ASSERT_EQ((size_t)16, b.size());
308 309

    // pop/append sth. from back-side and assign again.
gejun's avatar
gejun committed
310
    ASSERT_EQ((size_t)5, b.pop_back(5));
311 312 313 314 315 316
    ASSERT_EQ("prefihello ", b.to_string());
    b.append("blahblahfoobar");
    ASSERT_EQ(0, b.unsafe_assign(a1, "goodorbad")); // `x' will not be copied
    ASSERT_EQ("goodohello blahblahfoobar", b.to_string());

    // append a long string and assign again.
317
    std::string s1(DEFAULT_PAYLOAD * 3, '\0');
318 319 320
    for (size_t i = 0; i < s1.size(); ++i) {
        s1[i] = i * 7;
    }
321
    ASSERT_EQ(DEFAULT_PAYLOAD * 3, s1.size());
322 323 324 325 326 327 328 329 330 331 332
    // remove everything after reserved area
    ASSERT_GE(b.size(), NRESERVED1);
    b.pop_back(b.size() - NRESERVED1);
    ASSERT_EQ(NRESERVED1, b.size());
    b.append(s1);
    ASSERT_EQ(0, b.unsafe_assign(a1, "appleblahblah"));
    ASSERT_EQ("apple" + s1, b.to_string());

    // Reserve long
    b.pop_back(b.size() - NRESERVED1);
    ASSERT_EQ(NRESERVED1, b.size());
333
    const size_t NRESERVED2 = DEFAULT_PAYLOAD * 3;
334
    const butil::IOBuf::Area a2 = b.reserve(NRESERVED2);
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    ASSERT_EQ(NRESERVED1 + NRESERVED2, b.size());
    b.append(s1);
    ASSERT_EQ(NRESERVED1 + NRESERVED2 + s1.size(), b.size());
    std::string s2(NRESERVED2, 0);
    for (size_t i = 0; i < s2.size(); ++i) {
        s2[i] = i * 13;
    }
    ASSERT_EQ(NRESERVED2, s2.size());
    ASSERT_EQ(0, b.unsafe_assign(a2, s2.data()));
    ASSERT_EQ("apple" + s2 + s1, b.to_string());
    ASSERT_EQ(0, b.unsafe_assign(a1, "orangeblahblah"));
    ASSERT_EQ("orang" + s2 + s1, b.to_string());
}

struct FakeBlock {
    int nshared;
    FakeBlock() : nshared(1) {}
};

TEST_F(IOBufTest, iobuf_as_queue) {
    install_debug_allocator();

357 358 359
    // If INITIAL_CAP gets bigger, creating butil::IOBuf::Block are very
    // small. Since We don't access butil::IOBuf::Block::data in this case.
    // We replace butil::IOBuf::Block with FakeBlock with only nshared (in
360
    // the same offset)
361
    FakeBlock* blocks[butil::IOBuf::INITIAL_CAP+16];
362
    const size_t NBLOCKS = ARRAY_SIZE(blocks);
363
    butil::IOBuf::BlockRef r[NBLOCKS];
364 365 366 367 368
    const size_t LENGTH = 7UL;
    for (size_t i = 0; i < NBLOCKS; ++i) {
        ASSERT_TRUE((blocks[i] = new FakeBlock));
        r[i].offset = 1;
        r[i].length = LENGTH;
369
        r[i].block = (butil::IOBuf::Block*)blocks[i];
370 371
    }

372
    butil::IOBuf p;
373 374 375 376 377 378 379 380 381 382 383 384 385
    
    // Empty
    ASSERT_EQ(0UL, p._ref_num());
    ASSERT_EQ(-1, p._pop_front_ref());
    ASSERT_EQ(0UL, p.length());

    // Add one ref
    p._push_back_ref(r[0]);
    ASSERT_EQ(1UL, p._ref_num());
    ASSERT_EQ(LENGTH, p.length());
    ASSERT_EQ(r[0], p._front_ref());
    ASSERT_EQ(r[0], p._back_ref());
    ASSERT_EQ(r[0], p._ref_at(0));
386
    ASSERT_EQ(2, butil::iobuf::block_shared_count(r[0].block));
387 388 389 390 391 392 393 394 395

    // Add second ref
    p._push_back_ref(r[1]);
    ASSERT_EQ(2UL, p._ref_num());
    ASSERT_EQ(LENGTH*2, p.length());
    ASSERT_EQ(r[0], p._front_ref());
    ASSERT_EQ(r[1], p._back_ref());
    ASSERT_EQ(r[0], p._ref_at(0));
    ASSERT_EQ(r[1], p._ref_at(1));
396
    ASSERT_EQ(2, butil::iobuf::block_shared_count(r[1].block));
397 398 399 400 401 402 403 404 405

    // Pop a ref
    ASSERT_EQ(0, p._pop_front_ref());
    ASSERT_EQ(1UL, p._ref_num());
    ASSERT_EQ(LENGTH, p.length());
    
    ASSERT_EQ(r[1], p._front_ref());
    ASSERT_EQ(r[1], p._back_ref());
    ASSERT_EQ(r[1], p._ref_at(0));
406
    //ASSERT_EQ(1, butil::iobuf::block_shared_count(r[0].block));
407 408 409 410 411 412 413 414

    // Pop second
    ASSERT_EQ(0, p._pop_front_ref());
    ASSERT_EQ(0UL, p._ref_num());
    ASSERT_EQ(0UL, p.length());
    //ASSERT_EQ(1, r[1].block->nshared);
    
    // Add INITIAL_CAP+2 refs, r[0] and r[1] are used, don't use again
415
    for (size_t i = 0; i < butil::IOBuf::INITIAL_CAP+2; ++i) {
416 417 418 419 420 421 422 423
        p._push_back_ref(r[i+2]);
        ASSERT_EQ(i+1, p._ref_num());
        ASSERT_EQ(p._ref_num()*LENGTH, p.length());
        ASSERT_EQ(r[2], p._front_ref()) << i;
        ASSERT_EQ(r[i+2], p._back_ref());
        for (size_t j = 0; j <= i; j+=std::max(1UL, i/20) /*not check all*/) {
            ASSERT_EQ(r[j+2], p._ref_at(j));
        }
424
        ASSERT_EQ(2, butil::iobuf::block_shared_count(r[i+2].block));
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
    }

    // Pop them all
    const size_t saved_ref_num = p._ref_num();
    while (p._ref_num() >= 2UL) {
        const size_t last_ref_num = p._ref_num();
        ASSERT_EQ(0, p._pop_front_ref());
        ASSERT_EQ(last_ref_num, p._ref_num()+1);
        ASSERT_EQ(p._ref_num()*LENGTH, p.length());
        const size_t f = saved_ref_num - p._ref_num() + 2;
        ASSERT_EQ(r[f], p._front_ref());
        ASSERT_EQ(r[saved_ref_num+1], p._back_ref());
        for (size_t j = 0; j < p._ref_num(); j += std::max(1UL, p._ref_num()/20)) {
            ASSERT_EQ(r[j+f], p._ref_at(j));
        }
        //ASSERT_EQ(1, r[f-1].block->nshared);
    }
    
    ASSERT_EQ(1ul, p._ref_num());
    // Pop last one
    ASSERT_EQ(0, p._pop_front_ref());
    ASSERT_EQ(0UL, p._ref_num());
    ASSERT_EQ(0UL, p.length());
    //ASSERT_EQ(1, r[saved_ref_num+1].block->nshared);

    // Delete blocks
    for (size_t i = 0; i < NBLOCKS; ++i) {
        delete blocks[i];
    }
}

TEST_F(IOBufTest, iobuf_sanity) {
    install_debug_allocator();
        
459 460
    LOG(INFO) << "sizeof(butil::IOBuf)=" << sizeof(butil::IOBuf)
              << " sizeof(IOPortal)=" << sizeof(butil::IOPortal);
461
    
462
    butil::IOBuf b1;
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
    std::string s1 = "hello world";
    const char c1 = 'A';
    const std::string s2 = "too simple";
    std::string s1c = s1;
    s1c.erase(0, 1);

    // Append a c-std::string
    ASSERT_EQ(0, b1.append(s1.c_str()));
    ASSERT_EQ(s1.length(), b1.length());
    ASSERT_EQ(s1, to_str(b1));
    ASSERT_EQ(1UL, b1._ref_num());

    // Append a char
    ASSERT_EQ(0, b1.push_back(c1));
    ASSERT_EQ(s1.length() + 1, b1.length());
    ASSERT_EQ(s1+c1, to_str(b1));
    ASSERT_EQ(1UL, b1._ref_num());
    
    // Append a std::string
    ASSERT_EQ(0, b1.append(s2));
    ASSERT_EQ(s1.length() + 1 + s2.length(), b1.length());
    ASSERT_EQ(s1+c1+s2, to_str(b1));
    ASSERT_EQ(1UL, b1._ref_num());

    // Pop first char
    ASSERT_EQ(1UL, b1.pop_front(1));
    ASSERT_EQ(1UL, b1._ref_num());
    ASSERT_EQ(s1.length() + s2.length(), b1.length());
    ASSERT_EQ(s1c+c1+s2, to_str(b1));

    // Pop all
    ASSERT_EQ(0UL, b1.pop_front(0));
    ASSERT_EQ(s1.length() + s2.length(), b1.pop_front(b1.length()+1));
    ASSERT_TRUE(b1.empty());
    ASSERT_EQ(0UL, b1.length());
    ASSERT_EQ(0UL, b1._ref_num());
    ASSERT_EQ("", to_str(b1));

    // Restore
    ASSERT_EQ(0, b1.append(s1.c_str()));
    ASSERT_EQ(0, b1.push_back(c1));
    ASSERT_EQ(0, b1.append(s2));
    
    // Cut first char
507
    butil::IOBuf p;
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
    b1.cutn(&p, 0);
    b1.cutn(&p, 1);
    ASSERT_EQ(s1.substr(0, 1), to_str(p));
    ASSERT_EQ(s1c+c1+s2, to_str(b1));

    // Cut another two and append to p
    b1.cutn(&p, 2);
    ASSERT_EQ(s1.substr(0, 3), to_str(p));
    std::string s1d = s1;
    s1d.erase(0, 3);
    ASSERT_EQ(s1d+c1+s2, to_str(b1));

    // Clear
    b1.clear();
    ASSERT_TRUE(b1.empty());
    ASSERT_EQ(0UL, b1.length());
    ASSERT_EQ(0UL, b1._ref_num());
    ASSERT_EQ("", to_str(b1));
    ASSERT_EQ(s1.substr(0, 3), to_str(p));    
}

TEST_F(IOBufTest, copy_and_assign) {
    install_debug_allocator();

gejun's avatar
gejun committed
532
    const size_t TARGET_SIZE = butil::IOBuf::DEFAULT_BLOCK_SIZE * 2;
533
    butil::IOBuf buf0;
534 535 536 537
    buf0.append("hello");
    ASSERT_EQ(1u, buf0._ref_num());

    // Copy-construct from SmallView
538
    butil::IOBuf buf1 = buf0;
539 540 541 542 543 544 545 546
    ASSERT_EQ(1u, buf1._ref_num());
    ASSERT_EQ(buf0, buf1);

    buf1.resize(TARGET_SIZE, 'z');
    ASSERT_LT(2u, buf1._ref_num());
    ASSERT_EQ(TARGET_SIZE, buf1.size());

    // Copy-construct from BigView 
547
    butil::IOBuf buf2 = buf1;
548 549 550
    ASSERT_EQ(buf1, buf2);

    // assign BigView to SmallView
551
    butil::IOBuf buf3;
552 553 554 555
    buf3 = buf1;
    ASSERT_EQ(buf1, buf3);

    // assign BigView to BigView
556
    butil::IOBuf buf4;
557 558 559 560 561 562 563 564 565 566
    buf4.resize(TARGET_SIZE, 'w');
    ASSERT_NE(buf1, buf4);
    buf4 = buf1;
    ASSERT_EQ(buf1, buf4);
}

TEST_F(IOBufTest, compare) {
    install_debug_allocator();

    const char* SEED = "abcdefghijklmnqopqrstuvwxyz";
567
    butil::IOBuf seedbuf;
568 569
    seedbuf.append(SEED);
    const int REP = 100;
570
    butil::IOBuf b1;
571 572 573 574
    for (int i = 0; i < REP; ++i) {
        b1.append(seedbuf);
        b1.append(SEED);
    }
575
    butil::IOBuf b2;
576 577 578 579 580
    for (int i = 0; i < REP * 2; ++i) {
        b2.append(SEED);
    }
    ASSERT_EQ(b1, b2);

581
    butil::IOBuf b3 = b2;
582 583 584 585 586 587 588 589 590 591 592

    b2.push_back('0');
    ASSERT_NE(b1, b2);
    ASSERT_EQ(b1, b3);
    
    b1.clear();
    b2.clear();
    ASSERT_EQ(b1, b2);
}

TEST_F(IOBufTest, append_and_cut_it_all) {
593
    butil::IOBuf b;
594 595 596 597 598
    const size_t N = 32768UL;
    for (size_t i = 0; i < N; ++i) {
        ASSERT_EQ(0, b.push_back(i));
    }
    ASSERT_EQ(N, b.length());
599
    butil::IOBuf p;
600 601 602 603 604 605
    b.cutn(&p, N);
    ASSERT_TRUE(b.empty());
    ASSERT_EQ(N, p.length());
}

TEST_F(IOBufTest, copy_to) {
606
    butil::IOBuf b;
607 608 609 610 611 612
    const std::string seed = "abcdefghijklmnopqrstuvwxyz";
    std::string src;
    for (size_t i = 0; i < 1000; ++i) {
        src.append(seed);
    }
    b.append(src);
613
    ASSERT_GT(b.size(), DEFAULT_PAYLOAD);
614 615 616 617 618 619 620 621 622
    std::string s1;
    ASSERT_EQ(src.size(), b.copy_to(&s1));
    ASSERT_EQ(src, s1);

    std::string s2;
    ASSERT_EQ(32u, b.copy_to(&s2, 32));
    ASSERT_EQ(src.substr(0, 32), s2);

    std::string s3;
623 624
    const std::string expected = src.substr(DEFAULT_PAYLOAD - 1, 33);
    ASSERT_EQ(33u, b.copy_to(&s3, 33, DEFAULT_PAYLOAD - 1));
625 626
    ASSERT_EQ(expected, s3);

627
    ASSERT_EQ(33u, b.append_to(&s3, 33, DEFAULT_PAYLOAD - 1));
628 629
    ASSERT_EQ(expected + expected, s3);

630
    butil::IOBuf b1;
631 632 633
    ASSERT_EQ(src.size(), b.append_to(&b1));
    ASSERT_EQ(src, b1.to_string());

634
    butil::IOBuf b2;
635 636 637
    ASSERT_EQ(32u, b.append_to(&b2, 32));
    ASSERT_EQ(src.substr(0, 32), b2.to_string());

638
    butil::IOBuf b3;
639
    ASSERT_EQ(33u, b.append_to(&b3, 33, DEFAULT_PAYLOAD - 1));
640 641
    ASSERT_EQ(expected, b3.to_string());

642
    ASSERT_EQ(33u, b.append_to(&b3, 33, DEFAULT_PAYLOAD - 1));
643 644 645 646 647 648
    ASSERT_EQ(expected + expected, b3.to_string());
}

TEST_F(IOBufTest, cut_by_single_text_delim) {
    install_debug_allocator();
    
649 650 651
    butil::IOBuf b;
    butil::IOBuf p;
    std::vector<butil::IOBuf> ps;
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
    std::string s1 = "1234567\n12\n\n2567";
    ASSERT_EQ(0, b.append(s1));
    ASSERT_EQ(s1.length(), b.length());
    
    for (; b.cut_until(&p, "\n") == 0; ) {
        ps.push_back(p);
        p.clear();
    }
    
    ASSERT_EQ(3UL, ps.size());
    ASSERT_EQ("1234567", to_str(ps[0]));
    ASSERT_EQ("12", to_str(ps[1]));
    ASSERT_EQ("", to_str(ps[2]));
    ASSERT_EQ("2567", to_str(b));

    b.append("\n");
    ASSERT_EQ(0, b.cut_until(&p, "\n"));
    ASSERT_EQ("2567", to_str(p));
    ASSERT_EQ("", to_str(b));
}

TEST_F(IOBufTest, cut_by_multiple_text_delim) {
    install_debug_allocator();
    
676 677 678
    butil::IOBuf b;
    butil::IOBuf p;
    std::vector<butil::IOBuf> ps;
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
    std::string s1 = "\r\n1234567\r\n12\r\n\n\r2567";
    ASSERT_EQ(0, b.append(s1));
    ASSERT_EQ(s1.length(), b.length());
    
    for (; b.cut_until(&p, "\r\n") == 0; ) {
        ps.push_back(p);
        p.clear();
    }
    
    ASSERT_EQ(3UL, ps.size());
    ASSERT_EQ("", to_str(ps[0]));
    ASSERT_EQ("1234567", to_str(ps[1]));
    ASSERT_EQ("12", to_str(ps[2]));
    ASSERT_EQ("\n\r2567", to_str(b));

    b.append("\r\n");
    ASSERT_EQ(0, b.cut_until(&p, "\r\n"));
    ASSERT_EQ("\n\r2567", to_str(p));
    ASSERT_EQ("", to_str(b));
}

TEST_F(IOBufTest, append_a_lot_and_cut_them_all) {
    install_debug_allocator();
    
703 704
    butil::IOBuf b;
    butil::IOBuf p;
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
    std::string s1 = "12345678901234567";
    const size_t N = 10000;
    for (size_t i= 0; i < N; ++i) {
        b.append(s1);
    }
    ASSERT_EQ(N*s1.length(), b.length());

    while (b.length() >= 7) {
        b.cutn(&p, 7);
    }
    size_t remain = s1.length()*N % 7;
    ASSERT_EQ(remain, b.length());
    ASSERT_EQ(s1.substr(s1.length() - remain, remain), to_str(b));
    ASSERT_EQ(s1.length()*N/7*7, p.length());
}

TEST_F(IOBufTest, cut_into_fd_tiny) {
    install_debug_allocator();
    
724
    butil::IOPortal b1, b2;
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
    std::string ref;
    int fds[2];

    for (int j = 10; j > 0; --j) {
        ref.push_back(j);
    }
    b1.append(ref);
    ASSERT_EQ(1UL, b1.pop_front(1));
    ref.erase(0, 1);
    ASSERT_EQ(ref, to_str(b1));
    LOG(INFO) << "ref.size=" << ref.size();
    
    //ASSERT_EQ(0, pipe(fds));
    ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));

740 741
    butil::make_non_blocking(fds[0]);
    butil::make_non_blocking(fds[1]);
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
    
    while (!b1.empty() || b2.length() != ref.length()) {
        size_t b1len = b1.length(), b2len = b2.length();
        errno = 0;
        printf("b1.length=%lu - %ld (%m), ",
               b1len, b1.cut_into_file_descriptor(fds[1]));
        printf("b2.length=%lu + %ld (%m)\n",
               b2len, b2.append_from_file_descriptor(fds[0], LONG_MAX));
    }
    printf("b1.length=%lu, b2.length=%lu\n", b1.length(), b2.length());

    ASSERT_EQ(ref, to_str(b2));
    
    close(fds[0]);
    close(fds[1]);
}

TEST_F(IOBufTest, cut_multiple_into_fd_tiny) {
    install_debug_allocator();
    
762 763
    butil::IOBuf* b1[10];
    butil::IOPortal b2;
764 765 766 767 768 769 770 771 772
    std::string ref;
    int fds[2];

    for (size_t j = 0; j < ARRAY_SIZE(b1); ++j) {
        std::string s;
        for (int i = 10; i > 0; --i) {
            s.push_back(j * 10 + i);
        }
        ref.append(s);
773
        butil::IOPortal* b = new butil::IOPortal();
774 775 776 777 778
        b->append(s);
        b1[j] = b;
    }
    
    ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
779 780
    butil::make_non_blocking(fds[0]);
    butil::make_non_blocking(fds[1]);
781 782
    
    ASSERT_EQ((ssize_t)ref.length(),
783
              butil::IOBuf::cut_multiple_into_file_descriptor(
784 785 786
                  fds[1], b1, ARRAY_SIZE(b1)));
    for (size_t j = 0; j < ARRAY_SIZE(b1); ++j) {
        ASSERT_TRUE(b1[j]->empty());
787
        delete (butil::IOPortal*)b1[j];
788 789 790 791 792 793 794 795 796 797 798 799 800
        b1[j] = NULL;
    }
    ASSERT_EQ((ssize_t)ref.length(),
              b2.append_from_file_descriptor(fds[0], LONG_MAX));
    ASSERT_EQ(ref, to_str(b2));
    
    close(fds[0]);
    close(fds[1]);
}

TEST_F(IOBufTest, cut_into_fd_a_lot_of_data) {
    install_debug_allocator();

801
    butil::IOPortal b0, b1, b2;
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
    std::string s, ref;
    int fds[2];

    for (int j = rand()%7777+300000; j > 0; --j) {
        ref.push_back(j);
        s.push_back(j);

        if (s.length() == 1024UL || j == 1) {
            b0.append(s);
            ref.append("tailing");
            b0.cutn(&b1, b0.length());
            ASSERT_EQ(0, b1.append("tailing"));
            s.clear();
        }
    }

    ASSERT_EQ(ref.length(), b1.length());
    ASSERT_EQ(ref, to_str(b1));
    ASSERT_TRUE(b0.empty());
    LOG(INFO) << "ref.size=" << ref.size();

    //ASSERT_EQ(0, pipe(fds));
    ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
825 826
    butil::make_non_blocking(fds[0]);
    butil::make_non_blocking(fds[1]);
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
    const int sockbufsize = 16 * 1024 - 17;
    ASSERT_EQ(0, setsockopt(fds[1], SOL_SOCKET, SO_SNDBUF,
                            (const char*)&sockbufsize, sizeof(int)));
    ASSERT_EQ(0, setsockopt(fds[0], SOL_SOCKET, SO_RCVBUF,
                            (const char*)&sockbufsize, sizeof(int)));
    
    while (!b1.empty() || b2.length() != ref.length()) {
        size_t b1len = b1.length(), b2len = b2.length();
        errno = 0;
        printf("b1.length=%lu - %ld (%m), ", b1len, b1.cut_into_file_descriptor(fds[1]));
        printf("b2.length=%lu + %ld (%m)\n", b2len, b2.append_from_file_descriptor(fds[0], LONG_MAX));
    }
    printf("b1.length=%lu, b2.length=%lu\n", b1.length(), b2.length());

    ASSERT_EQ(ref, to_str(b2));
    
    close(fds[0]);
    close(fds[1]);
}

TEST_F(IOBufTest, cut_by_delim_perf) {
848
    butil::iobuf::reset_blockmem_allocate_and_deallocate();
849
    
850 851 852
    butil::IOBuf b;
    butil::IOBuf p;
    std::vector<butil::IOBuf> ps;
853 854 855 856 857 858 859
    std::string s1 = "123456789012345678901234567890\n";
    const size_t N = 100000;
    for (size_t i = 0; i < N; ++i) {
        ASSERT_EQ(0, b.append(s1));
    }
    ASSERT_EQ(N * s1.length(), b.length());

860
    butil::Timer t;
861 862 863 864 865 866 867 868 869 870 871 872 873 874
    //ProfilerStart("cutd.prof");
    t.start();
    for (; b.cut_until(&p, "\n") == 0; ) { }
    t.stop();
    //ProfilerStop();

    LOG(INFO) << "IOPortal::cut_by_delim takes "
              << t.n_elapsed()/N << "ns, tp="
              << s1.length() * N * 1000.0 / t.n_elapsed () << "MB/s";
    show_prof_and_rm("test_iobuf", "cutd.prof", 10);
}


TEST_F(IOBufTest, cut_perf) {
875
    butil::iobuf::reset_blockmem_allocate_and_deallocate();
876
    
877 878
    butil::IOBuf b;
    butil::IOBuf p;
879 880
    const size_t length = 60000000UL;
    const size_t REP = 10;
881
    butil::Timer t;
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
    std::string s = "1234567890";
    const bool push_char = false;

    if (!push_char) {
        //ProfilerStart("iobuf_append.prof");
        t.start();
        for (size_t j = 0; j < REP; ++j) {
            b.clear();
            for (size_t i = 0; i < length/s.length(); ++i) {
                b.append(s);
            }
        }
        t.stop();
        //ProfilerStop();
        LOG(INFO) << "IOPortal::append(std::string_" << s.length() << ") takes "
                  << t.n_elapsed() * s.length() / length / REP << "ns, tp="
                  << REP * length * 1000.0 / t.n_elapsed () << "MB/s";
    } else {
        //ProfilerStart("iobuf_pushback.prof");
        t.start();
        for (size_t i = 0; i < length; ++i) {
            b.push_back(i);
        }
        t.stop();
        //ProfilerStop();
        LOG(INFO) << "IOPortal::push_back(char) takes "
                  << t.n_elapsed() / length << "ns, tp="
                  << length * 1000.0 / t.n_elapsed () << "MB/s";
    }

    ASSERT_EQ(length, b.length());

    size_t w[3] = { 16, 128, 1024 };
    //char name[32];

    for (size_t i = 0; i < ARRAY_SIZE(w); ++i) {
        // snprintf(name, sizeof(name), "iobuf_cut%lu.prof", w[i]);
        // ProfilerStart(name);
    
        t.start ();
        while (b.length() >= w[i]+12) {
            b.cutn(&p, 12);
            b.cutn(&p, w[i]);
        }
        t.stop ();

        //ProfilerStop();
        
        LOG(INFO) << "IOPortal::cutn(12+" << w[i] << ") takes "
                  << t.n_elapsed()*(w[i]+12)/length << "ns, tp="
                  << length * 1000.0 / t.n_elapsed () << "MB/s";
    
        ASSERT_LT(b.length(), w[i]+12);

        t.start();
        b.append(p);
        t.stop();
939
        LOG(INFO) << "IOPortal::append(butil::IOBuf) takes "
940 941 942 943 944 945 946 947 948 949 950 951
                  << t.n_elapsed ()/p._ref_num() << "ns, tp="
                  << length * 1000.0 / t.n_elapsed () << "MB/s";
        
        p.clear();
        ASSERT_EQ(length, b.length());
    }

    show_prof_and_rm("test_iobuf", "./iobuf_append.prof", 10);
    show_prof_and_rm("test_iobuf", "./iobuf_pushback.prof", 10);
}

TEST_F(IOBufTest, append_store_append_cut) {
952
    butil::iobuf::reset_blockmem_allocate_and_deallocate();
953 954 955 956 957 958 959
    
    std::string ref;
    ref.resize(rand()%376813+19777777);
    for (size_t j = 0; j < ref.size(); ++j) {
        ref[j] = j;
    }
    
960 961
    butil::IOPortal b1, b2;
    std::vector<butil::IOBuf> ps;
962 963
    ssize_t nr;
    size_t HINT = 16*1024UL;
964
    butil::Timer t;
965 966 967 968 969 970 971
    size_t w[3] = { 16, 128, 1024 };
    char name[64];
    char profname[64];
    char cmd[512];
    bool write_to_dev_null = true;
    size_t nappend, ncut;

972
    butil::TempFile f;
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
    ASSERT_EQ(0, f.save_bin(ref.data(), ref.length()));
    
    for (size_t i = 0; i < ARRAY_SIZE(w); ++i) {
        ps.reserve(ref.size()/(w[i]+12) + 1);
        // LOG(INFO) << "ps.cap=" << ps.capacity();

        const int ifd = open(f.fname(), O_RDONLY);
        ASSERT_TRUE(ifd > 0);
        if (write_to_dev_null) {
            snprintf(name, sizeof(name), "/dev/null");
        } else {
            snprintf(name, sizeof(name), "iobuf_asac%lu.output", w[i]);
            snprintf(cmd, sizeof(cmd), "cmp %s %s", f.fname(), name);
        }
        const int ofd = open(name, O_CREAT | O_WRONLY, 0666);
        ASSERT_TRUE(ofd > 0) << strerror(errno);
        snprintf(profname, sizeof(profname), "iobuf_asac%lu.prof", w[i]);
        
        //ProfilerStart(profname);
        t.start();

        nappend = ncut = 0;
        while ((nr = b1.append_from_file_descriptor(ifd, HINT)) > 0) {
            ++nappend;
            while (b1.length() >= w[i] + 12) {
998
                butil::IOBuf p;
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
                b1.cutn(&p, 12);
                b1.cutn(&p, w[i]);
                ps.push_back(p);
            }
        }
        for (size_t j = 0; j < ps.size(); ++j) {
            b2.append(ps[j]);
            if (b2.length() >= HINT) {
                b2.cut_into_file_descriptor(ofd);
            }
        }
        b2.cut_into_file_descriptor(ofd);
        b1.cut_into_file_descriptor(ofd);

        close(ifd);
        close(ofd);
        t.stop();
        //ProfilerStop();

        ASSERT_TRUE(b1.empty());
        ASSERT_TRUE(b2.empty());
        //LOG(INFO) << "ps.size=" << ps.size();
        ps.clear();
        LOG(INFO) << "Bandwidth of append(" << f.fname() << ")->cut(12+" << w[i]
                  << ")->store->append->cut(" << name << ") is "
                  << ref.length() * 1000.0 / t.n_elapsed () << "MB/s";

        if (!write_to_dev_null) {
            ASSERT_EQ(0, system(cmd));
        }
        remove(name);
    }

    for (size_t i = 0; i < ARRAY_SIZE(w); ++i) {
        snprintf(name, sizeof(name), "iobuf_asac%lu.prof", w[i]);
        show_prof_and_rm("test_iobuf", name, 10);
    }
}

TEST_F(IOBufTest, conversion_with_protobuf) {
    const int REP = 1000;
    proto::Misc m1;
    m1.set_required_enum(proto::CompressTypeGzip);
    m1.set_required_uint64(0xdeadbeef);
    m1.set_optional_uint64(10000);
    m1.set_required_string("hello iobuf");
    m1.set_optional_string("hello iobuf again");
    for (int i = 0; i < REP; ++i) {
        char buf[16];
        snprintf(buf, sizeof(buf), "value%d", i);
        m1.add_repeated_string(buf);
    }
    m1.set_required_bool(true);
    m1.set_required_int32(0xbeefdead);

1054
    butil::IOBuf buf;
1055 1056
    const std::string header("just-make-sure-wrapper-does-not-clear-IOBuf");
    ASSERT_EQ(0, buf.append(header));
1057
    butil::IOBufAsZeroCopyOutputStream out_wrapper(&buf);
1058 1059 1060 1061 1062 1063
    ASSERT_EQ(0, out_wrapper.ByteCount());
    ASSERT_TRUE(m1.SerializeToZeroCopyStream(&out_wrapper));
    ASSERT_EQ((size_t)m1.ByteSize() + header.size(), buf.length());
    ASSERT_EQ(m1.ByteSize(), out_wrapper.ByteCount());

    ASSERT_EQ(header.size(), buf.pop_front(header.size()));
1064
    butil::IOBufAsZeroCopyInputStream in_wrapper(buf);
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    ASSERT_EQ(0, in_wrapper.ByteCount());
    {
        const void* dummy_blk = NULL;
        int dummy_size = 0;
        ASSERT_TRUE(in_wrapper.Next(&dummy_blk, &dummy_size));
        ASSERT_EQ(dummy_size, in_wrapper.ByteCount());
        in_wrapper.BackUp(1);
        ASSERT_EQ(dummy_size - 1, in_wrapper.ByteCount());
        const void* dummy_blk2 = NULL;
        int dummy_size2 = 0;
        ASSERT_TRUE(in_wrapper.Next(&dummy_blk2, &dummy_size2));
        ASSERT_EQ(1, dummy_size2);
        ASSERT_EQ((char*)dummy_blk + dummy_size - 1, (char*)dummy_blk2);
        ASSERT_EQ(dummy_size, in_wrapper.ByteCount());
        in_wrapper.BackUp(dummy_size);
        ASSERT_EQ(0, in_wrapper.ByteCount());
    }
    proto::Misc m2;
    ASSERT_TRUE(m2.ParseFromZeroCopyStream(&in_wrapper));
    ASSERT_EQ(m1.ByteSize(), in_wrapper.ByteCount());
    ASSERT_EQ(m2.ByteSize(), in_wrapper.ByteCount());
    
    ASSERT_EQ(m1.required_enum(), m2.required_enum());
    ASSERT_FALSE(m2.has_optional_enum());
    ASSERT_EQ(m1.required_uint64(), m2.required_uint64());
    ASSERT_TRUE(m2.has_optional_uint64());
    ASSERT_EQ(m1.optional_uint64(), m2.optional_uint64());
    ASSERT_EQ(m1.required_string(), m2.required_string());
    ASSERT_TRUE(m2.has_optional_string());
    ASSERT_EQ(m1.optional_string(), m2.optional_string());
    ASSERT_EQ(REP, m2.repeated_string_size());
    for (int i = 0; i < REP; ++i) {
        ASSERT_EQ(m1.repeated_string(i), m2.repeated_string(i));
    }
    ASSERT_EQ(m1.required_bool(), m2.required_bool());
    ASSERT_FALSE(m2.has_optional_bool());
    ASSERT_EQ(m1.required_int32(), m2.required_int32());
    ASSERT_FALSE(m2.has_optional_int32());
}

TEST_F(IOBufTest, extended_backup) {
    for (int i = 0; i < 2; ++i) {
        std::cout << "i=" << i << std::endl;
        // Consume the left TLS block so that cases are easier to check.
1109 1110 1111
        butil::iobuf::remove_tls_block_chain();
        butil::IOBuf src;
        const int BLKSIZE = (i == 0 ? 1024 : butil::IOBuf::DEFAULT_BLOCK_SIZE);
1112
        const int PLDSIZE = BLKSIZE - BLOCK_OVERHEAD;
1113 1114 1115
        butil::IOBufAsZeroCopyOutputStream out_stream1(&src, BLKSIZE);
        butil::IOBufAsZeroCopyOutputStream out_stream2(&src);
        butil::IOBufAsZeroCopyOutputStream & out_stream =
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
            (i == 0 ? out_stream1 : out_stream2);
        void* blk1 = NULL;
        int size1 = 0;
        ASSERT_TRUE(out_stream.Next(&blk1, &size1));
        ASSERT_EQ(PLDSIZE, size1);
        ASSERT_EQ(size1, out_stream.ByteCount());
        void* blk2 = NULL;
        int size2 = 0;
        ASSERT_TRUE(out_stream.Next(&blk2, &size2));
        ASSERT_EQ(PLDSIZE, size2);
        ASSERT_EQ(size1 + size2, out_stream.ByteCount());
        // BackUp a size that's valid for all ZeroCopyOutputStream
        out_stream.BackUp(PLDSIZE / 2);
        ASSERT_EQ(size1 + size2 - PLDSIZE / 2, out_stream.ByteCount());
        void* blk3 = NULL;
        int size3 = 0;
        ASSERT_TRUE(out_stream.Next(&blk3, &size3));
        ASSERT_EQ((char*)blk2 + PLDSIZE / 2, blk3);
        ASSERT_EQ(PLDSIZE / 2, size3);
        ASSERT_EQ(size1 + size2, out_stream.ByteCount());

        // BackUp a size that's undefined in regular ZeroCopyOutputStream
        out_stream.BackUp(PLDSIZE * 2);
        ASSERT_EQ(0, out_stream.ByteCount());
        void* blk4 = NULL;
        int size4 = 0;
        ASSERT_TRUE(out_stream.Next(&blk4, &size4));
        ASSERT_EQ(PLDSIZE, size4);
        ASSERT_EQ(size4, out_stream.ByteCount());
        if (i == 1) {
            ASSERT_EQ(blk1, blk4);
        }
        void* blk5 = NULL;
        int size5 = 0;
        ASSERT_TRUE(out_stream.Next(&blk5, &size5));
        ASSERT_EQ(PLDSIZE, size5);
        ASSERT_EQ(size4 + size5, out_stream.ByteCount());
        if (i == 1) {
            ASSERT_EQ(blk2, blk5);
        }
    }
}

TEST_F(IOBufTest, backup_iobuf_never_called_next) {
    {
        // Consume the left TLS block so that later cases are easier
        // to check.
1163 1164
        butil::IOBuf dummy;
        butil::IOBufAsZeroCopyOutputStream dummy_stream(&dummy);
1165 1166 1167 1168
        void* dummy_data = NULL;
        int dummy_size = 0;
        ASSERT_TRUE(dummy_stream.Next(&dummy_data, &dummy_size));
    }
1169
    butil::IOBuf src;
1170
    const size_t N = DEFAULT_PAYLOAD * 2;
1171 1172 1173
    src.resize(N);
    ASSERT_EQ(2u, src.backing_block_num());
    ASSERT_EQ(N, src.size());
1174
    butil::IOBufAsZeroCopyOutputStream out_stream(&src);
1175 1176
    out_stream.BackUp(1); // also succeed.
    ASSERT_EQ(-1, out_stream.ByteCount());
1177
    ASSERT_EQ(DEFAULT_PAYLOAD * 2 - 1, src.size());
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
    ASSERT_EQ(2u, src.backing_block_num());
    void* data0 = NULL;
    int size0 = 0;
    ASSERT_TRUE(out_stream.Next(&data0, &size0));
    ASSERT_EQ(1, size0);
    ASSERT_EQ(0, out_stream.ByteCount());
    ASSERT_EQ(2u, src.backing_block_num());
    void* data1 = NULL;
    int size1 = 0;
    ASSERT_TRUE(out_stream.Next(&data1, &size1));
    ASSERT_EQ(size1, out_stream.ByteCount());
    ASSERT_EQ(3u, src.backing_block_num());
    ASSERT_EQ(N + size1, src.size());
    void* data2 = NULL;
    int size2 = 0;    
    ASSERT_TRUE(out_stream.Next(&data2, &size2));
    ASSERT_EQ(size1 + size2, out_stream.ByteCount());
    ASSERT_EQ(4u, src.backing_block_num());
    ASSERT_EQ(N + size1 + size2, src.size());
    LOG(INFO) << "Backup1";
    out_stream.BackUp(size1); // intended size1, not size2 to make this BackUp
    // to cross boundary of blocks.
    ASSERT_EQ(size2, out_stream.ByteCount());
    ASSERT_EQ(N + size2, src.size());
    LOG(INFO) << "Backup2";
    out_stream.BackUp(size2);
    ASSERT_EQ(0, out_stream.ByteCount());
    ASSERT_EQ(N, src.size());
}

void *backup_thread(void *arg) {
1209 1210
    butil::IOBufAsZeroCopyOutputStream *wrapper = 
        (butil::IOBufAsZeroCopyOutputStream *)arg;
1211 1212 1213 1214 1215
    wrapper->BackUp(1024);
    return NULL;
}

TEST_F(IOBufTest, backup_in_another_thread) {
1216 1217
    butil::IOBuf buf;
    butil::IOBufAsZeroCopyOutputStream wrapper(&buf);
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
    size_t alloc_size = 0;
    for (int i = 0; i < 10; ++i) {
        void *data; 
        int len;
        ASSERT_TRUE(wrapper.Next(&data, &len));
        alloc_size += len;
    }
    ASSERT_EQ(alloc_size, buf.length());
    for (int i = 0; i < 10; ++i) {
        void *data; 
        int len;
        ASSERT_TRUE(wrapper.Next(&data, &len));
        alloc_size += len;
        pthread_t tid;
        pthread_create(&tid, NULL, backup_thread, &wrapper);
        pthread_join(tid, NULL);
    }
    ASSERT_EQ(alloc_size - 1024 * 10, buf.length()); 
}

TEST_F(IOBufTest, own_block) {
1239
    butil::IOBuf buf;
1240
    const ssize_t BLOCK_SIZE = 1024;
1241 1242
    butil::IOBuf::Block *saved_tls_block = butil::iobuf::get_tls_block_head();
    butil::IOBufAsZeroCopyOutputStream wrapper(&buf, BLOCK_SIZE);
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
    int alloc_size = 0;
    for (int i = 0; i < 100; ++i) {
        void *data;
        int size;
        ASSERT_TRUE(wrapper.Next(&data, &size));
        alloc_size += size;
        if (size > 1) {
            wrapper.BackUp(1);
            alloc_size -= 1;
        }
    }
    ASSERT_EQ(static_cast<size_t>(alloc_size), buf.length());
1255
    ASSERT_EQ(saved_tls_block, butil::iobuf::get_tls_block_head());
1256
    ASSERT_EQ(butil::iobuf::block_cap(buf._front_ref().block), BLOCK_SIZE - BLOCK_OVERHEAD);
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
}

struct Foo1 {
    explicit Foo1(int x2) : x(x2) {}
    int x;
};

struct Foo2 {
    std::vector<Foo1> foo1;
};

std::ostream& operator<<(std::ostream& os, const Foo1& foo1) {
    return os << "foo1.x=" << foo1.x;
}

std::ostream& operator<<(std::ostream& os, const Foo2& foo2) {
    for (size_t i = 0; i < foo2.foo1.size(); ++i) {
        os << "foo2[" << i << "]=" << foo2.foo1[i];
    }
    return os;
}

TEST_F(IOBufTest, as_ostream) {
1280
    butil::iobuf::reset_blockmem_allocate_and_deallocate();
1281

1282
    butil::IOBufBuilder builder;
1283
    LOG(INFO) << "sizeof(IOBufBuilder)=" << sizeof(builder) << std::endl
1284
              << "sizeof(IOBuf)=" << sizeof(butil::IOBuf) << std::endl
1285
              << "sizeof(IOBufAsZeroCopyOutputStream)="
1286
              << sizeof(butil::IOBufAsZeroCopyOutputStream) << std::endl
1287
              << "sizeof(ZeroCopyStreamAsStreamBuf)="
1288
              << sizeof(butil::ZeroCopyStreamAsStreamBuf) << std::endl
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
              << "sizeof(ostream)=" << sizeof(std::ostream);
    int x = -1;
    builder << 2 << " " << x << " " << 1.1 << " hello ";
    ASSERT_EQ("2 -1 1.1 hello ", builder.buf().to_string());

    builder << "world!";
    ASSERT_EQ("2 -1 1.1 hello world!", builder.buf().to_string());

    builder.buf().clear();
    builder << "world!";
    ASSERT_EQ("world!", builder.buf().to_string());

    Foo2 foo2;
    for (int i = 0; i < 10000; ++i) {
        foo2.foo1.push_back(Foo1(i));
    }
    builder.buf().clear();
    builder << "<before>" << foo2 << "<after>";
    std::ostringstream oss;
    oss << "<before>" << foo2 << "<after>";
    ASSERT_EQ(oss.str(), builder.buf().to_string());

1311
    butil::IOBuf target;
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
    builder.move_to(target);
    ASSERT_TRUE(builder.buf().empty());
    ASSERT_EQ(oss.str(), target.to_string());

    std::ostringstream oss2;
    oss2 << target;
    ASSERT_EQ(oss.str(), oss2.str());
}

TEST_F(IOBufTest, append_from_fd_with_offset) {
1322
    butil::TempFile file;
1323
    file.save("dummy");
1324
    butil::fd_guard fd(open(file.fname(), O_RDWR | O_TRUNC));
1325
    ASSERT_TRUE(fd >= 0) << file.fname() << ' ' << berror();
1326
    butil::IOPortal buf;
1327 1328
    char dummy[10 * 1024];
    buf.append(dummy, sizeof(dummy));
gejun's avatar
gejun committed
1329
    ASSERT_EQ((ssize_t)sizeof(dummy), buf.cut_into_file_descriptor(fd));
1330
    for (size_t i = 0; i < sizeof(dummy); ++i) {
1331
        butil::IOPortal b0;
gejun's avatar
gejun committed
1332
        ASSERT_EQ(sizeof(dummy) - i, (size_t)b0.pappend_from_file_descriptor(fd, i, sizeof(dummy))) << berror();
1333 1334 1335 1336 1337 1338
        char tmp[sizeof(dummy)];
        ASSERT_EQ(0, memcmp(dummy + i, b0.fetch(tmp, b0.length()), b0.length()));
    }

}

1339
static butil::atomic<int> s_nthread(0);
1340 1341 1342 1343 1344
static long number_per_thread = 1024;

void* cut_into_fd(void* arg) {
    int fd = (int)(long)arg;
    const long start_num = number_per_thread * 
1345
        s_nthread.fetch_add(1, butil::memory_order_relaxed);
1346 1347 1348
    off_t offset = start_num * sizeof(int);
    for (int i = 0; i < number_per_thread; ++i) {
        int to_write = start_num + i;
1349
        butil::IOBuf out;
1350 1351
        out.append(&to_write, sizeof(int));
        CHECK_EQ(out.pcut_into_file_descriptor(fd, offset + sizeof(int) * i), 
1352
                 (ssize_t)sizeof(int));
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
    }
    return NULL;
}

TEST_F(IOBufTest, cut_into_fd_with_offset_multithreaded) {
    s_nthread.store(0);
    number_per_thread = 10240;
    pthread_t threads[8];
    long fd = open(".out.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);
    ASSERT_TRUE(fd >= 0) << berror();
    for (size_t i = 0; i < ARRAY_SIZE(threads); ++i) {
        ASSERT_EQ(0, pthread_create(&threads[i], NULL, cut_into_fd, (void*)fd));
    }
    for (size_t i = 0; i < ARRAY_SIZE(threads); ++i) {
        pthread_join(threads[i], NULL);
    }
    for (int i = 0; i < number_per_thread * (int)ARRAY_SIZE(threads); ++i) {
        off_t offset = i * sizeof(int);
1371
        butil::IOPortal in;
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
        ASSERT_EQ(sizeof(int), in.pappend_from_file_descriptor(fd, offset, sizeof(int)));
        int j;
        ASSERT_EQ(sizeof(j), in.cutn(&j, sizeof(j)));
        ASSERT_EQ(i, j);
    }
}

TEST_F(IOBufTest, slice) {
    size_t N = 100000;
    std::string expected;
    expected.reserve(N);
1383
    butil::IOBuf buf;
1384 1385 1386 1387 1388 1389 1390 1391
    for (size_t i = 0; i < N; ++i) {
        expected.push_back(i % 26 + 'a');
        buf.push_back(i % 26 + 'a');
    }
    const size_t block_count = buf.backing_block_num();
    std::string actual;
    actual.reserve(expected.size());
    for (size_t i = 0; i < block_count; ++i) {
1392
        butil::StringPiece p = buf.backing_block(i);
1393 1394 1395 1396 1397 1398 1399
        ASSERT_FALSE(p.empty());
        actual.append(p.data(), p.size());
    }
    ASSERT_TRUE(expected == actual);
}

TEST_F(IOBufTest, swap) {
1400
    butil::IOBuf a;
1401
    a.append("I'am a");
1402
    butil::IOBuf b;
1403 1404 1405 1406 1407 1408 1409
    b.append("I'am b");
    std::swap(a, b);
    ASSERT_TRUE(a.equals("I'am b"));
    ASSERT_TRUE(b.equals("I'am a"));
}

TEST_F(IOBufTest, resize) {
1410
    butil::IOBuf a;
1411 1412 1413
    a.resize(100);
    std::string as;
    as.resize(100);
1414
    butil::IOBuf b;
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
    b.resize(100, 'b');
    std::string bs;
    bs.resize(100, 'b');
    ASSERT_EQ(100u, a.length());
    ASSERT_EQ(100u, b.length());
    ASSERT_TRUE(a.equals(as));
    ASSERT_TRUE(b.equals(bs));
}

TEST_F(IOBufTest, iterate_bytes) {
1425
    butil::IOBuf a;
1426 1427 1428
    a.append("hello world");
    std::string saved_a = a.to_string();
    size_t n = 0;
1429
    butil::IOBufBytesIterator it(a);
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
    for (; it != NULL; ++it, ++n) {
        ASSERT_EQ(saved_a[n], *it);
    }
    ASSERT_EQ(saved_a.size(), n);
    ASSERT_TRUE(saved_a == a);

    // append more to the iobuf, iterator should still be ended.
    a.append(", this is iobuf");
    ASSERT_TRUE(it == NULL);

    // append more-than-one-block data to the iobuf
    for (int i = 0; i < 1024; ++i) {
        a.append("ab33jm4hgaklkv;2[25lj4lkj312kl4j321kl4j3k");
    }
    saved_a = a.to_string();
    n = 0;
1446
    for (butil::IOBufBytesIterator it2(a); it2 != NULL; it2++/*intended post++*/, ++n) {
1447 1448 1449 1450 1451 1452 1453
        ASSERT_EQ(saved_a[n], *it2);
    }
    ASSERT_EQ(saved_a.size(), n);
    ASSERT_TRUE(saved_a == a);    
}

TEST_F(IOBufTest, appender) {
1454
    butil::IOBufAppender appender;
1455 1456 1457 1458 1459
    ASSERT_EQ(0, appender.append("hello", 5));
    ASSERT_EQ("hello", appender.buf());
    ASSERT_EQ(0, appender.push_back(' '));
    ASSERT_EQ(0, appender.append("world", 5));
    ASSERT_EQ("hello world", appender.buf());
1460
    butil::IOBuf buf2;
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
    appender.move_to(buf2);
    ASSERT_EQ("", appender.buf());
    ASSERT_EQ("hello world", buf2);
    std::string str;
    for (int i = 0; i < 10000; ++i) {
        char buf[128];
        int len = snprintf(buf, sizeof(buf), "1%d2%d3%d4%d5%d", i, i, i, i, i);
        appender.append(buf, len);
        str.append(buf, len);
    }
    ASSERT_EQ(str, appender.buf());
1472
    butil::IOBuf buf3;
1473 1474 1475 1476 1477 1478 1479
    appender.move_to(buf3);
    ASSERT_EQ("", appender.buf());
    ASSERT_EQ(str, buf3);
}

TEST_F(IOBufTest, appender_perf) {
    const size_t N1 = 100000;
1480
    butil::Timer tm1;
1481
    tm1.start();
1482
    butil::IOBuf buf1;
1483 1484 1485 1486 1487
    for (size_t i = 0; i < N1; ++i) {
        buf1.push_back(i);
    }
    tm1.stop();

1488
    butil::Timer tm2;
1489
    tm2.start();
1490
    butil::IOBufAppender appender1;
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
    for (size_t i = 0; i < N1; ++i) {
        appender1.push_back(i);
    }
    tm2.stop();

    LOG(INFO) << "IOBuf.push_back=" << tm1.n_elapsed() / N1
              << "ns IOBufAppender.push_back=" << tm2.n_elapsed() / N1
              << "ns";

    const size_t N2 = 50000;
    const std::string s = "a repeatly appended string";
    std::string str2;
1503
    butil::IOBuf buf2;
1504 1505 1506 1507 1508 1509 1510
    tm1.start();
    for (size_t i = 0; i < N2; ++i) {
        buf2.append(s);
    }
    tm1.stop();

    tm2.start();
1511
    butil::IOBufAppender appender2;
1512 1513 1514 1515 1516
    for (size_t i = 0; i < N2; ++i) {
        appender2.append(s);
    }
    tm2.stop();

1517
    butil::Timer tm3;
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
    tm3.start();
    for (size_t i = 0; i < N2; ++i) {
        str2.append(s);
    }
    tm3.stop();

    LOG(INFO) << "IOBuf.append=" << tm1.n_elapsed() / N2
              << "ns IOBufAppender.append=" << tm2.n_elapsed() / N2
              << "ns string.append=" << tm3.n_elapsed() / N2
              << "ns (string-length=" << s.size() << ')';
}

TEST_F(IOBufTest, printed_as_binary) {
1531
    butil::IOBuf buf;
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
    std::string str;
    for (int i = 0; i < 256; ++i) {
        buf.push_back((char)i);
        str.push_back((char)i);
    }
    const char* const OUTPUT =
        "\\00\\01\\02\\03\\04\\05\\06\\07\\b\\t\\n\\0B\\0C\\r\\0E\\0F"
        "\\10\\11\\12\\13\\14\\15\\16\\17\\18\\19\\1A\\1B\\1C\\1D\\1E"
        "\\1F !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUV"
        "WXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\7F\\80\\81\\82"
        "\\83\\84\\85\\86\\87\\88\\89\\8A\\8B\\8C\\8D\\8E\\8F\\90\\91"
        "\\92\\93\\94\\95\\96\\97\\98\\99\\9A\\9B\\9C\\9D\\9E\\9F\\A0"
        "\\A1\\A2\\A3\\A4\\A5\\A6\\A7\\A8\\A9\\AA\\AB\\AC\\AD\\AE\\AF"
        "\\B0\\B1\\B2\\B3\\B4\\B5\\B6\\B7\\B8\\B9\\BA\\BB\\BC\\BD\\BE"
        "\\BF\\C0\\C1\\C2\\C3\\C4\\C5\\C6\\C7\\C8\\C9\\CA\\CB\\CC\\CD"
        "\\CE\\CF\\D0\\D1\\D2\\D3\\D4\\D5\\D6\\D7\\D8\\D9\\DA\\DB\\DC"
        "\\DD\\DE\\DF\\E0\\E1\\E2\\E3\\E4\\E5\\E6\\E7\\E8\\E9\\EA\\EB"
        "\\EC\\ED\\EE\\EF\\F0\\F1\\F2\\F3\\F4\\F5\\F6\\F7\\F8\\F9\\FA"
        "\\FB\\FC\\FD\\FE\\FF";
    std::ostringstream os;
1552
    os << butil::ToPrintable(buf, 256);
1553 1554
    ASSERT_STREQ(OUTPUT, os.str().c_str());
    os.str("");
1555
    os << butil::ToPrintable(str, 256);
1556 1557 1558 1559
    ASSERT_STREQ(OUTPUT, os.str().c_str());
}

TEST_F(IOBufTest, copy_to_string_from_iterator) {
1560
    butil::IOBuf b0;
1561
    for (size_t i = 0; i < 1 * 1024 * 1024lu; ++i) {
1562
        b0.push_back(butil::fast_rand_in('a', 'z'));
1563
    }
1564 1565
    butil::IOBuf b1(b0);
    butil::IOBufBytesIterator iter(b0);
1566 1567
    size_t nc = 0;
    while (nc < b0.length()) {
1568 1569
        size_t to_copy = butil::fast_rand_in(1024lu, 64 * 1024lu);
        butil::IOBuf b;
1570 1571 1572 1573 1574 1575 1576 1577 1578
        b1.cutn(&b, to_copy);
        std::string s;
        const size_t copied = iter.copy_and_forward(&s, to_copy);
        ASSERT_GT(copied, 0u);
        ASSERT_TRUE(b.equals(s));
        nc += copied;
    }
    ASSERT_EQ(nc, b0.length());
}
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658

static void* my_free_params = NULL;
static void my_free(void* m) {
    free(m);
    my_free_params = m;
}
    
TEST_F(IOBufTest, append_user_data_and_consume) {
    butil::IOBuf b0;
    const int REP = 16;
    const int len = REP * 256;
    char* data = (char*)malloc(len);
    for (int i = 0; i < 256; ++i) {
        for (int j = 0; j < REP; ++j) {
            data[i * REP + j] = (char)i;
        }
    }
    my_free_params = NULL;
    ASSERT_EQ(0, b0.append_user_data(data, len, my_free));
    ASSERT_EQ(1UL, b0._ref_num());
    butil::IOBuf::BlockRef r = b0._front_ref();
    ASSERT_EQ(1, butil::iobuf::block_shared_count(r.block));
    ASSERT_EQ(len, b0.size());
    std::string out;
    ASSERT_EQ(len, b0.cutn(&out, len));
    ASSERT_TRUE(b0.empty());
    ASSERT_EQ(data, my_free_params);
        
    ASSERT_EQ(len, out.size());
    // note: cannot memcmp with data which is already free-ed
    for (int i = 0; i < 256; ++i) {
        for (int j = 0; j < REP; ++j) {
            ASSERT_EQ((char)i, out[i * REP + j]);
        }
    }
}

TEST_F(IOBufTest, append_user_data_and_share) {
    butil::IOBuf b0;
    const int REP = 16;
    const int len = REP * 256;
    char* data = (char*)malloc(len);
    for (int i = 0; i < 256; ++i) {
        for (int j = 0; j < REP; ++j) {
            data[i * REP + j] = (char)i;
        }
    }
    my_free_params = NULL;
    ASSERT_EQ(0, b0.append_user_data(data, len, my_free));
    ASSERT_EQ(1UL, b0._ref_num());
    butil::IOBuf::BlockRef r = b0._front_ref();
    ASSERT_EQ(1, butil::iobuf::block_shared_count(r.block));
    ASSERT_EQ(len, b0.size());

    {
        butil::IOBuf bufs[256];
        for (int i = 0; i < 256; ++i) {
            ASSERT_EQ(REP, b0.cutn(&bufs[i], REP));
            ASSERT_EQ(len - (i+1) * REP, b0.size());
            if (i != 255) {
                ASSERT_EQ(1UL, b0._ref_num());
                butil::IOBuf::BlockRef r = b0._front_ref();
                ASSERT_EQ(i + 2, butil::iobuf::block_shared_count(r.block));
            } else {
                ASSERT_EQ(0UL, b0._ref_num());
                ASSERT_TRUE(b0.empty());
            }
        }
        ASSERT_EQ(NULL, my_free_params);
        for (int i = 0; i < 256; ++i) {
            std::string out = bufs[i].to_string();
            ASSERT_EQ(REP, out.size());
            for (int j = 0; j < REP; ++j) {
                ASSERT_EQ((char)i, out[j]);
            }
        }
    }
    ASSERT_EQ(data, my_free_params);
}

李磊's avatar
李磊 committed
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
TEST_F(IOBufTest, acquire_tls_block) {
    butil::iobuf::remove_tls_block_chain();
    butil::IOBuf::Block* b = butil::iobuf::acquire_tls_block();
    const size_t block_cap = butil::iobuf::block_cap(b);
    butil::IOBuf buf;
    for (size_t i = 0; i < block_cap; i++) {
        buf.append("x");
    }
    ASSERT_EQ(1, butil::iobuf::get_tls_block_count());
    butil::IOBuf::Block* head = butil::iobuf::get_tls_block_head();
    ASSERT_EQ(butil::iobuf::block_cap(head), butil::iobuf::block_size(head));
    butil::iobuf::release_tls_block_chain(b);
    ASSERT_EQ(2, butil::iobuf::get_tls_block_count());
    for (size_t i = 0; i < block_cap; i++) {
        buf.append("x");
    }
    ASSERT_EQ(2, butil::iobuf::get_tls_block_count());
    head = butil::iobuf::get_tls_block_head();
    ASSERT_EQ(butil::iobuf::block_cap(head), butil::iobuf::block_size(head));
    b = butil::iobuf::acquire_tls_block();
    ASSERT_EQ(0, butil::iobuf::get_tls_block_count());
    ASSERT_NE(butil::iobuf::block_cap(b), butil::iobuf::block_size(b));
}

1683
} // namespace