chiark / gitweb /
read_limited_bytes: take a `capacity` argument
[hippotat.git] / src / utils.rs
index a254b7b60e51acf0c7084817e78f7eaec94b3242..c210a7d3ce2ab7a0801653cbfb40060f9465058b 100644 (file)
@@ -39,12 +39,16 @@ impl<T> Result<T,ReadLimitedError> {
 }
 
 #[throws(ReadLimitedError)]
-pub async fn read_limited_bytes<S>(limit: usize, stream: &mut S) -> Box<[u8]>
+pub async fn read_limited_bytes<S>(limit: usize, initial: Box<[u8]>,
+                                   capacity: usize,
+                                   stream: &mut S) -> Box<[u8]>
 where S: futures::Stream<Item=Result<hyper::body::Bytes,hyper::Error>>
          + Debug + Unpin,
       // we also require that the Stream is cancellation-safe
 {
-  let mut accum = vec![];
+  let mut accum = initial.into_vec();
+  let capacity = min(limit, capacity);
+  if capacity > accum.len() { accum.reserve(capacity - accum.len()); }
   while let Some(item) = stream.next().await {
     let b = item?;
     accum.extend(b);
@@ -55,11 +59,18 @@ where S: futures::Stream<Item=Result<hyper::body::Bytes,hyper::Error>>
   accum.into()
 }
 
+pub fn time_t_now() -> u64 {
+  SystemTime::now()
+    .duration_since(UNIX_EPOCH)
+    .unwrap_or_else(|_| Duration::default()) // clock is being weird
+    .as_secs()
+}
+
 use sha2::Digest as _;
 
-type HmacH = sha2::Sha256;
-const HMAC_B: usize = 64;
-const HMAC_L: usize = 32;
+pub type HmacH = sha2::Sha256;
+pub const HMAC_B: usize = 64;
+pub const HMAC_L: usize = 32;
 
 pub fn token_hmac(key: &[u8], message: &[u8]) -> [u8; HMAC_L] {
   let key = {
@@ -75,7 +86,7 @@ pub fn token_hmac(key: &[u8], message: &[u8]) -> [u8; HMAC_L] {
   let mut ikey = key;  for k in &mut ikey { *k ^= 0x36; }
   let mut okey = key;  for k in &mut okey { *k ^= 0x5C; }
 
-//dbg!(&key, &ikey, &okey);
+  //dbg!(DumpHex(&key), DumpHex(message), DumpHex(&ikey), DumpHex(&okey));
 
   let h1 = HmacH::new()
     .chain(&ikey)