Skip to content

Commit e94b89e

Browse files
committed
value: introduce CqlVarint type
Added a `CqlVarint` type which represents the native cql varint type. Varint value is represented as a signed binary in big-endian order.
1 parent d01b473 commit e94b89e

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

scylla-cql/src/frame/value.rs

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,70 @@ impl std::hash::Hash for CqlTimeuuid {
215215
}
216216
}
217217

218+
/// Native CQL `varint` representation.
219+
///
220+
/// Represented as two's-complement binary in big-endian order.
221+
///
222+
/// This type is a raw representation in bytes. It's the default
223+
/// implementation of `varint` type - independent of any
224+
/// external crates and crate features.
225+
///
226+
/// # DB data format
227+
/// Notice that [constructors](CqlVarint#impl-CqlVarint)
228+
/// don't perform any normalization on the provided data.
229+
/// This means that underlying bytes may contain leading zeros.
230+
///
231+
/// Currently, Scylla and Cassandra support non-normalized `varint` values.
232+
/// Bytes provided by the user via constructor are passed to DB as is.
233+
#[derive(Clone, Debug)]
234+
pub struct CqlVarint(Vec<u8>);
235+
236+
/// Constructors from bytes
237+
impl CqlVarint {
238+
/// Creates a [`CqlVarint`] from an array of bytes in
239+
/// two's complement big-endian binary representation.
240+
///
241+
/// See: disclaimer about [non-normalized values](CqlVarint#db-data-format).
242+
pub fn from_signed_bytes_be(digits: Vec<u8>) -> Self {
243+
Self(digits)
244+
}
245+
246+
/// Creates a [`CqlVarint`] from a slice of bytes in
247+
/// two's complement binary big-endian representation.
248+
///
249+
/// See: disclaimer about [non-normalized values](CqlVarint#db-data-format).
250+
pub fn from_signed_bytes_be_slice(digits: &[u8]) -> Self {
251+
Self::from_signed_bytes_be(digits.to_vec())
252+
}
253+
}
254+
255+
/// Conversion to bytes
256+
impl CqlVarint {
257+
/// Converts [`CqlVarint`] to an array of bytes in two's
258+
/// complement binary big-endian representation.
259+
pub fn into_signed_bytes_be(self) -> Vec<u8> {
260+
self.0
261+
}
262+
263+
/// Returns a slice of bytes in two's complement
264+
/// binary big-endian representation.
265+
pub fn as_signed_bytes_be_slice(&self) -> &[u8] {
266+
&self.0
267+
}
268+
}
269+
270+
impl From<BigInt> for CqlVarint {
271+
fn from(value: BigInt) -> Self {
272+
Self(value.to_signed_bytes_be())
273+
}
274+
}
275+
276+
impl From<CqlVarint> for BigInt {
277+
fn from(val: CqlVarint) -> Self {
278+
BigInt::from_signed_bytes_be(&val.0)
279+
}
280+
}
281+
218282
/// Native CQL date representation that allows for a bigger range of dates (-262145-1-1 to 262143-12-31).
219283
///
220284
/// Represented as number of days since -5877641-06-23 i.e. 2^31 days before unix epoch.

0 commit comments

Comments
 (0)