oasis_core_runtime/common/sgx/pcs/
utils.rs1use std::{borrow::Cow, mem};
3
4use super::Error;
5
6pub trait TakePrefix: Sized {
7 fn take_prefix(&mut self, mid: usize) -> Result<Self, Error>;
8}
9
10impl<'a, T: 'a> TakePrefix for &'a [T] {
11 fn take_prefix(&mut self, mid: usize) -> Result<Self, Error> {
12 if let (Some(prefix), Some(rest)) = (self.get(..mid), self.get(mid..)) {
13 *self = rest;
14 Ok(prefix)
15 } else {
16 Err(Error::QuoteParseError(
17 "unexpected end of quote".to_string(),
18 ))
19 }
20 }
21}
22
23impl<'a, T: 'a + Clone> TakePrefix for Cow<'a, [T]> {
24 fn take_prefix(&mut self, mid: usize) -> Result<Self, Error> {
25 if mid <= self.len() {
26 match *self {
27 Cow::Borrowed(ref mut slice) => slice.take_prefix(mid).map(Cow::Borrowed),
28 Cow::Owned(ref mut vec) => {
29 let rest = vec.split_off(mid);
30 Ok(Cow::Owned(mem::replace(vec, rest)))
31 }
32 }
33 } else {
34 Err(Error::QuoteParseError(
35 "unexpected end of quote".to_string(),
36 ))
37 }
38 }
39}
40
41impl<'a> TakePrefix for &'a str {
42 fn take_prefix(&mut self, mid: usize) -> Result<Self, Error> {
43 if let (Some(prefix), Some(rest)) = (self.get(..mid), self.get(mid..)) {
44 *self = rest;
45 Ok(prefix)
46 } else {
47 Err(Error::QuoteParseError(
48 "unexpected end of quote".to_string(),
49 ))
50 }
51 }
52}
53
54impl<'a> TakePrefix for Cow<'a, str> {
55 fn take_prefix(&mut self, mid: usize) -> Result<Self, Error> {
56 if mid <= self.len() {
57 match *self {
58 Cow::Borrowed(ref mut slice) => slice.take_prefix(mid).map(Cow::Borrowed),
59 Cow::Owned(ref mut vec) => {
60 let rest = vec.split_off(mid);
61 Ok(Cow::Owned(mem::replace(vec, rest)))
62 }
63 }
64 } else {
65 Err(Error::QuoteParseError(
66 "unexpected end of quote".to_string(),
67 ))
68 }
69 }
70}