1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
//! `Store` string read commands (GET family) + INCRBY. The SET-family
//! write path lives in `string_set.rs` (500-LOC house cap).
use crate::util::{format_i64_into, itoa_i64_stack, parse_i64};
use crate::value::{SmallBytes, Value};
use crate::{Entry, Store, StoreError};
use std::borrow::Cow;
use std::sync::Arc;
/// L1 return shape for [`Store::get_for_reply`] — lets the reactor's reply
/// path choose between memcpy (`Bytes`) and writev zero-copy (`ArcBulk`)
/// off one keyspace lookup.
pub enum GetReply<'a> {
/// Inline-encoded value — caller memcpys the bytes into its output Vec
/// (small replies; encoding cost is tiny vs the RTT floor).
Bytes(Cow<'a, [u8]>),
/// L1 (2026-06-21): Arc-backed bulk. The reactor's reply path pushes
/// the Arc into the conn's `output_arcs` so the next `writev` iovec
/// list points DIRECTLY at the value bytes — skipping the per-GET
/// memcpy that valkey's `tryAvoidBulkStrCopyToReply` likewise avoids.
ArcBulk(Arc<Box<[u8]>>),
}
impl Store {
// ---- strings -------------------------------------------------------
/// L1 (2026-06-21): GET variant that exposes the underlying encoding
/// so the reactor's reply path can choose zero-copy
/// (`Value::ArcBulk` → push the Arc to the conn's `output_arcs` for a
/// writev iovec) vs memcpy (`Value::Str` / `Value::Int` → encode bytes
/// into the conn's output Vec). ONE keyspace lookup; the variant tag
/// chooses the encoding without a second probe.
pub fn get_for_reply(&mut self, key: &[u8]) -> Result<Option<GetReply<'_>>, StoreError> {
match self.live_entry(key) {
None => Ok(None),
Some(e) => match &e.value {
Value::Str(v) => Ok(Some(GetReply::Bytes(Cow::Borrowed(v.as_slice())))),
Value::ArcBulk(a) => Ok(Some(GetReply::ArcBulk(Arc::clone(a)))),
Value::Int(n) => {
let mut tmp = itoa_i64_stack();
let s = format_i64_into(*n, &mut tmp);
Ok(Some(GetReply::Bytes(Cow::Owned(s.to_vec()))))
}
_ => Err(StoreError::WrongType),
},
}
}
/// A.6 (v1.25): fused GET-into-output. Skips the [`GetReply`] enum tag
/// round-trip + caller match arm by writing the RESP frame directly into
/// `output` (header + bytes + CRLF for Str/Int) or pushing the Arc into
/// `output_arcs` at the right offset (ArcBulk zero-copy via writev).
/// Returns the same outcomes as [`Self::get_for_reply`]: `Ok(true)` if
/// the key was found and emitted, `Ok(false)` if absent (the caller
/// emits the `$-1` null bulk — preserves the existing inline-null
/// semantics on the reactor side), `Err` for WRONGTYPE.
pub fn get_into_output(
&mut self,
key: &[u8],
output: &mut Vec<u8>,
output_arcs: &mut Vec<(usize, Arc<Box<[u8]>>)>,
) -> Result<bool, StoreError> {
match self.live_entry(key) {
None => Ok(false),
Some(e) => match &e.value {
Value::Str(v) => {
let bytes = v.as_slice();
crate::util::bulk_header_into(output, bytes.len());
output.extend_from_slice(bytes);
output.extend_from_slice(b"\r\n");
Ok(true)
}
Value::ArcBulk(a) => {
crate::util::bulk_header_into(output, a.len());
let pos = output.len();
output_arcs.push((pos, Arc::clone(a)));
output.extend_from_slice(b"\r\n");
Ok(true)
}
Value::Int(n) => {
let mut tmp = itoa_i64_stack();
let s = format_i64_into(*n, &mut tmp);
crate::util::bulk_header_into(output, s.len());
output.extend_from_slice(s);
output.extend_from_slice(b"\r\n");
Ok(true)
}
_ => Err(StoreError::WrongType),
},
}
}
/// `GET` — returns a `Cow<[u8]>` so `Value::Int` callers can format the
/// integer to ASCII without storing it. L2 (2026-06-21): `Value::Str`
/// returns `Cow::Borrowed` (zero copy, same as before); `Value::Int`
/// formats to a small owned `Vec<u8>` (up to 20 bytes for `i64::MIN`).
pub fn get(&mut self, key: &[u8]) -> Result<Option<Cow<'_, [u8]>>, StoreError> {
match self.live_entry(key) {
None => Ok(None),
Some(e) => match &e.value {
Value::Str(v) => Ok(Some(Cow::Borrowed(v.as_slice()))),
// L1: Arc-backed bulk — return borrow into the Arc's
// bytes. Caller can either memcpy via Cow::Borrowed
// (default `encode_bulk` path) OR look up the
// underlying `Value::ArcBulk(arc)` separately for the
// writev zero-copy reply path.
Value::ArcBulk(a) => Ok(Some(Cow::Borrowed(a.as_ref()))),
Value::Int(n) => {
let mut tmp = itoa_i64_stack();
let s = format_i64_into(*n, &mut tmp);
Ok(Some(Cow::Owned(s.to_vec())))
}
_ => Err(StoreError::WrongType),
},
}
}
/// Read-only `GET`: `&self`, so concurrent readers can run under a shared
/// lock (embedded mode's `RwLock` read path). Expiry is checked against the
/// coarse cached clock but an expired key is *not* removed here (no `&mut`)
/// — the reaper / next write reclaims it; a reader just sees `None`. LRU is
/// not touched, so this path is only used when eviction is off
/// (`maxmemory == 0`); with eviction, the caller takes the mutating
/// [`Self::get`] under an exclusive lock so access still stamps the LRU.
pub fn get_shared(&self, key: &[u8]) -> Result<Option<Cow<'_, [u8]>>, StoreError> {
match self.map.get(key) {
None => Ok(None),
Some(e) if e.is_expired(self.cached_clock, self.cached_ns) => Ok(None),
Some(e) => match &e.value {
Value::Str(v) => Ok(Some(Cow::Borrowed(v.as_slice()))),
Value::ArcBulk(a) => Ok(Some(Cow::Borrowed(a.as_ref()))),
Value::Int(n) => {
let mut tmp = itoa_i64_stack();
let s = format_i64_into(*n, &mut tmp);
Ok(Some(Cow::Owned(s.to_vec())))
}
_ => Err(StoreError::WrongType),
},
}
}
pub fn strlen(&mut self, key: &[u8]) -> Result<usize, StoreError> {
Ok(self.get(key)?.map_or(0, |c| c.len()))
}
/// `INCRBY` family; preserves any TTL.
///
/// L2 (2026-06-21, lessons from valkey OBJ_ENCODING_INT): the hot path
/// matches `Value::Int(n)` and does the increment in place — no parse,
/// no format, no allocation. The legacy `Value::Str` arm parses,
/// increments, and **promotes** to `Value::Int(next)` so subsequent
/// INCRs land on the fast path. Insert-new path also lands as `Int`.
pub fn incr_by(&mut self, key: &[u8], delta: i64) -> Result<i64, StoreError> {
let outcome = match self.live_entry_mut(key) {
Some(e) => match &mut e.value {
Value::Int(n) => {
let next = n.checked_add(delta).ok_or(StoreError::Overflow)?;
*n = next;
// In-place i64 mutation — weight unchanged (still 0
// heap bytes for an Int). Skip the reweigh entirely.
return Ok(next);
}
Value::Str(v) => {
let next = parse_i64(v.as_slice())
.ok_or(StoreError::NotInteger)?
.checked_add(delta)
.ok_or(StoreError::Overflow)?;
// Promote to Int: future INCRs hit the fast path.
e.value = Value::Int(next);
IncrOutcome::Reweigh(next)
}
Value::ArcBulk(a) => {
// L1: large value claimed to be numeric — parse and
// promote to Int. Subsequent INCRs hit the fast path.
let next = parse_i64(a.as_ref())
.ok_or(StoreError::NotInteger)?
.checked_add(delta)
.ok_or(StoreError::Overflow)?;
e.value = Value::Int(next);
IncrOutcome::Reweigh(next)
}
_ => return Err(StoreError::WrongType),
},
// Absent/expired ⇒ start from 0; 0 + delta can't overflow i64.
None => IncrOutcome::Insert(delta),
};
match outcome {
IncrOutcome::Reweigh(next) => {
self.reweigh_entry(key);
Ok(next)
}
IncrOutcome::Insert(next) => {
self.insert_entry(
SmallBytes::from_slice(key),
Entry::new(Value::Int(next), None),
);
Ok(next)
}
}
}
}
enum IncrOutcome {
Reweigh(i64),
Insert(i64),
}