OR-Tools  9.1
message_callback_data.cc
Go to the documentation of this file.
1 // Copyright 2010-2021 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
15 
16 #include <cstddef>
17 #include <string>
18 #include <utility>
19 
20 #include "absl/strings/string_view.h"
21 #include "absl/types/optional.h"
22 #include "ortools/math_opt/callback.pb.h"
23 
24 namespace operations_research {
25 namespace math_opt {
26 
27 absl::optional<CallbackDataProto> MessageCallbackData::Parse(
28  const absl::string_view message) {
29  CallbackDataProto data;
30 
31  // Iterate on all complete lines (lines ending with a '\n').
32  absl::string_view remainder = message;
33  for (std::size_t end = 0; end = remainder.find('\n'), end != remainder.npos;
34  remainder = remainder.substr(end + 1)) {
35  const auto line = remainder.substr(0, end);
36  if (!unfinished_line_.empty()) {
37  std::string& new_message = *data.add_messages();
38  new_message = std::move(unfinished_line_);
39  unfinished_line_.clear();
40  new_message += line;
41  } else {
42  data.add_messages(std::string(line));
43  }
44  }
45 
46  // At the end of the loop, the remainder may contains the last unfinished
47  // line. This could be the first line too if the entire message does not
48  // contain '\n'.
49  unfinished_line_ += remainder;
50 
51  // It is an error to call the user callback without any message.
52  if (data.messages().empty()) {
53  return absl::nullopt;
54  }
55 
56  // We only need to set that if we have messages.
57  data.set_event(CALLBACK_EVENT_MESSAGE);
58 
59  return data;
60 }
61 
62 absl::optional<CallbackDataProto> MessageCallbackData::Flush() {
63  if (unfinished_line_.empty()) {
64  return absl::nullopt;
65  }
66 
67  CallbackDataProto data;
68  data.set_event(CALLBACK_EVENT_MESSAGE);
69  *data.add_messages() = std::move(unfinished_line_);
70  unfinished_line_.clear();
71  return data;
72 }
73 
74 } // namespace math_opt
75 } // namespace operations_research
absl::optional< CallbackDataProto > Parse(absl::string_view message)
std::string message
Definition: trace.cc:398
Collection of objects used to extend the Constraint Solver library.