From e8a27bb203fe2aff70390a5eca002d7438da9b0f Mon Sep 17 00:00:00 2001
From: mrDarker <mr.darker@163.com>
Date: 星期三, 22 十月 2025 14:24:34 +0800
Subject: [PATCH] Merge branch 'clh' into liuyang

---
 SourceCode/Bond/DAQBridge/buffer/SampleBuffer.h |   57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 57 insertions(+), 0 deletions(-)

diff --git a/SourceCode/Bond/DAQBridge/buffer/SampleBuffer.h b/SourceCode/Bond/DAQBridge/buffer/SampleBuffer.h
new file mode 100644
index 0000000..12d44f8
--- /dev/null
+++ b/SourceCode/Bond/DAQBridge/buffer/SampleBuffer.h
@@ -0,0 +1,57 @@
+// SampleBuffer.h
+#pragma once
+#include "../core/DataTypes.h"
+#include <deque>
+#include <vector>
+#include <shared_mutex>
+#include <chrono>
+
+enum class RetainMode {
+    ByCount,        // 按样本数上限
+    ByRollingAge,   // 按滚动时间窗口(maxAge)
+    ByAbsoluteRange // 按绝对时间段 [absFrom, absTo]
+};
+
+struct RetentionPolicy {
+    RetainMode mode = RetainMode::ByCount;
+    size_t maxSamples = 100000;                         // ByCount 用
+    std::chrono::milliseconds maxAge{ std::chrono::hours(1) }; // ByRollingAge 用
+    int64_t absFrom = 0;                                // ByAbsoluteRange 用
+    int64_t absTo = 0;                                // ByAbsoluteRange 用(absTo>=absFrom 有效)
+};
+
+class SampleBuffer {
+public:
+    explicit SampleBuffer(RetentionPolicy policy = {}) : policy_(policy) {}
+
+    // 写:按时间戳递增推入(乱序会被简单纠正为非递减)
+    void push(int64_t ts_ms, double v);
+
+    // 读:按“tsExclusive 之后”的新数据
+    std::vector<Sample> getSince(int64_t tsExclusive, size_t maxCount = 4096) const;
+
+    // 读:按区间 [from, to](包含边界)
+    std::vector<Sample> getRange(int64_t from_ts, int64_t to_ts, size_t maxCount = 4096) const;
+
+    // 查询 / 维护
+    size_t size() const;
+    bool   empty() const;
+    int64_t latestTs() const;
+    void clear();
+
+    // 配置
+    void setPolicy(const RetentionPolicy& p);
+    RetentionPolicy getPolicy() const;
+
+    int64_t earliestTs() const;  // 无数据时返回 0
+
+private:
+    void pruneUnlocked(int64_t ref_now_ms);       // 按策略清理
+    size_t lowerBoundIndex(int64_t tsExclusive) const; // 二分:第一个 > tsExclusive
+    size_t lowerBoundInclusive(int64_t tsInclusive) const; // 第一个 >= tsInclusive
+    size_t upperBoundInclusive(int64_t tsInclusive) const; // 最后一个 <= tsInclusive 的下一个位置
+
+    mutable std::shared_mutex mtx_;
+    std::deque<Sample> data_;
+    RetentionPolicy policy_;
+};

--
Gitblit v1.9.3