xref: /freebsd-src/contrib/llvm-project/lldb/source/Core/Progress.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
1 //===-- Progress.cpp ------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Core/Progress.h"
10 
11 #include "lldb/Core/Debugger.h"
12 #include "lldb/Utility/StreamString.h"
13 
14 using namespace lldb;
15 using namespace lldb_private;
16 
17 std::atomic<uint64_t> Progress::g_id(0);
18 
19 Progress::Progress(std::string title, uint64_t total,
20                    lldb_private::Debugger *debugger)
21     : m_title(title), m_id(++g_id), m_completed(0), m_total(total) {
22   assert(total > 0);
23   if (debugger)
24     m_debugger_id = debugger->GetID();
25   std::lock_guard<std::mutex> guard(m_mutex);
26   ReportProgress();
27 }
28 
29 Progress::~Progress() {
30   // Make sure to always report progress completed when this object is
31   // destructed so it indicates the progress dialog/activity should go away.
32   std::lock_guard<std::mutex> guard(m_mutex);
33   if (!m_completed)
34     m_completed = m_total;
35   ReportProgress();
36 }
37 
38 void Progress::Increment(uint64_t amount, std::string update) {
39   if (amount > 0) {
40     std::lock_guard<std::mutex> guard(m_mutex);
41     // Watch out for unsigned overflow and make sure we don't increment too
42     // much and exceed m_total.
43     if (amount > (m_total - m_completed))
44       m_completed = m_total;
45     else
46       m_completed += amount;
47     ReportProgress(update);
48   }
49 }
50 
51 void Progress::ReportProgress(std::string update) {
52   if (!m_complete) {
53     // Make sure we only send one notification that indicates the progress is
54     // complete.
55     m_complete = m_completed == m_total;
56     Debugger::ReportProgress(m_id, m_title, std::move(update), m_completed,
57                              m_total, m_debugger_id);
58   }
59 }
60