1 //  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 //  This source code is licensed under both the GPLv2 (found in the
3 //  COPYING file in the root directory) and Apache 2.0 License
4 //  (found in the LICENSE.Apache file in the root directory).
5 //
6 // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
7 // Use of this source code is governed by a BSD-style license that can be
8 // found in the LICENSE file. See the AUTHORS file for names of contributors.
9 
10 #include "file/read_write_util.h"
11 
12 #include <sstream>
13 #include "test_util/sync_point.h"
14 
15 namespace ROCKSDB_NAMESPACE {
16 
NewWritableFile(FileSystem * fs,const std::string & fname,std::unique_ptr<FSWritableFile> * result,const FileOptions & options)17 IOStatus NewWritableFile(FileSystem* fs, const std::string& fname,
18                          std::unique_ptr<FSWritableFile>* result,
19                          const FileOptions& options) {
20   IOStatus s = fs->NewWritableFile(fname, options, result, nullptr);
21   TEST_KILL_RANDOM("NewWritableFile:0", rocksdb_kill_odds * REDUCE_ODDS2);
22   return s;
23 }
24 
ReadOneLine(std::istringstream * iss,SequentialFileReader * seq_file_reader,std::string * output,bool * has_data,Status * result)25 bool ReadOneLine(std::istringstream* iss, SequentialFileReader* seq_file_reader,
26                  std::string* output, bool* has_data, Status* result) {
27   const int kBufferSize = 8192;
28   char buffer[kBufferSize + 1];
29   Slice input_slice;
30 
31   std::string line;
32   bool has_complete_line = false;
33   while (!has_complete_line) {
34     if (std::getline(*iss, line)) {
35       has_complete_line = !iss->eof();
36     } else {
37       has_complete_line = false;
38     }
39     if (!has_complete_line) {
40       // if we're not sure whether we have a complete line,
41       // further read from the file.
42       if (*has_data) {
43         *result = seq_file_reader->Read(kBufferSize, &input_slice, buffer);
44       }
45       if (input_slice.size() == 0) {
46         // meaning we have read all the data
47         *has_data = false;
48         break;
49       } else {
50         iss->str(line + input_slice.ToString());
51         // reset the internal state of iss so that we can keep reading it.
52         iss->clear();
53         *has_data = (input_slice.size() == kBufferSize);
54         continue;
55       }
56     }
57   }
58   *output = line;
59   return *has_data || has_complete_line;
60 }
61 
62 #ifndef NDEBUG
IsFileSectorAligned(const size_t off,size_t sector_size)63 bool IsFileSectorAligned(const size_t off, size_t sector_size) {
64   return off % sector_size == 0;
65 }
66 #endif  // NDEBUG
67 }  // namespace ROCKSDB_NAMESPACE
68