|
| 1 | +// Copyright 2023 Datafuse Labs. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +use std::borrow::Cow; |
| 16 | +use std::fmt::Debug; |
| 17 | + |
| 18 | +use crate::array_length; |
| 19 | +use crate::ser::Encoder; |
| 20 | +use crate::Value; |
| 21 | + |
| 22 | +#[derive(Debug, Clone, PartialEq, Eq)] |
| 23 | +pub enum LazyValue<'a> { |
| 24 | + Value(Value<'a>), |
| 25 | + // Raw JSONB bytes |
| 26 | + Raw(Cow<'a, [u8]>), |
| 27 | +} |
| 28 | + |
| 29 | +impl<'a> LazyValue<'a> { |
| 30 | + /// Serialize the JSONB Value into a byte stream. |
| 31 | + pub fn write_to_vec(&self, buf: &mut Vec<u8>) { |
| 32 | + match self { |
| 33 | + LazyValue::Value(v) => { |
| 34 | + let mut encoder = Encoder::new(buf); |
| 35 | + encoder.encode(v) |
| 36 | + } |
| 37 | + LazyValue::Raw(v) => buf.extend_from_slice(v), |
| 38 | + }; |
| 39 | + } |
| 40 | + |
| 41 | + /// Serialize the JSONB Value into a byte stream. |
| 42 | + pub fn to_vec(&self) -> Vec<u8> { |
| 43 | + match self { |
| 44 | + LazyValue::Value(value) => { |
| 45 | + let mut buf = Vec::new(); |
| 46 | + value.write_to_vec(&mut buf); |
| 47 | + buf |
| 48 | + } |
| 49 | + LazyValue::Raw(cow) => cow.to_vec(), |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + // TODO migrate more functions to be methods of LazyValue |
| 54 | + pub fn array_length(&self) -> Option<usize> { |
| 55 | + match self { |
| 56 | + LazyValue::Value(Value::Array(arr)) => Some(arr.len()), |
| 57 | + LazyValue::Raw(cow) => array_length(cow.as_ref()), |
| 58 | + _ => None, |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + pub fn to_value(&'a self) -> Cow<Value<'a>> { |
| 63 | + match self { |
| 64 | + LazyValue::Value(v) => Cow::Borrowed(v), |
| 65 | + LazyValue::Raw(v) => Cow::Owned(crate::from_slice(v.as_ref()).unwrap()), |
| 66 | + } |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +impl<'a> From<Value<'a>> for LazyValue<'a> { |
| 71 | + fn from(value: Value<'a>) -> Self { |
| 72 | + LazyValue::Value(value) |
| 73 | + } |
| 74 | +} |
0 commit comments