text:
// THIS FILE IS GENERATED BY api-generator, DO NOT EDIT DIRECTLY!
//
#[derive(Debug, Clone, Default)]
#[doc = "调用 API 所用的路径参数"]
pub struct PathParams {
    r#entry: Option<std::borrow::Cow<'static, str>>,
    extended_segments: Vec<std::borrow::Cow<'static, str>>,
}
impl PathParams {
    #[inline]
    #[must_use]
    #[doc = "追加新的路径段"]
    pub fn push_segment(mut self, segment: impl Into<std::borrow::Cow<'static, str>>) -> Self {
        self.extended_segments.push(segment.into());
        self
    }
    fn build(self) -> Vec<std::borrow::Cow<'static, str>> {
        let mut all_segments: Vec<_> = Default::default();
        if let Some(segment) = self.r#entry {
            all_segments.push(segment);
        }
        all_segments.extend(self.extended_segments);
        all_segments
    }
}
impl PathParams {
    #[inline]
    #[must_use]
    #[doc = "指定目标对象空间与目标对象名称"]
    pub fn set_entry_as_str(mut self, value: impl Into<std::borrow::Cow<'static, str>>) -> Self {
        self.r#entry = Some(qiniu_utils::base64::urlsafe(value.into().as_bytes()).into());
        self
    }
}
#[derive(Debug, Clone, Default)]
#[doc = "调用 API 所用的 URL 查询参数"]
pub struct QueryParams<'a> {
    map: indexmap::IndexMap<qiniu_http_client::QueryPairKey<'a>, qiniu_http_client::QueryPairValue<'a>>,
}
impl<'a> QueryParams<'a> {
    #[inline]
    #[must_use]
    #[doc = "插入一个新的查询参数对"]
    pub fn insert(
        mut self,
        query_pair_key: qiniu_http_client::QueryPairKey<'a>,
        query_pair_value: qiniu_http_client::QueryPairValue<'a>,
    ) -> Self {
        self.map.insert(query_pair_key, query_pair_value);
        self
    }
    fn build(self) -> Vec<qiniu_http_client::QueryPair<'a>> {
        Vec::from_iter(self.map)
    }
}
impl<'a> From<QueryParams<'a>> for Vec<qiniu_http_client::QueryPair<'a>> {
    #[inline]
    fn from(map: QueryParams<'a>) -> Self {
        map.build()
    }
}
impl<'a> QueryParams<'a> {
    #[inline]
    #[must_use]
    #[doc = "如果文件是通过分片上传的，是否返回对应的分片信息"]
    pub fn set_need_parts_as_bool(self, value: bool) -> Self {
        self.insert("needparts".into(), value.to_string().into())
    }
}
#[derive(Clone, Debug, serde :: Serialize, serde :: Deserialize)]
#[serde(transparent)]
#[doc = "获取 API 所用的响应体参数"]
pub struct ResponseBody(serde_json::Value);
impl ResponseBody {
    #[allow(dead_code)]
    pub(crate) fn new(value: serde_json::Value) -> Self {
        Self(value)
    }
}
impl Default for ResponseBody {
    #[inline]
    fn default() -> Self {
        Self(serde_json::Value::Object(Default::default()))
    }
}
impl From<ResponseBody> for serde_json::Value {
    #[inline]
    fn from(val: ResponseBody) -> Self {
        val.0
    }
}
impl AsRef<serde_json::Value> for ResponseBody {
    #[inline]
    fn as_ref(&self) -> &serde_json::Value {
        &self.0
    }
}
impl AsMut<serde_json::Value> for ResponseBody {
    #[inline]
    fn as_mut(&mut self) -> &mut serde_json::Value {
        &mut self.0
    }
}
impl ResponseBody {
    #[doc = "获取 对象大小，单位为字节"]
    pub fn get_size_as_i64(&self) -> i64 {
        self.0.as_object().unwrap().get("fsize").unwrap().as_i64().unwrap()
    }
}
impl ResponseBody {
    #[doc = "设置 对象大小，单位为字节"]
    pub fn set_size_as_i64(&mut self, new: i64) -> Option<i64> {
        self.0
            .as_object_mut()
            .unwrap()
            .insert("fsize".to_owned(), new.into())
            .and_then(|val| val.as_i64())
    }
}
impl ResponseBody {
    #[doc = "获取 对象大小，单位为字节"]
    pub fn get_size_as_u64(&self) -> u64 {
        self.0.as_object().unwrap().get("fsize").unwrap().as_u64().unwrap()
    }
}
impl ResponseBody {
    #[doc = "设置 对象大小，单位为字节"]
    pub fn set_size_as_u64(&mut self, new: u64) -> Option<u64> {
        self.0
            .as_object_mut()
            .unwrap()
            .insert("fsize".to_owned(), new.into())
            .and_then(|val| val.as_u64())
    }
}
impl ResponseBody {
    #[doc = "获取 对象哈希值"]
    pub fn get_hash_as_str(&self) -> &str {
        self.0.as_object().unwrap().get("hash").unwrap().as_str().unwrap()
    }
}
impl ResponseBody {
    #[doc = "设置 对象哈希值"]
    pub fn set_hash_as_str(&mut self, new: String) -> Option<String> {
        self.0
            .as_object_mut()
            .unwrap()
            .insert("hash".to_owned(), new.into())
            .and_then(|val| match val {
                serde_json::Value::String(s) => Some(s),
                _ => None,
            })
    }
}
impl ResponseBody {
    #[doc = "获取 对象 MIME 类型"]
    pub fn get_mime_type_as_str(&self) -> &str {
        self.0.as_object().unwrap().get("mimeType").unwrap().as_str().unwrap()
    }
}
impl ResponseBody {
    #[doc = "设置 对象 MIME 类型"]
    pub fn set_mime_type_as_str(&mut self, new: String) -> Option<String> {
        self.0
            .as_object_mut()
            .unwrap()
            .insert("mimeType".to_owned(), new.into())
            .and_then(|val| match val {
                serde_json::Value::String(s) => Some(s),
                _ => None,
            })
    }
}
impl ResponseBody {
    #[doc = "获取 对象存储类型，`0` 表示普通存储，`1` 表示低频存储，`2` 表示归档存储"]
    pub fn get_type_as_i64(&self) -> i64 {
        self.0.as_object().unwrap().get("type").unwrap().as_i64().unwrap()
    }
}
impl ResponseBody {
    #[doc = "设置 对象存储类型，`0` 表示普通存储，`1` 表示低频存储，`2` 表示归档存储"]
    pub fn set_type_as_i64(&mut self, new: i64) -> Option<i64> {
        self.0
            .as_object_mut()
            .unwrap()
            .insert("type".to_owned(), new.into())
            .and_then(|val| val.as_i64())
    }
}
impl ResponseBody {
    #[doc = "获取 对象存储类型，`0` 表示普通存储，`1` 表示低频存储，`2` 表示归档存储"]
    pub fn get_type_as_u64(&self) -> u64 {
        self.0.as_object().unwrap().get("type").unwrap().as_u64().unwrap()
    }
}
impl ResponseBody {
    #[doc = "设置 对象存储类型，`0` 表示普通存储，`1` 表示低频存储，`2` 表示归档存储"]
    pub fn set_type_as_u64(&mut self, new: u64) -> Option<u64> {
        self.0
            .as_object_mut()
            .unwrap()
            .insert("type".to_owned(), new.into())
            .and_then(|val| val.as_u64())
    }
}
impl ResponseBody {
    #[doc = "获取 文件上传时间，UNIX 时间戳格式，单位为 100 纳秒"]
    pub fn get_put_time_as_i64(&self) -> i64 {
        self.0.as_object().unwrap().get("putTime").unwrap().as_i64().unwrap()
    }
}
impl ResponseBody {
    #[doc = "设置 文件上传时间，UNIX 时间戳格式，单位为 100 纳秒"]
    pub fn set_put_time_as_i64(&mut self, new: i64) -> Option<i64> {
        self.0
            .as_object_mut()
            .unwrap()
            .insert("putTime".to_owned(), new.into())
            .and_then(|val| val.as_i64())
    }
}
impl ResponseBody {
    #[doc = "获取 文件上传时间，UNIX 时间戳格式，单位为 100 纳秒"]
    pub fn get_put_time_as_u64(&self) -> u64 {
        self.0.as_object().unwrap().get("putTime").unwrap().as_u64().unwrap()
    }
}
impl ResponseBody {
    #[doc = "设置 文件上传时间，UNIX 时间戳格式，单位为 100 纳秒"]
    pub fn set_put_time_as_u64(&mut self, new: u64) -> Option<u64> {
        self.0
            .as_object_mut()
            .unwrap()
            .insert("putTime".to_owned(), new.into())
            .and_then(|val| val.as_u64())
    }
}
impl ResponseBody {
    #[doc = "获取 归档存储文件的解冻状态，`2` 表示解冻完成，`1` 表示解冻中；归档文件冻结时，不返回该字段"]
    pub fn get_unfreezing_status_as_i64(&self) -> Option<i64> {
        self.0
            .as_object()
            .and_then(|obj| obj.get("restoreStatus"))
            .and_then(|val| val.as_i64())
    }
}
impl ResponseBody {
    #[doc = "设置 归档存储文件的解冻状态，`2` 表示解冻完成，`1` 表示解冻中；归档文件冻结时，不返回该字段"]
    pub fn set_unfreezing_status_as_i64(&mut self, new: i64) -> Option<i64> {
        self.0.as_object_mut().and_then(|object| {
            object
                .insert("restoreStatus".to_owned(), new.into())
                .and_then(|val| val.as_i64())
        })
    }
}
impl ResponseBody {
    #[doc = "获取 归档存储文件的解冻状态，`2` 表示解冻完成，`1` 表示解冻中；归档文件冻结时，不返回该字段"]
    pub fn get_unfreezing_status_as_u64(&self) -> Option<u64> {
        self.0
            .as_object()
            .and_then(|obj| obj.get("restoreStatus"))
            .and_then(|val| val.as_u64())
    }
}
impl ResponseBody {
    #[doc = "设置 归档存储文件的解冻状态，`2` 表示解冻完成，`1` 表示解冻中；归档文件冻结时，不返回该字段"]
    pub fn set_unfreezing_status_as_u64(&mut self, new: u64) -> Option<u64> {
        self.0.as_object_mut().and_then(|object| {
            object
                .insert("restoreStatus".to_owned(), new.into())
                .and_then(|val| val.as_u64())
        })
    }
}
impl ResponseBody {
    #[doc = "获取 文件状态。`1` 表示禁用；只有禁用状态的文件才会返回该字段"]
    pub fn get_status_as_i64(&self) -> Option<i64> {
        self.0
            .as_object()
            .and_then(|obj| obj.get("status"))
            .and_then(|val| val.as_i64())
    }
}
impl ResponseBody {
    #[doc = "设置 文件状态。`1` 表示禁用；只有禁用状态的文件才会返回该字段"]
    pub fn set_status_as_i64(&mut self, new: i64) -> Option<i64> {
        self.0.as_object_mut().and_then(|object| {
            object
                .insert("status".to_owned(), new.into())
                .and_then(|val| val.as_i64())
        })
    }
}
impl ResponseBody {
    #[doc = "获取 文件状态。`1` 表示禁用；只有禁用状态的文件才会返回该字段"]
    pub fn get_status_as_u64(&self) -> Option<u64> {
        self.0
            .as_object()
            .and_then(|obj| obj.get("status"))
            .and_then(|val| val.as_u64())
    }
}
impl ResponseBody {
    #[doc = "设置 文件状态。`1` 表示禁用；只有禁用状态的文件才会返回该字段"]
    pub fn set_status_as_u64(&mut self, new: u64) -> Option<u64> {
        self.0.as_object_mut().and_then(|object| {
            object
                .insert("status".to_owned(), new.into())
                .and_then(|val| val.as_u64())
        })
    }
}
impl ResponseBody {
    #[doc = "获取 对象 MD5 值，只有通过直传文件和追加文件 API 上传的文件，服务端确保有该字段返回"]
    pub fn get_md_5_as_str(&self) -> Option<&str> {
        self.0
            .as_object()
            .and_then(|obj| obj.get("md5"))
            .and_then(|val| val.as_str())
    }
}
impl ResponseBody {
    #[doc = "设置 对象 MD5 值，只有通过直传文件和追加文件 API 上传的文件，服务端确保有该字段返回"]
    pub fn set_md_5_as_str(&mut self, new: String) -> Option<String> {
        self.0.as_object_mut().and_then(|object| {
            object.insert("md5".to_owned(), new.into()).and_then(|val| match val {
                serde_json::Value::String(s) => Some(s),
                _ => None,
            })
        })
    }
}
impl ResponseBody {
    #[doc = "获取 文件过期删除日期，UNIX 时间戳格式，文件在设置过期时间后才会返回该字段"]
    pub fn get_expiration_time_as_i64(&self) -> Option<i64> {
        self.0
            .as_object()
            .and_then(|obj| obj.get("expiration"))
            .and_then(|val| val.as_i64())
    }
}
impl ResponseBody {
    #[doc = "设置 文件过期删除日期，UNIX 时间戳格式，文件在设置过期时间后才会返回该字段"]
    pub fn set_expiration_time_as_i64(&mut self, new: i64) -> Option<i64> {
        self.0.as_object_mut().and_then(|object| {
            object
                .insert("expiration".to_owned(), new.into())
                .and_then(|val| val.as_i64())
        })
    }
}
impl ResponseBody {
    #[doc = "获取 文件过期删除日期，UNIX 时间戳格式，文件在设置过期时间后才会返回该字段"]
    pub fn get_expiration_time_as_u64(&self) -> Option<u64> {
        self.0
            .as_object()
            .and_then(|obj| obj.get("expiration"))
            .and_then(|val| val.as_u64())
    }
}
impl ResponseBody {
    #[doc = "设置 文件过期删除日期，UNIX 时间戳格式，文件在设置过期时间后才会返回该字段"]
    pub fn set_expiration_time_as_u64(&mut self, new: u64) -> Option<u64> {
        self.0.as_object_mut().and_then(|object| {
            object
                .insert("expiration".to_owned(), new.into())
                .and_then(|val| val.as_u64())
        })
    }
}
impl ResponseBody {
    #[doc = "获取 文件生命周期中转为低频存储的日期，UNIX 时间戳格式，文件在设置转低频后才会返回该字段"]
    pub fn get_transition_to_ia_time_as_i64(&self) -> Option<i64> {
        self.0
            .as_object()
            .and_then(|obj| obj.get("transitionToIA"))
            .and_then(|val| val.as_i64())
    }
}
impl ResponseBody {
    #[doc = "设置 文件生命周期中转为低频存储的日期，UNIX 时间戳格式，文件在设置转低频后才会返回该字段"]
    pub fn set_transition_to_ia_time_as_i64(&mut self, new: i64) -> Option<i64> {
        self.0.as_object_mut().and_then(|object| {
            object
                .insert("transitionToIA".to_owned(), new.into())
                .and_then(|val| val.as_i64())
        })
    }
}
impl ResponseBody {
    #[doc = "获取 文件生命周期中转为低频存储的日期，UNIX 时间戳格式，文件在设置转低频后才会返回该字段"]
    pub fn get_transition_to_ia_time_as_u64(&self) -> Option<u64> {
        self.0
            .as_object()
            .and_then(|obj| obj.get("transitionToIA"))
            .and_then(|val| val.as_u64())
    }
}
impl ResponseBody {
    #[doc = "设置 文件生命周期中转为低频存储的日期，UNIX 时间戳格式，文件在设置转低频后才会返回该字段"]
    pub fn set_transition_to_ia_time_as_u64(&mut self, new: u64) -> Option<u64> {
        self.0.as_object_mut().and_then(|object| {
            object
                .insert("transitionToIA".to_owned(), new.into())
                .and_then(|val| val.as_u64())
        })
    }
}
impl ResponseBody {
    #[doc = "获取 文件生命周期中转为归档存储的日期，UNIX 时间戳格式，文件在设置转归档后才会返回该字段"]
    pub fn get_transition_to_archive_time_as_i64(&self) -> Option<i64> {
        self.0
            .as_object()
            .and_then(|obj| obj.get("transitionToARCHIVE"))
            .and_then(|val| val.as_i64())
    }
}
impl ResponseBody {
    #[doc = "设置 文件生命周期中转为归档存储的日期，UNIX 时间戳格式，文件在设置转归档后才会返回该字段"]
    pub fn set_transition_to_archive_time_as_i64(&mut self, new: i64) -> Option<i64> {
        self.0.as_object_mut().and_then(|object| {
            object
                .insert("transitionToARCHIVE".to_owned(), new.into())
                .and_then(|val| val.as_i64())
        })
    }
}
impl ResponseBody {
    #[doc = "获取 文件生命周期中转为归档存储的日期，UNIX 时间戳格式，文件在设置转归档后才会返回该字段"]
    pub fn get_transition_to_archive_time_as_u64(&self) -> Option<u64> {
        self.0
            .as_object()
            .and_then(|obj| obj.get("transitionToARCHIVE"))
            .and_then(|val| val.as_u64())
    }
}
impl ResponseBody {
    #[doc = "设置 文件生命周期中转为归档存储的日期，UNIX 时间戳格式，文件在设置转归档后才会返回该字段"]
    pub fn set_transition_to_archive_time_as_u64(&mut self, new: u64) -> Option<u64> {
        self.0.as_object_mut().and_then(|object| {
            object
                .insert("transitionToARCHIVE".to_owned(), new.into())
                .and_then(|val| val.as_u64())
        })
    }
}
#[derive(Clone, Debug, serde :: Serialize, serde :: Deserialize)]
#[serde(transparent)]
#[doc = "每个分片的大小"]
pub struct PartSizes(serde_json::Value);
impl PartSizes {
    #[allow(dead_code)]
    pub(crate) fn new(value: serde_json::Value) -> Self {
        Self(value)
    }
}
impl Default for PartSizes {
    #[inline]
    fn default() -> Self {
        Self(serde_json::Value::Array(Default::default()))
    }
}
impl From<PartSizes> for serde_json::Value {
    #[inline]
    fn from(val: PartSizes) -> Self {
        val.0
    }
}
impl AsRef<serde_json::Value> for PartSizes {
    #[inline]
    fn as_ref(&self) -> &serde_json::Value {
        &self.0
    }
}
impl AsMut<serde_json::Value> for PartSizes {
    #[inline]
    fn as_mut(&mut self) -> &mut serde_json::Value {
        &mut self.0
    }
}
impl PartSizes {
    #[doc = "获取数组的长度"]
    pub fn len(&self) -> usize {
        self.0.as_array().unwrap().len()
    }
    #[doc = "数组是否为空"]
    pub fn is_empty(&self) -> bool {
        self.0.as_array().unwrap().is_empty()
    }
}
impl PartSizes {
    #[doc = "解析 JSON 得到整型列表"]
    pub fn to_i64_vec(&self) -> Vec<i64> {
        self.0
            .as_array()
            .unwrap()
            .iter()
            .map(|ele| ele.as_i64().unwrap())
            .collect()
    }
}
impl PartSizes {
    #[doc = "解析 JSON 得到无符号整型列表"]
    pub fn to_u64_vec(&self) -> Vec<u64> {
        self.0
            .as_array()
            .unwrap()
            .iter()
            .map(|ele| ele.as_u64().unwrap())
            .collect()
    }
}
impl PartSizes {
    #[doc = "在列表的指定位置移出 JSON i64 整型"]
    pub fn remove_as_i64(&mut self, index: usize) -> Option<i64> {
        match self.0.as_array_mut().unwrap().remove(index) {
            serde_json::Value::Number(s) => s.as_i64(),
            _ => None,
        }
    }
}
impl PartSizes {
    #[doc = "在列表尾部取出 JSON i64 整型"]
    pub fn pop_as_i64(&mut self) -> Option<i64> {
        self.0.as_array_mut().unwrap().pop().and_then(|val| match val {
            serde_json::Value::Number(s) => s.as_i64(),
            _ => None,
        })
    }
}
impl PartSizes {
    #[doc = "在列表的指定位置移出 JSON u64 整型"]
    pub fn remove_as_u64(&mut self, index: usize) -> Option<u64> {
        match self.0.as_array_mut().unwrap().remove(index) {
            serde_json::Value::Number(s) => s.as_u64(),
            _ => None,
        }
    }
}
impl PartSizes {
    #[doc = "在列表尾部取出 JSON u64 整型"]
    pub fn pop_as_u64(&mut self) -> Option<u64> {
        self.0.as_array_mut().unwrap().pop().and_then(|val| match val {
            serde_json::Value::Number(s) => s.as_u64(),
            _ => None,
        })
    }
}
impl From<Vec<i8>> for PartSizes {
    #[inline]
    fn from(val: Vec<i8>) -> Self {
        Self(serde_json::Value::from(val))
    }
}
impl PartSizes {
    #[doc = "在列表的指定位置插入 JSON i8 整型"]
    pub fn insert_i8(&mut self, index: usize, val: i8) {
        self.0.as_array_mut().unwrap().insert(index, val.into());
    }
}
impl PartSizes {
    #[doc = "在列表尾部追加 JSON i8 整型"]
    pub fn push_i8(&mut self, val: i8) {
        self.0.as_array_mut().unwrap().push(val.into());
    }
}
impl From<Vec<i16>> for PartSizes {
    #[inline]
    fn from(val: Vec<i16>) -> Self {
        Self(serde_json::Value::from(val))
    }
}
impl PartSizes {
    #[doc = "在列表的指定位置插入 JSON i16 整型"]
    pub fn insert_i16(&mut self, index: usize, val: i16) {
        self.0.as_array_mut().unwrap().insert(index, val.into());
    }
}
impl PartSizes {
    #[doc = "在列表尾部追加 JSON i16 整型"]
    pub fn push_i16(&mut self, val: i16) {
        self.0.as_array_mut().unwrap().push(val.into());
    }
}
impl From<Vec<i32>> for PartSizes {
    #[inline]
    fn from(val: Vec<i32>) -> Self {
        Self(serde_json::Value::from(val))
    }
}
impl PartSizes {
    #[doc = "在列表的指定位置插入 JSON i32 整型"]
    pub fn insert_i32(&mut self, index: usize, val: i32) {
        self.0.as_array_mut().unwrap().insert(index, val.into());
    }
}
impl PartSizes {
    #[doc = "在列表尾部追加 JSON i32 整型"]
    pub fn push_i32(&mut self, val: i32) {
        self.0.as_array_mut().unwrap().push(val.into());
    }
}
impl From<Vec<i64>> for PartSizes {
    #[inline]
    fn from(val: Vec<i64>) -> Self {
        Self(serde_json::Value::from(val))
    }
}
impl PartSizes {
    #[doc = "在列表的指定位置插入 JSON i64 整型"]
    pub fn insert_i64(&mut self, index: usize, val: i64) {
        self.0.as_array_mut().unwrap().insert(index, val.into());
    }
}
impl PartSizes {
    #[doc = "在列表尾部追加 JSON i64 整型"]
    pub fn push_i64(&mut self, val: i64) {
        self.0.as_array_mut().unwrap().push(val.into());
    }
}
impl From<Vec<isize>> for PartSizes {
    #[inline]
    fn from(val: Vec<isize>) -> Self {
        Self(serde_json::Value::from(val))
    }
}
impl PartSizes {
    #[doc = "在列表的指定位置插入 JSON isize 整型"]
    pub fn insert_isize(&mut self, index: usize, val: isize) {
        self.0.as_array_mut().unwrap().insert(index, val.into());
    }
}
impl PartSizes {
    #[doc = "在列表尾部追加 JSON isize 整型"]
    pub fn push_isize(&mut self, val: isize) {
        self.0.as_array_mut().unwrap().push(val.into());
    }
}
impl From<Vec<u8>> for PartSizes {
    #[inline]
    fn from(val: Vec<u8>) -> Self {
        Self(serde_json::Value::from(val))
    }
}
impl PartSizes {
    #[doc = "在列表的指定位置插入 JSON u8 整型"]
    pub fn insert_u8(&mut self, index: usize, val: u8) {
        self.0.as_array_mut().unwrap().insert(index, val.into());
    }
}
impl PartSizes {
    #[doc = "在列表尾部追加 JSON u8 整型"]
    pub fn push_u8(&mut self, val: u8) {
        self.0.as_array_mut().unwrap().push(val.into());
    }
}
impl From<Vec<u16>> for PartSizes {
    #[inline]
    fn from(val: Vec<u16>) -> Self {
        Self(serde_json::Value::from(val))
    }
}
impl PartSizes {
    #[doc = "在列表的指定位置插入 JSON u16 整型"]
    pub fn insert_u16(&mut self, index: usize, val: u16) {
        self.0.as_array_mut().unwrap().insert(index, val.into());


text:
use std::ffi::OsStr;
use std::io;
use std::process::{self, Command};

use crate::errors::*;
use crate::utils::utils::ExitCode;

pub fn run_command_for_dir<S: AsRef<OsStr>>(
    mut cmd: Command,
    arg0: &str,
    args: &[S],
) -> Result<ExitCode> {
    cmd.args(args);

    // FIXME rust-lang/rust#32254. It's not clear to me
    // when and why this is needed.
    // TODO: currentprocess support for mocked file descriptor inheritance here: until
    // then tests that depend on rustups stdin being inherited won't work in-process.
    cmd.stdin(process::Stdio::inherit());

    return exec(&mut cmd).chain_err(|| crate::ErrorKind::RunningCommand {
        name: OsStr::new(arg0).to_owned(),
    });

    #[cfg(unix)]
    fn exec(cmd: &mut Command) -> io::Result<ExitCode> {
        use std::os::unix::prelude::*;
        Err(cmd.exec())
    }

    #[cfg(windows)]
    fn exec(cmd: &mut Command) -> io::Result<ExitCode> {
        use winapi::shared::minwindef::{BOOL, DWORD, FALSE, TRUE};
        use winapi::um::consoleapi::SetConsoleCtrlHandler;

        unsafe extern "system" fn ctrlc_handler(_: DWORD) -> BOOL {
            // Do nothing. Let the child process handle it.
            TRUE
        }
        unsafe {
            if SetConsoleCtrlHandler(Some(ctrlc_handler), TRUE) == FALSE {
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    "Unable to set console handler",
                ));
            }
        }
        let status = cmd.status()?;
        Ok(ExitCode(status.code().unwrap()))
    }
}

domain: rust


text:
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
*/

pub type Chunk=i64;
pub type DChunk=i128;
pub const CHUNK:usize=64;


text:
//! The `solana` library implements the Solana high-performance blockchain architecture.
//! It includes a full Rust implementation of the architecture (see
//! [Validator](server/struct.Validator.html)) as well as hooks to GPU implementations of its most
//! paralellizable components (i.e. [SigVerify](sigverify/index.html)).  It also includes
//! command-line tools to spin up validators and a Rust library
//!

pub mod accounts_background_service;
pub mod accounts_hash_verifier;
pub mod banking_stage;
pub mod broadcast_stage;
pub mod cluster_info_vote_listener;
pub mod commitment;
pub mod commitment_service;
mod deprecated;
pub mod shred_fetch_stage;
#[macro_use]
pub mod contact_info;
pub mod bank_weight_fork_choice;
pub mod cluster_info;
pub mod cluster_slots;
pub mod consensus;
pub mod crds;
pub mod crds_gossip;
pub mod crds_gossip_error;
pub mod crds_gossip_pull;
pub mod crds_gossip_push;
pub mod crds_value;
pub mod epoch_slots;
pub mod fetch_stage;
pub mod fork_choice;
pub mod gen_keys;
pub mod gossip_service;
pub mod heaviest_subtree_fork_choice;
pub mod ledger_cleanup_service;
pub mod local_vote_signer_service;
pub mod non_circulating_supply;
pub mod poh_recorder;
pub mod poh_service;
pub mod progress_map;
pub mod pubkey_references;
pub mod repair_response;
pub mod repair_service;
pub mod repair_weight;
pub mod repair_weighted_traversal;
pub mod replay_stage;
mod result;
pub mod retransmit_stage;
pub mod rewards_recorder_service;
pub mod rpc;
pub mod rpc_error;
pub mod rpc_health;
pub mod rpc_pubsub;
pub mod rpc_pubsub_service;
pub mod rpc_service;
pub mod rpc_subscriptions;
pub mod send_transaction_service;
pub mod serve_repair;
pub mod serve_repair_service;
pub mod sigverify;
pub mod sigverify_shreds;
pub mod sigverify_stage;
pub mod snapshot_packager_service;
pub mod tpu;
pub mod transaction_status_service;
pub mod tree_diff;
pub mod tvu;
pub mod validator;
pub mod verified_vote_packets;
pub mod weighted_shuffle;
pub mod window_service;

#[macro_use]
extern crate solana_bpf_loader_program;

#[macro_use]
extern crate solana_budget_program;

#[macro_use]
extern crate log;

#[macro_use]
extern crate serde_derive;

#[cfg(test)]
#[macro_use]
extern crate serde_json;

#[macro_use]
extern crate solana_metrics;

#[cfg(test)]
#[macro_use]
extern crate matches;


text:
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

fn main() {
    let y = 1;
    match y {
       a | b => {} //~  ERROR variable `a` is not bound in all patterns
                   //~^ ERROR variable `b` is not bound in all patterns
    }
}


text:
use crate::consts::PGID;

/// bucket represents the on-file representation of a bucket.
/// This is stored as the "value" of a bucket key. If the bucket is small enough,
/// then its root page can be stored inline in the "value", after the bucket
/// header. In the case of inline buckets, the "root" will be 0.
#[derive(Clone, Debug)]
#[repr(C)]
pub struct IBucket {
	/// page id of the bucket's root-level page
	pub root: PGID,

	/// monotonically incrementing, used by next_sequence()
	pub sequence: u64,
}

impl IBucket {
	pub(crate) const SIZE: usize = std::mem::size_of::<Self>();

	pub(crate) fn new() -> IBucket {
		IBucket {
			root: 0,
			sequence: 0,
		}
	}
}


text:
#![warn(
    unused_extern_crates,
    missing_debug_implementations,
    missing_copy_implementations,
    rust_2018_idioms,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::fallible_impl_from,
    clippy::cast_precision_loss,
    clippy::cast_possible_wrap,
    clippy::dbg_macro
)]
#![cfg_attr(not(test), warn(clippy::unwrap_used))]
#![forbid(unsafe_code)]
#![allow(non_snake_case)]

#[macro_use]
mod utils {

    macro_rules! impl_try_from_parent_enum {
        ($type:ident, $parent:ident) => {
            impl TryFrom<$parent> for $type {
                type Error = anyhow::Error;
                fn try_from(from: $parent) -> Result<Self> {
                    if let $parent::$type(inner) = from {
                        Ok(inner)
                    } else {
                        Err(anyhow::anyhow!(
                            "Failed to convert parent state to child state"
                        ))
                    }
                }
            }
        };
    }

    macro_rules! impl_from_child_enum {
        ($type:ident, $parent:ident) => {
            impl From<$type> for $parent {
                fn from(from: $type) -> Self {
                    $parent::$type(from)
                }
            }
        };
    }
}

pub mod alice;
pub mod bitcoin;
pub mod bob;
pub mod monero;
pub mod transport;


text:
pub mod cuda_runtime;
pub mod data_budget;
pub mod packet;
pub mod perf_libs;
pub mod recycler;
pub mod recycler_cache;
pub mod sigverify;
pub mod test_tx;
pub mod thread;

#[macro_use]
extern crate lazy_static;

#[macro_use]
extern crate log;

#[cfg(test)]
#[macro_use]
extern crate matches;

#[macro_use]
extern crate analog_metrics;

fn is_rosetta_emulated() -> bool {
    #[cfg(target_os = "macos")]
    {
        use std::str::FromStr;
        std::process::Command::new("sysctl")
            .args(&["-in", "sysctl.proc_translated"])
            .output()
            .map_err(|_| ())
            .and_then(|output| String::from_utf8(output.stdout).map_err(|_| ()))
            .and_then(|stdout| u8::from_str(stdout.trim()).map_err(|_| ()))
            .map(|enabled| enabled == 1)
            .unwrap_or(false)
    }
    #[cfg(not(target_os = "macos"))]
    {
        false
    }
}

pub fn report_target_features() {
    warn!(
        "CUDA is {}abled",
        if crate::perf_libs::api().is_some() {
            "en"
        } else {
            "dis"
        }
    );

    // Validator binaries built on a machine with AVX support will generate invalid opcodes
    // when run on machines without AVX causing a non-obvious process abort.  Instead detect
    // the mismatch and error cleanly.
    if !is_rosetta_emulated() {
        #[cfg(build_target_feature_avx)]
        {
            if is_x86_feature_detected!("avx") {
                info!("AVX detected");
            } else {
                error!(
                "Incompatible CPU detected: missing AVX support. Please build from source on the target"
            );
                std::process::abort();
            }
        }

        #[cfg(build_target_feature_avx2)]
        {
            if is_x86_feature_detected!("avx2") {
                info!("AVX2 detected");
            } else {
                error!(
                    "Incompatible CPU detected: missing AVX2 support. Please build from source on the target"
                );
                std::process::abort();
            }
        }
    }
}


text:
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::prefix::{
    ENCODER_CAPACITY, ENCODER_DUPLICATE, ENCODER_INSERT_WITH_NAME_LITERAL,
    ENCODER_INSERT_WITH_NAME_REF_DYNAMIC, ENCODER_INSERT_WITH_NAME_REF_STATIC, NO_PREFIX,
};
use crate::qpack_send_buf::QpackData;
use crate::reader::{IntReader, LiteralReader, ReadByte, Reader};
use crate::Res;
use neqo_common::{qdebug, qtrace};
use std::mem;

// The encoder only uses InsertWithNameLiteral, therefore clippy is complaining about dead_code.
// We may decide to use othe instruction in the future.
// All instructions are used for testing, therefore they are defined.
#[allow(dead_code)]
#[derive(Debug, PartialEq)]
pub enum EncoderInstruction<'a> {
    Capacity { value: u64 },
    InsertWithNameRefStatic { index: u64, value: &'a [u8] },
    InsertWithNameRefDynamic { index: u64, value: &'a [u8] },
    InsertWithNameLiteral { name: &'a [u8], value: &'a [u8] },
    Duplicate { index: u64 },
    NoInstruction,
}

impl<'a> EncoderInstruction<'a> {
    pub(crate) fn marshal(&self, enc: &mut QpackData, use_huffman: bool) {
        match self {
            Self::Capacity { value } => {
                enc.encode_prefixed_encoded_int(ENCODER_CAPACITY, *value);
            }
            Self::InsertWithNameRefStatic { index, value } => {
                enc.encode_prefixed_encoded_int(ENCODER_INSERT_WITH_NAME_REF_STATIC, *index);
                enc.encode_literal(use_huffman, NO_PREFIX, value);
            }
            Self::InsertWithNameRefDynamic { index, value } => {
                enc.encode_prefixed_encoded_int(ENCODER_INSERT_WITH_NAME_REF_DYNAMIC, *index);
                enc.encode_literal(use_huffman, NO_PREFIX, value);
            }
            Self::InsertWithNameLiteral { name, value } => {
                enc.encode_literal(use_huffman, ENCODER_INSERT_WITH_NAME_LITERAL, name);
                enc.encode_literal(use_huffman, NO_PREFIX, value);
            }
            Self::Duplicate { index } => {
                enc.encode_prefixed_encoded_int(ENCODER_DUPLICATE, *index);
            }
            Self::NoInstruction => {}
        }
    }
}

#[derive(Debug)]
enum EncoderInstructionReaderState {
    ReadInstruction,
    ReadFirstInt { reader: IntReader },
    ReadFirstLiteral { reader: LiteralReader },
    ReadSecondLiteral { reader: LiteralReader },
    Done,
}

#[derive(Debug, PartialEq)]
pub enum DecodedEncoderInstruction {
    Capacity { value: u64 },
    InsertWithNameRefStatic { index: u64, value: Vec<u8> },
    InsertWithNameRefDynamic { index: u64, value: Vec<u8> },
    InsertWithNameLiteral { name: Vec<u8>, value: Vec<u8> },
    Duplicate { index: u64 },
    NoInstruction,
}

impl<'a> From<&'a EncoderInstruction<'a>> for DecodedEncoderInstruction {
    fn from(inst: &'a EncoderInstruction) -> Self {
        match inst {
            EncoderInstruction::Capacity { value } => Self::Capacity { value: *value },
            EncoderInstruction::InsertWithNameRefStatic { index, value } => {
                Self::InsertWithNameRefStatic {
                    index: *index,
                    value: value.to_vec(),
                }
            }
            EncoderInstruction::InsertWithNameRefDynamic { index, value } => {
                Self::InsertWithNameRefDynamic {
                    index: *index,
                    value: value.to_vec(),
                }
            }
            EncoderInstruction::InsertWithNameLiteral { name, value } => {
                Self::InsertWithNameLiteral {
                    name: name.to_vec(),
                    value: value.to_vec(),
                }
            }
            EncoderInstruction::Duplicate { index } => Self::Duplicate { index: *index },
            EncoderInstruction::NoInstruction => Self::NoInstruction,
        }
    }
}

#[derive(Debug)]
pub struct EncoderInstructionReader {
    state: EncoderInstructionReaderState,
    instruction: DecodedEncoderInstruction,
}

impl ::std::fmt::Display for EncoderInstructionReader {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(
            f,
            "EncoderInstructionReader state={:?} instruction:{:?}",
            self.state, self.instruction
        )
    }
}

impl EncoderInstructionReader {
    pub fn new() -> Self {
        Self {
            state: EncoderInstructionReaderState::ReadInstruction,
            instruction: DecodedEncoderInstruction::NoInstruction,
        }
    }

    fn decode_instruction_from_byte(&mut self, b: u8) {
        self.instruction = if ENCODER_INSERT_WITH_NAME_REF_STATIC.cmp_prefix(b) {
            DecodedEncoderInstruction::InsertWithNameRefStatic {
                index: 0,
                value: Vec::new(),
            }
        } else if ENCODER_INSERT_WITH_NAME_REF_DYNAMIC.cmp_prefix(b) {
            DecodedEncoderInstruction::InsertWithNameRefDynamic {
                index: 0,
                value: Vec::new(),
            }
        } else if ENCODER_INSERT_WITH_NAME_LITERAL.cmp_prefix(b) {
            DecodedEncoderInstruction::InsertWithNameLiteral {
                name: Vec::new(),
                value: Vec::new(),
            }
        } else if ENCODER_CAPACITY.cmp_prefix(b) {
            DecodedEncoderInstruction::Capacity { value: 0 }
        } else if ENCODER_DUPLICATE.cmp_prefix(b) {
            DecodedEncoderInstruction::Duplicate { index: 0 }
        } else {
            unreachable!("The above patterns match everything.");
        };
        qdebug!([self], "instruction decoded");
    }

    fn decode_instruction_type<T: ReadByte + Reader>(&mut self, recv: &mut T) -> Res<()> {
        let b = recv.read_byte()?;

        self.decode_instruction_from_byte(b);
        match self.instruction {
            DecodedEncoderInstruction::Capacity { .. }
            | DecodedEncoderInstruction::Duplicate { .. } => {
                self.state = EncoderInstructionReaderState::ReadFirstInt {
                    reader: IntReader::new(b, ENCODER_CAPACITY.len()),
                }
            }
            DecodedEncoderInstruction::InsertWithNameRefStatic { .. }
            | DecodedEncoderInstruction::InsertWithNameRefDynamic { .. } => {
                self.state = EncoderInstructionReaderState::ReadFirstInt {
                    reader: IntReader::new(b, ENCODER_INSERT_WITH_NAME_REF_STATIC.len()),
                }
            }
            DecodedEncoderInstruction::InsertWithNameLiteral { .. } => {
                self.state = EncoderInstructionReaderState::ReadFirstLiteral {
                    reader: LiteralReader::new_with_first_byte(
                        b,
                        ENCODER_INSERT_WITH_NAME_LITERAL.len(),
                    ),
                }
            }
            DecodedEncoderInstruction::NoInstruction => {
                unreachable!("We must have instruction at this point.");
            }
        }
        Ok(())
    }

    /// ### Errors
    ///  1) `NeedMoreData` if the reader needs more data
    ///  2) `ClosedCriticalStream`
    ///  3) other errors will be translated to `EncoderStream` by the caller of this function.
    pub fn read_instructions<T: ReadByte + Reader>(
        &mut self,
        recv: &mut T,
    ) -> Res<DecodedEncoderInstruction> {
        qdebug!([self], "reading instructions");
        loop {
            match &mut self.state {
                EncoderInstructionReaderState::ReadInstruction => {
                    self.decode_instruction_type(recv)?;
                }
                EncoderInstructionReaderState::ReadFirstInt { reader } => {
                    let val = reader.read(recv)?;

                    qtrace!([self], "First varint read {}", val);
                    match &mut self.instruction {
                        DecodedEncoderInstruction::Capacity { value: v, .. }
                        | DecodedEncoderInstruction::Duplicate { index: v } => {
                            *v = val;
                            self.state = EncoderInstructionReaderState::Done;
                        }
                        DecodedEncoderInstruction::InsertWithNameRefStatic { index, .. }
                        | DecodedEncoderInstruction::InsertWithNameRefDynamic { index, .. } => {
                            *index = val;
                            self.state = EncoderInstructionReaderState::ReadFirstLiteral {
                                reader: LiteralReader::default(),
                            };
                        }
                        _ => unreachable!("This instruction cannot be in this state."),
                    }
                }
                EncoderInstructionReaderState::ReadFirstLiteral { reader } => {
                    let val = reader.read(recv)?;

                    qtrace!([self], "first literal read {:?}", val);
                    match &mut self.instruction {
                        DecodedEncoderInstruction::InsertWithNameRefStatic { value, .. }
                        | DecodedEncoderInstruction::InsertWithNameRefDynamic { value, .. } => {
                            *value = val;
                            self.state = EncoderInstructionReaderState::Done;
                        }
                        DecodedEncoderInstruction::InsertWithNameLiteral { name, .. } => {
                            *name = val;
                            self.state = EncoderInstructionReaderState::ReadSecondLiteral {
                                reader: LiteralReader::default(),
                            };
                        }
                        _ => unreachable!("This instruction cannot be in this state."),
                    }
                }
                EncoderInstructionReaderState::ReadSecondLiteral { reader } => {
                    let val = reader.read(recv)?;

                    qtrace!([self], "second literal read {:?}", val);
                    match &mut self.instruction {
                        DecodedEncoderInstruction::InsertWithNameLiteral { value, .. } => {
                            *value = val;
                            self.state = EncoderInstructionReaderState::Done;
                        }
                        _ => unreachable!("This instruction cannot be in this state."),
                    }
                }
                EncoderInstructionReaderState::Done => {}
            }
            if matches!(self.state, EncoderInstructionReaderState::Done) {
                self.state = EncoderInstructionReaderState::ReadInstruction;
                break Ok(mem::replace(
                    &mut self.instruction,
                    DecodedEncoderInstruction::NoInstruction,
                ));
            }
        }
    }
}

#[cfg(test)]
mod test {

    use super::{EncoderInstruction, EncoderInstructionReader, QpackData};
    use crate::reader::test_receiver::TestReceiver;
    use crate::Error;

    fn test_encoding_decoding(instruction: &EncoderInstruction, use_huffman: bool) {
        let mut buf = QpackData::default();
        instruction.marshal(&mut buf, use_huffman);
        let mut test_receiver: TestReceiver = TestReceiver::default();
        test_receiver.write(&buf);
        let mut reader = EncoderInstructionReader::new();
        assert_eq!(
            reader.read_instructions(&mut test_receiver).unwrap(),
            instruction.into()
        );
    }

    #[test]
    fn test_encoding_decoding_instructions() {
        test_encoding_decoding(&EncoderInstruction::Capacity { value: 1 }, false);
        test_encoding_decoding(&EncoderInstruction::Capacity { value: 10_000 }, false);

        test_encoding_decoding(
            &EncoderInstruction::InsertWithNameRefStatic {
                index: 1,
                value: &[0x62, 0x64, 0x65],
            },
            false,
        );
        test_encoding_decoding(
            &EncoderInstruction::InsertWithNameRefStatic {
                index: 1,
                value: &[0x62, 0x64, 0x65],
            },
            true,
        );
        test_encoding_decoding(
            &EncoderInstruction::InsertWithNameRefStatic {
                index: 10_000,
                value: &[0x62, 0x64, 0x65],
            },
            false,
        );
        test_encoding_decoding(
            &EncoderInstruction::InsertWithNameRefStatic {
                index: 10_000,
                value: &[0x62, 0x64, 0x65],
            },
            true,
        );

        test_encoding_decoding(
            &EncoderInstruction::InsertWithNameRefDynamic {
                index: 1,
                value: &[0x62, 0x64, 0x65],
            },
            false,
        );
        test_encoding_decoding(
            &EncoderInstruction::InsertWithNameRefDynamic {
                index: 1,
                value: &[0x62, 0x64, 0x65],
            },
            true,
        );
        test_encoding_decoding(
            &EncoderInstruction::InsertWithNameRefDynamic {
                index: 10_000,
                value: &[0x62, 0x64, 0x65],
            },
            false,
        );
        test_encoding_decoding(
            &EncoderInstruction::InsertWithNameRefDynamic {
                index: 10_000,
                value: &[0x62, 0x64, 0x65],
            },
            true,
        );

        test_encoding_decoding(
            &EncoderInstruction::InsertWithNameLiteral {
                name: &[0x62, 0x64, 0x65],
                value: &[0x62, 0x64, 0x65],
            },
            false,
        );
        test_encoding_decoding(
            &EncoderInstruction::InsertWithNameLiteral {
                name: &[0x62, 0x64, 0x65],
                value: &[0x62, 0x64, 0x65],
            },
            true,
        );

        test_encoding_decoding(&EncoderInstruction::Duplicate { index: 1 }, false);
        test_encoding_decoding(&EncoderInstruction::Duplicate { index: 10_000 }, false);
    }

    fn test_encoding_decoding_slow_reader(instruction: &EncoderInstruction, use_huffman: bool) {
        let mut buf = QpackData::default();
        instruction.marshal(&mut buf, use_huffman);
        let mut test_receiver: TestReceiver = TestReceiver::default();
        let mut decoder = EncoderInstructionReader::new();
        for i in 0..buf.len() - 1 {
            test_receiver.write(&buf[i..=i]);
            assert_eq!(
                decoder.read_instructions(&mut test_receiver),
                Err(Error::NeedMoreData)
            );
        }
        test_receiver.write(&buf[buf.len() - 1..buf.len()]);
        assert_eq!(
            decoder.read_instructions(&mut test_receiver).unwrap(),
            instruction.into()
        );
    }

    #[test]
    fn test_encoding_decoding_instructions_slow_reader() {
        test_encoding_decoding_slow_reader(&EncoderInstruction::Capacity { value: 1 }, false);
        test_encoding_decoding_slow_reader(&EncoderInstruction::Capacity { value: 10_000 }, false);

        test_encoding_decoding_slow_reader(
            &EncoderInstruction::InsertWithNameRefStatic {
                index: 1,
                value: &[0x62, 0x64, 0x65],
            },
            false,
        );
        test_encoding_decoding_slow_reader(
            &EncoderInstruction::InsertWithNameRefStatic {
                index: 1,
                value: &[0x62, 0x64, 0x65],
            },
            true,
        );
        test_encoding_decoding_slow_reader(
            &EncoderInstruction::InsertWithNameRefStatic {
                index: 10_000,
                value: &[0x62, 0x64, 0x65],
            },
            false,
        );
        test_encoding_decoding_slow_reader(
            &EncoderInstruction::InsertWithNameRefStatic {
                index: 10_000,
                value: &[0x62, 0x64, 0x65],
            },
            true,
        );

        test_encoding_decoding_slow_reader(
            &EncoderInstruction::InsertWithNameRefDynamic {
                index: 1,
                value: &[0x62, 0x64, 0x65],
            },
            false,
        );
        test_encoding_decoding_slow_reader(
            &EncoderInstruction::InsertWithNameRefDynamic {
                index: 1,
                value: &[0x62, 0x64, 0x65],
            },
            true,
        );
        test_encoding_decoding_slow_reader(
            &EncoderInstruction::InsertWithNameRefDynamic {
                index: 10_000,
                value: &[0x62, 0x64, 0x65],
            },
            false,
        );
        test_encoding_decoding_slow_reader(
            &EncoderInstruction::InsertWithNameRefDynamic {
                index: 10_000,
                value: &[0x62, 0x64, 0x65],
            },
            true,
        );

        test_encoding_decoding_slow_reader(
            &EncoderInstruction::InsertWithNameLiteral {
                name: &[0x62, 0x64, 0x65],
                value: &[0x62, 0x64, 0x65],
            },
            false,
        );
        test_encoding_decoding_slow_reader(
            &EncoderInstruction::InsertWithNameLiteral {
                name: &[0x62, 0x64, 0x65],
                value: &[0x62, 0x64, 0x65],
            },
            true,
        );

        test_encoding_decoding_slow_reader(&EncoderInstruction::Duplicate { index: 1 }, false);
        test_encoding_decoding_slow_reader(&EncoderInstruction::Duplicate { index: 10_000 }, false);
    }

    #[test]
    fn test_decoding_error() {
        let mut test_receiver: TestReceiver = TestReceiver::default();
        // EncoderInstruction::Capacity with overflow
        test_receiver.write(&[
            0x3f, 0xc1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xff, 0x02,
        ]);
        let mut decoder = EncoderInstructionReader::new();
        assert_eq!(
            decoder.read_instructions(&mut test_receiver),
            Err(Error::IntegerOverflow)
        );

        let mut test_receiver: TestReceiver = TestReceiver::default();
        // EncoderInstruction::InsertWithNameRefStatic with overflow of index value.
        test_receiver.write(&[
            0xff, 0xc1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xff, 0x02, 0x00, 0x00,
        ]);
        let mut decoder = EncoderInstructionReader::new();
        assert_eq!(
            decoder.read_instructions(&mut test_receiver),
            Err(Error::IntegerOverflow)
        );

        let mut test_receiver: TestReceiver = TestReceiver::default();
        // EncoderInstruction::InsertWithNameRefStatic with a garbage value.
        test_receiver.write(&[0xc1, 0x81, 0x00]);
        let mut decoder = EncoderInstructionReader::new();
        assert_eq!(
            decoder.read_instructions(&mut test_receiver),
            Err(Error::HuffmanDecompressionFailed)
        );
    }
}


text:
/*
    Copyright 2019 Supercomputing Systems AG

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

*/

use std::sgxfs::SgxFile;
use std::vec::Vec;

use sgx_crypto_helper::rsa3072::{Rsa3072KeyPair, Rsa3072PubKey};
use sgx_crypto_helper::RsaKeyPair;
use sgx_types::*;

use log::*;

use crate::constants::RSA3072_SEALED_KEY_FILE;
use crate::io;

pub fn unseal_pair() -> SgxResult<Rsa3072KeyPair> {
    let keyvec = io::unseal(RSA3072_SEALED_KEY_FILE)?;
    let key_json_str = std::str::from_utf8(&keyvec).unwrap();
    let pair: Rsa3072KeyPair = serde_json::from_str(&key_json_str).unwrap();
    Ok(pair)
}

pub fn unseal_pubkey() -> SgxResult<Rsa3072PubKey> {
    let pair = (unseal_pair())?;
    let pubkey = pair.export_pubkey().unwrap();

    Ok(pubkey)
}

pub fn create_sealed_if_absent() -> SgxResult<sgx_status_t> {
    if SgxFile::open(RSA3072_SEALED_KEY_FILE).is_err() {
        info!(
            "[Enclave] Keyfile not found, creating new! {}",
            RSA3072_SEALED_KEY_FILE
        );
        return create_sealed();
    }
    Ok(sgx_status_t::SGX_SUCCESS)
}

pub fn create_sealed() -> Result<sgx_status_t, sgx_status_t> {
    let rsa_keypair = Rsa3072KeyPair::new().unwrap();
    let rsa_key_json = serde_json::to_string(&rsa_keypair).unwrap();
    // println!("[Enclave] generated RSA3072 key pair. Cleartext: {}", rsa_key_json);
    seal(rsa_key_json.as_bytes())
}

pub fn seal(pair: &[u8]) -> SgxResult<sgx_status_t> {
    io::seal(pair, RSA3072_SEALED_KEY_FILE)
}

pub fn decrypt(ciphertext_slice: &[u8], rsa_pair: &Rsa3072KeyPair) -> SgxResult<Vec<u8>> {
    let mut decrypted_buffer = Vec::new();

    rsa_pair.decrypt_buffer(ciphertext_slice, &mut decrypted_buffer)?;
    Ok(decrypted_buffer)
}


text:
//! Traits that indicate the allowed arguments in a ChunkedArray::take operation.
use crate::frame::groupby::GroupsProxyIter;
use crate::prelude::*;
use polars_arrow::array::PolarsArray;

// Utility traits
pub trait TakeIterator: Iterator<Item = usize> + TrustedLen {
    fn check_bounds(&self, bound: usize) -> Result<()>;
    // a sort of clone
    fn boxed_clone(&self) -> Box<dyn TakeIterator + '_>;
}
pub trait TakeIteratorNulls: Iterator<Item = Option<usize>> + TrustedLen {
    fn check_bounds(&self, bound: usize) -> Result<()>;

    fn boxed_clone(&self) -> Box<dyn TakeIteratorNulls + '_>;
}

unsafe impl TrustedLen for &mut dyn TakeIterator {}
unsafe impl TrustedLen for &mut dyn TakeIteratorNulls {}
unsafe impl TrustedLen for GroupsProxyIter<'_> {}

// Implement for the ref as well
impl TakeIterator for &mut dyn TakeIterator {
    fn check_bounds(&self, bound: usize) -> Result<()> {
        (**self).check_bounds(bound)
    }

    fn boxed_clone(&self) -> Box<dyn TakeIterator + '_> {
        (**self).boxed_clone()
    }
}
impl TakeIteratorNulls for &mut dyn TakeIteratorNulls {
    fn check_bounds(&self, bound: usize) -> Result<()> {
        (**self).check_bounds(bound)
    }

    fn boxed_clone(&self) -> Box<dyn TakeIteratorNulls + '_> {
        (**self).boxed_clone()
    }
}

// Clonable iterators may implement the traits above
impl<I> TakeIterator for I
where
    I: Iterator<Item = usize> + Clone + Sized + TrustedLen,
{
    fn check_bounds(&self, bound: usize) -> Result<()> {
        // clone so that the iterator can be used again.
        let iter = self.clone();
        let mut inbounds = true;

        for i in iter {
            if i >= bound {
                inbounds = false;
                break;
            }
        }
        if inbounds {
            Ok(())
        } else {
            Err(PolarsError::ComputeError(
                "take indices are out of bounds".into(),
            ))
        }
    }

    fn boxed_clone(&self) -> Box<dyn TakeIterator + '_> {
        Box::new(self.clone())
    }
}
impl<I> TakeIteratorNulls for I
where
    I: Iterator<Item = Option<usize>> + Clone + Sized + TrustedLen,
{
    fn check_bounds(&self, bound: usize) -> Result<()> {
        // clone so that the iterator can be used again.
        let iter = self.clone();
        let mut inbounds = true;

        for i in iter.flatten() {
            if i >= bound {
                inbounds = false;
                break;
            }
        }
        if inbounds {
            Ok(())
        } else {
            Err(PolarsError::ComputeError(
                "take indices are out of bounds".into(),
            ))
        }
    }

    fn boxed_clone(&self) -> Box<dyn TakeIteratorNulls + '_> {
        Box::new(self.clone())
    }
}

/// One of the three arguments allowed in unchecked_take
pub enum TakeIdx<'a, I, INulls>
where
    I: TakeIterator,
    INulls: TakeIteratorNulls,
{
    Array(&'a IdxArr),
    Iter(I),
    // will return a null where None
    IterNulls(INulls),
}

impl<'a, I, INulls> TakeIdx<'a, I, INulls>
where
    I: TakeIterator,
    INulls: TakeIteratorNulls,
{
    pub(crate) fn check_bounds(&self, bound: usize) -> Result<()> {
        match self {
            TakeIdx::Iter(i) => i.check_bounds(bound),
            TakeIdx::IterNulls(i) => i.check_bounds(bound),
            TakeIdx::Array(arr) => {
                let mut inbounds = true;
                let len = bound as IdxSize;
                if !arr.has_validity() {
                    for &i in arr.values().as_slice() {
                        if i >= len {
                            inbounds = false;
                            break;
                        }
                    }
                } else {
                    for opt_v in *arr {
                        match opt_v {
                            Some(&v) if v >= len => {
                                inbounds = false;
                                break;
                            }
                            _ => {}
                        }
                    }
                }
                if inbounds {
                    Ok(())
                } else {
                    Err(PolarsError::ComputeError(
                        "take indices are out of bounds".into(),
                    ))
                }
            }
        }
    }
}

/// Dummy type, we need to instantiate all generic types, so we fill one with a dummy.
pub type Dummy<T> = std::iter::Once<T>;

// Below the conversions from
// * UInt32Chunked
// * Iterator<Item=usize>
// * Iterator<Item=Option<usize>>
//
// To the checked and unchecked TakeIdx enums

// Unchecked conversions

/// Conversion from UInt32Chunked to Unchecked TakeIdx
impl<'a> From<&'a IdxCa> for TakeIdx<'a, Dummy<usize>, Dummy<Option<usize>>> {
    fn from(ca: &'a IdxCa) -> Self {
        if ca.chunks.len() == 1 {
            TakeIdx::Array(ca.downcast_iter().next().unwrap())
        } else {
            panic!("implementation error, should be transformed to an iterator by the caller")
        }
    }
}

/// Conversion from Iterator<Item=usize> to Unchecked TakeIdx
impl<'a, I> From<I> for TakeIdx<'a, I, Dummy<Option<usize>>>
where
    I: TakeIterator,
{
    fn from(iter: I) -> Self {
        TakeIdx::Iter(iter)
    }
}

/// Conversion from Iterator<Item=Option<usize>> to Unchecked TakeIdx
impl<'a, I> From<I> for TakeIdx<'a, Dummy<usize>, I>
where
    I: TakeIteratorNulls,
{
    fn from(iter: I) -> Self {
        TakeIdx::IterNulls(iter)
    }
}

#[inline]
fn to_usize(idx: &IdxSize) -> usize {
    *idx as usize
}

/// Conversion from `&[IdxSize]` to Unchecked TakeIdx
impl<'a> From<&'a [IdxSize]>
    for TakeIdx<
        'a,
        std::iter::Map<std::slice::Iter<'a, IdxSize>, fn(&IdxSize) -> usize>,
        Dummy<Option<usize>>,
    >
{
    fn from(slice: &'a [IdxSize]) -> Self {
        TakeIdx::Iter(slice.iter().map(to_usize))
    }
}

/// Conversion from `&[IdxSize]` to Unchecked TakeIdx
impl<'a> From<&'a Vec<IdxSize>>
    for TakeIdx<
        'a,
        std::iter::Map<std::slice::Iter<'a, IdxSize>, fn(&IdxSize) -> usize>,
        Dummy<Option<usize>>,
    >
{
    fn from(slice: &'a Vec<IdxSize>) -> Self {
        (&**slice).into()
    }
}


text:
use super::Window;
use super::WindowHandle;
use super::WindowState;
use super::WindowType;
use crate::models::XYHWChange;

type MaybeWindowHandle = Option<WindowHandle>;
type MaybeName = Option<String>;

#[derive(Debug, Clone)]
pub struct WindowChange {
    pub handle: WindowHandle,
    pub transient: Option<MaybeWindowHandle>,
    pub never_focus: Option<bool>,
    pub name: Option<MaybeName>,
    pub type_: Option<WindowType>,
    pub floating: Option<XYHWChange>,
    pub strut: Option<XYHWChange>,
    pub states: Option<Vec<WindowState>>,
}

impl WindowChange {
    pub fn new(h: WindowHandle) -> WindowChange {
        WindowChange {
            handle: h,
            transient: None,
            never_focus: None,
            name: None,
            type_: None,
            floating: None,
            strut: None,
            states: None,
        }
    }

    pub fn update(self, window: &mut Window) -> bool {
        let mut changed = false;
        if let Some(trans) = &self.transient {
            let changed_trans = window.transient.is_none() || &window.transient != trans;
            //if changed_trans {
            //    warn!("CHANGED: trans");
            //}
            changed = changed || changed_trans;
            window.transient = trans.clone();
        }
        if let Some(name) = &self.name {
            let changed_name = window.name.is_none() || &window.name != name;
            //if changed_name {
            //    warn!("CHANGED: name");
            //}
            changed = changed || changed_name;
            window.name = name.clone();
        }
        if let Some(nf) = self.never_focus {
            let changed_nf = window.never_focus != nf;
            //if changed_nf {
            //    warn!("CHANGED: nf");
            //}
            changed = changed || changed_nf;
            window.never_focus = nf;
        }
        if let Some(floating_change) = self.floating {
            let changed_floating = floating_change.update_window_floating(window);
            //if changed_floating {
            //    warn!("CHANGED: floating");
            //}
            changed = changed || changed_floating;
        }
        if let Some(strut) = self.strut {
            let changed_strut = strut.update_window_strut(window);
            //////if changed_strut {
            //////    warn!("CHANGED: strut");
            //////}
            changed = changed || changed_strut;
        }
        if let Some(type_) = &self.type_ {
            let changed_type = &window.type_ != type_;
            //if changed_type {
            //    warn!("CHANGED: type");
            //}
            changed = changed || changed_type;
            window.type_ = type_.clone();
            if window.type_ == WindowType::Dock {
                window.border = 0;
                window.margin = 0;
            }
        }
        if let Some(states) = self.states {
            //warn!("CHANGED: state");
            changed = true;
            window.set_states(states);
        }
        changed
    }
}


text:
use skulpin_renderer::ash;
pub use sdl2;

pub use ash::version::{DeviceV1_0, EntryV1_0, InstanceV1_0};
use ash::vk;

use skulpin_renderer::PhysicalSize;
use skulpin_renderer::LogicalSize;
use skulpin_renderer::Window;
use std::ffi::CStr;
use ash::prelude::VkResult;

#[cfg(target_os = "windows")]
const DEFAULT_DPI: f32 = 96.0;

pub struct Sdl2Window<'a> {
    window: &'a sdl2::video::Window,
}

impl<'a> Sdl2Window<'a> {
    pub fn new(window: &'a sdl2::video::Window) -> Self {
        Sdl2Window { window }
    }

    #[cfg(target_os = "windows")]
    fn compute_scale_factor(&self) -> Option<f64> {
        let display_index = self.window.display_index().ok()?;
        let system = self.window.subsystem();
        let (_, dpi, _) = system.display_dpi(display_index).ok()?;
        Some((DEFAULT_DPI / dpi).into())
    }
}

impl<'a> Window for Sdl2Window<'a> {
    fn physical_size(&self) -> PhysicalSize {
        let physical_size = self.window.vulkan_drawable_size();
        PhysicalSize::new(physical_size.0, physical_size.1)
    }

    #[cfg(target_os = "windows")]
    fn logical_size(&self) -> LogicalSize {
        let physical_size = self.physical_size();
        physical_size.to_logical(self.scale_factor())
    }

    #[cfg(not(target_os = "windows"))]
    fn logical_size(&self) -> LogicalSize {
        let logical_size = self.window.size();
        LogicalSize::new(logical_size.0, logical_size.1)
    }

    #[cfg(target_os = "windows")]
    fn scale_factor(&self) -> f64 {
        self.compute_scale_factor().unwrap_or(1.0)
    }

    #[cfg(not(target_os = "windows"))]
    fn scale_factor(&self) -> f64 {
        let logical_size = self.window.size();
        let drawable_size = self.window.drawable_size();

        logical_size.0 as f64 / drawable_size.0 as f64
    }

    unsafe fn create_vulkan_surface(
        &self,
        entry: &ash::Entry,
        instance: &ash::Instance,
    ) -> VkResult<vk::SurfaceKHR> {
        ash_window::create_surface(entry, instance, self.window, None)
    }

    fn extension_names(&self) -> VkResult<Vec<&'static CStr>> {
        ash_window::enumerate_required_extensions(self.window)
    }
}


text:
use {
    // stry_common::{
    //     backend::{
    //         BackendAuthor, BackendCharacter, BackendOrigin, BackendPairing, BackendStory,
    //         BackendTag, BackendWarning,
    //     },
    //     models::{
    //         author::AuthorList, character::CharacterList, origin::OriginList, pairing::PairingList,
    //         story::StoryList, tag::TagList, warning::WarningList, Author, Character, Origin,
    //         Pairing, Story, Tag, Warning,
    //     },
    // },
    juniper::FieldResult,
    stry_backend::DataBackend,
};

pub struct Query;

#[juniper::graphql_object(Context = DataBackend)]
impl Query {
    fn hello(&self, ctx: &DataBackend) -> FieldResult<&str> {
        Ok("hello world")
    }

    // pub async fn all_authors(
    //     ctx: &DataBackend,
    //     offset: i32,
    //     limit: i32,
    // ) -> FieldResult<Option<AuthorList>> {
    //     let authors = ctx.all_authors(offset, limit).await?;

    //     Ok(authors.map(Into::into))
    // }

    // pub async fn get_author(ctx: &DataBackend, id: String) -> FieldResult<Option<Author>> {
    //     let author = ctx.get_author(id.into()).await?;

    //     Ok(author)
    // }

    // pub async fn all_characters(
    //     ctx: &DataBackend,
    //     offset: i32,
    //     limit: i32,
    // ) -> FieldResult<Option<CharacterList>> {
    //     let characters = ctx.all_characters(offset, limit).await?;

    //     Ok(characters.map(Into::into))
    // }

    // pub async fn get_character(ctx: &DataBackend, id: String) -> FieldResult<Option<Character>> {
    //     let character = ctx.get_character(id.into()).await?;

    //     Ok(character)
    // }

    // pub async fn all_origins(
    //     ctx: &DataBackend,
    //     offset: i32,
    //     limit: i32,
    // ) -> FieldResult<Option<OriginList>> {
    //     let origins = ctx.all_origins(offset, limit).await?;

    //     Ok(origins.map(Into::into))
    // }

    // pub async fn get_origin(ctx: &DataBackend, id: String) -> FieldResult<Option<Origin>> {
    //     let origin = ctx.get_origin(id.into()).await?;

    //     Ok(origin)
    // }

    // pub async fn all_pairings(
    //     ctx: &DataBackend,
    //     offset: i32,
    //     limit: i32,
    // ) -> FieldResult<Option<PairingList>> {
    //     let pairings = ctx.all_pairings(offset, limit).await?;

    //     Ok(pairings.map(Into::into))
    // }

    // pub async fn get_pairing(ctx: &DataBackend, id: String) -> FieldResult<Option<Pairing>> {
    //     let pairing = ctx.get_pairing(id.into()).await?;

    //     Ok(pairing)
    // }

    // pub async fn all_stories(
    //     ctx: &DataBackend,
    //     offset: i32,
    //     limit: i32,
    // ) -> FieldResult<Option<StoryList>> {
    //     let stories = ctx.all_stories(offset, limit).await?;

    //     Ok(stories.map(Into::into))
    // }

    // pub async fn get_story(ctx: &DataBackend, id: String) -> FieldResult<Option<Story>> {
    //     let story = ctx.get_story(id.into()).await?;

    //     Ok(story)
    // }

    // pub async fn all_tags(
    //     ctx: &DataBackend,
    //     offset: i32,
    //     limit: i32,
    // ) -> FieldResult<Option<TagList>> {
    //     let tags = ctx.all_tags(offset, limit).await?;

    //     Ok(tags.map(Into::into))
    // }

    // pub async fn get_tag(ctx: &DataBackend, id: String) -> FieldResult<Option<Tag>> {
    //     let tag = ctx.get_tag(id.into()).await?;

    //     Ok(tag)
    // }

    // pub async fn all_warnings(
    //     ctx: &DataBackend,
    //     offset: i32,
    //     limit: i32,
    // ) -> FieldResult<Option<WarningList>> {
    //     let warnings = ctx.all_warnings(offset, limit).await?;

    //     Ok(warnings.map(Into::into))
    // }

    // pub async fn get_warning(ctx: &DataBackend, id: String) -> FieldResult<Option<Warning>> {
    //     let warning = ctx.get_warning(id.into()).await?;

    //     Ok(warning)
    // }
}

// #[juniper::graphql_object(Context = DataBackend)]
// impl Author {
//     pub async fn stories(
//         ctx: &DataBackend,
//         offset: i32,
//         limit: i32,
//     ) -> FieldResult<Option<StoryList>> {
//         let stories = ctx.author_stories(id, offset, limit)
//     }
// }


text:
use crate::{
    codecs::{
        self,
        decoding::{DecodingConfig, DeserializerConfig, FramingConfig},
        BytesDecoderConfig, BytesDeserializerConfig, JsonDeserializerConfig,
        NewlineDelimitedDecoderConfig,
    },
    config::{
        log_schema, AcknowledgementsConfig, DataType, GenerateConfig, Resource, SourceConfig,
        SourceContext, SourceDescription,
    },
    event::{Event, Value},
    serde::{bool_or_struct, default_decoding, default_framing_stream_based},
    sources::util::{
        add_query_parameters, Encoding, ErrorMessage, HttpSource, HttpSourceAuthConfig,
    },
    tls::TlsConfig,
};
use bytes::{Bytes, BytesMut};
use chrono::Utc;
use http::StatusCode;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, net::SocketAddr};
use tokio_util::codec::Decoder;

use warp::http::{HeaderMap, HeaderValue};

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct SimpleHttpConfig {
    address: SocketAddr,
    #[serde(default)]
    encoding: Option<Encoding>,
    #[serde(default)]
    headers: Vec<String>,
    #[serde(default)]
    query_parameters: Vec<String>,
    tls: Option<TlsConfig>,
    auth: Option<HttpSourceAuthConfig>,
    #[serde(default = "crate::serde::default_true")]
    strict_path: bool,
    #[serde(default = "default_path")]
    path: String,
    #[serde(default = "default_path_key")]
    path_key: String,
    framing: Option<Box<dyn FramingConfig>>,
    decoding: Option<Box<dyn DeserializerConfig>>,
    #[serde(default, deserialize_with = "bool_or_struct")]
    acknowledgements: AcknowledgementsConfig,
}

inventory::submit! {
    SourceDescription::new::<SimpleHttpConfig>("http")
}

impl GenerateConfig for SimpleHttpConfig {
    fn generate_config() -> toml::Value {
        toml::Value::try_from(Self {
            address: "0.0.0.0:8080".parse().unwrap(),
            encoding: None,
            headers: Vec::new(),
            query_parameters: Vec::new(),
            tls: None,
            auth: None,
            path_key: "path".to_string(),
            path: "/".to_string(),
            strict_path: true,
            framing: Some(default_framing_stream_based()),
            decoding: Some(default_decoding()),
            acknowledgements: AcknowledgementsConfig::default(),
        })
        .unwrap()
    }
}

fn default_path() -> String {
    "/".to_string()
}

fn default_path_key() -> String {
    "path".to_string()
}

#[derive(Clone)]
struct SimpleHttpSource {
    headers: Vec<String>,
    query_parameters: Vec<String>,
    path_key: String,
    decoder: codecs::Decoder,
}

impl HttpSource for SimpleHttpSource {
    fn build_events(
        &self,
        body: Bytes,
        header_map: HeaderMap,
        query_parameters: HashMap<String, String>,
        request_path: &str,
    ) -> Result<Vec<Event>, ErrorMessage> {
        let mut decoder = self.decoder.clone();
        let mut events = Vec::new();
        let mut bytes = BytesMut::new();
        bytes.extend_from_slice(&body);

        loop {
            match decoder.decode_eof(&mut bytes) {
                Ok(Some((next, _))) => {
                    events.extend(next.into_iter());
                }
                Ok(None) => break,
                Err(error) => {
                    return Err(ErrorMessage::new(
                        StatusCode::BAD_REQUEST,
                        format!("Failed decoding body: {}", error),
                    ))
                }
            }
        }

        add_headers(&mut events, &self.headers, header_map);
        add_query_parameters(&mut events, &self.query_parameters, query_parameters);
        add_path(&mut events, self.path_key.as_str(), request_path);

        let now = Utc::now();
        for event in &mut events {
            let log = event.as_mut_log();

            log.try_insert(log_schema().source_type_key(), Bytes::from("http"));
            log.try_insert(log_schema().timestamp_key(), now);
        }

        Ok(events)
    }
}

#[async_trait::async_trait]
#[typetag::serde(name = "http")]
impl SourceConfig for SimpleHttpConfig {
    async fn build(&self, cx: SourceContext) -> crate::Result<super::Source> {
        if self.encoding.is_some() && (self.framing.is_some() || self.decoding.is_some()) {
            return Err("Using `encoding` is deprecated and does not have any effect when `decoding` or `framing` is provided. Configure `framing` and `decoding` instead.".into());
        }

        let (framing, decoding) = if let Some(encoding) = self.encoding {
            match encoding {
                Encoding::Text => (
                    Box::new(NewlineDelimitedDecoderConfig::new()) as Box<dyn FramingConfig>,
                    Box::new(BytesDeserializerConfig::new()) as Box<dyn DeserializerConfig>,
                ),
                Encoding::Json => (
                    Box::new(BytesDecoderConfig::new()) as Box<dyn FramingConfig>,
                    Box::new(JsonDeserializerConfig::new()) as Box<dyn DeserializerConfig>,
                ),
                Encoding::Ndjson => (
                    Box::new(NewlineDelimitedDecoderConfig::new()) as Box<dyn FramingConfig>,
                    Box::new(JsonDeserializerConfig::new()) as Box<dyn DeserializerConfig>,
                ),
                Encoding::Binary => (
                    Box::new(BytesDecoderConfig::new()) as Box<dyn FramingConfig>,
                    Box::new(BytesDeserializerConfig::new()) as Box<dyn DeserializerConfig>,
                ),
            }
        } else {
            (
                match self.framing.as_ref() {
                    Some(framing) => framing.clone(),
                    None => default_framing_stream_based(),
                } as Box<dyn FramingConfig>,
                match self.decoding.as_ref() {
                    Some(decoding) => decoding.clone(),
                    None => default_decoding(),
                } as Box<dyn DeserializerConfig>,
            )
        };

        let decoder = DecodingConfig::new(framing, decoding).build()?;
        let source = SimpleHttpSource {
            headers: self.headers.clone(),
            query_parameters: self.query_parameters.clone(),
            path_key: self.path_key.clone(),
            decoder,
        };
        source.run(
            self.address,
            self.path.as_str(),
            self.strict_path,
            &self.tls,
            &self.auth,
            cx,
            self.acknowledgements,
        )
    }

    fn output_type(&self) -> DataType {
        DataType::Log
    }

    fn source_type(&self) -> &'static str {
        "http"
    }

    fn resources(&self) -> Vec<Resource> {
        vec![Resource::tcp(self.address)]
    }
}

fn add_path(events: &mut [Event], key: &str, path: &str) {
    for event in events.iter_mut() {
        event
            .as_mut_log()
            .try_insert(key, Value::from(path.to_string()));
    }
}

fn add_headers(events: &mut [Event], headers_config: &[String], headers: HeaderMap) {
    for header_name in headers_config {
        let value = headers.get(header_name).map(HeaderValue::as_bytes);

        for event in events.iter_mut() {
            event.as_mut_log().try_insert_flat(
                header_name as &str,
                Value::from(value.map(Bytes::copy_from_slice)),
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::SimpleHttpConfig;
    use crate::{
        codecs::{
            decoding::{DeserializerConfig, FramingConfig},
            BytesDecoderConfig, JsonDeserializerConfig,
        },
        config::{log_schema, SourceConfig, SourceContext},
        event::{Event, EventStatus, Value},
        test_util::{components, next_addr, spawn_collect_n, trace_init, wait_for_tcp},
        Pipeline,
    };
    use flate2::{
        write::{GzEncoder, ZlibEncoder},
        Compression,
    };
    use futures::Stream;
    use http::HeaderMap;
    use pretty_assertions::assert_eq;
    use std::collections::BTreeMap;
    use std::io::Write;
    use std::net::SocketAddr;

    #[test]
    fn generate_config() {
        crate::test_util::test_generate_config::<SimpleHttpConfig>();
    }

    async fn source<'a>(
        headers: Vec<String>,
        query_parameters: Vec<String>,
        path_key: &'a str,
        path: &'a str,
        strict_path: bool,
        status: EventStatus,
        acknowledgements: bool,
        framing: Option<Box<dyn FramingConfig>>,
        decoding: Option<Box<dyn DeserializerConfig>>,
    ) -> (impl Stream<Item = Event> + 'a, SocketAddr) {
        components::init_test();
        let (sender, recv) = Pipeline::new_test_finalize(status);
        let address = next_addr();
        let path = path.to_owned();
        let path_key = path_key.to_owned();
        let context = SourceContext::new_test(sender);
        tokio::spawn(async move {
            SimpleHttpConfig {
                address,
                headers,
                encoding: None,
                query_parameters,
                tls: None,
                auth: None,
                strict_path,
                path_key,
                path,
                framing,
                decoding,
                acknowledgements: acknowledgements.into(),
            }
            .build(context)
            .await
            .unwrap()
            .await
            .unwrap();
        });
        wait_for_tcp(address).await;
        (recv, address)
    }

    async fn send(address: SocketAddr, body: &str) -> u16 {
        reqwest::Client::new()
            .post(&format!("http://{}/", address))
            .body(body.to_owned())
            .send()
            .await
            .unwrap()
            .status()
            .as_u16()
    }

    async fn send_with_headers(address: SocketAddr, body: &str, headers: HeaderMap) -> u16 {
        reqwest::Client::new()
            .post(&format!("http://{}/", address))
            .headers(headers)
            .body(body.to_owned())
            .send()
            .await
            .unwrap()
            .status()
            .as_u16()
    }

    async fn send_with_query(address: SocketAddr, body: &str, query: &str) -> u16 {
        reqwest::Client::new()
            .post(&format!("http://{}?{}", address, query))
            .body(body.to_owned())
            .send()
            .await
            .unwrap()
            .status()
            .as_u16()
    }

    async fn send_with_path(address: SocketAddr, body: &str, path: &str) -> u16 {
        reqwest::Client::new()
            .post(&format!("http://{}{}", address, path))
            .body(body.to_owned())
            .send()
            .await
            .unwrap()
            .status()
            .as_u16()
    }

    async fn send_bytes(address: SocketAddr, body: Vec<u8>, headers: HeaderMap) -> u16 {
        reqwest::Client::new()
            .post(&format!("http://{}/", address))
            .headers(headers)
            .body(body)
            .send()
            .await
            .unwrap()
            .status()
            .as_u16()
    }

    async fn spawn_ok_collect_n(
        send: impl std::future::Future<Output = u16> + Send + 'static,
        rx: impl Stream<Item = Event> + Unpin,
        n: usize,
    ) -> Vec<Event> {
        let events = spawn_collect_n(async move { assert_eq!(200, send.await) }, rx, n).await;
        components::SOURCE_TESTS.assert(&["http_path"]);
        events
    }

    #[tokio::test]
    async fn http_multiline_text() {
        let body = "test body\ntest body 2";

        let (rx, addr) = source(
            vec![],
            vec![],
            "http_path",
            "/",
            true,
            EventStatus::Delivered,
            true,
            None,
            None,
        )
        .await;

        let mut events = spawn_ok_collect_n(send(addr, body), rx, 2).await;

        {
            let event = events.remove(0);
            let log = event.as_log();
            assert_eq!(log[log_schema().message_key()], "test body".into());
            assert!(log.get(log_schema().timestamp_key()).is_some());
            assert_eq!(log[log_schema().source_type_key()], "http".into());
            assert_eq!(log["http_path"], "/".into());
        }
        {
            let event = events.remove(0);
            let log = event.as_log();
            assert_eq!(log[log_schema().message_key()], "test body 2".into());
            assert!(log.get(log_schema().timestamp_key()).is_some());
            assert_eq!(log[log_schema().source_type_key()], "http".into());
            assert_eq!(log["http_path"], "/".into());
        }
    }

    #[tokio::test]
    async fn http_multiline_text2() {
        //same as above test but with a newline at the end
        let body = "test body\ntest body 2\n";

        let (rx, addr) = source(
            vec![],
            vec![],
            "http_path",
            "/",
            true,
            EventStatus::Delivered,
            true,
            None,
            None,
        )
        .await;

        let mut events = spawn_ok_collect_n(send(addr, body), rx, 2).await;

        {
            let event = events.remove(0);
            let log = event.as_log();
            assert_eq!(log[log_schema().message_key()], "test body".into());
            assert!(log.get(log_schema().timestamp_key()).is_some());
            assert_eq!(log[log_schema().source_type_key()], "http".into());
            assert_eq!(log["http_path"], "/".into());
        }
        {
            let event = events.remove(0);
            let log = event.as_log();
            assert_eq!(log[log_schema().message_key()], "test body 2".into());
            assert!(log.get(log_schema().timestamp_key()).is_some());
            assert_eq!(log[log_schema().source_type_key()], "http".into());
            assert_eq!(log["http_path"], "/".into());
        }
    }

    #[tokio::test]
    async fn http_bytes_codec_preserves_newlines() {
        trace_init();

        let body = "foo\nbar";

        let (rx, addr) = source(
            vec![],
            vec![],
            "http_path",
            "/",
            true,
            EventStatus::Delivered,
            true,
            Some(Box::new(BytesDecoderConfig::new())),
            None,
        )
        .await;

        let mut events = spawn_ok_collect_n(send(addr, body), rx, 1).await;

        assert_eq!(events.len(), 1);

        {
            let event = events.remove(0);
            let log = event.as_log();
            assert_eq!(log[log_schema().message_key()], "foo\nbar".into());
            assert!(log.get(log_schema().timestamp_key()).is_some());
            assert_eq!(log[log_schema().source_type_key()], "http".into());
            assert_eq!(log["http_path"], "/".into());
        }
    }

    #[tokio::test]
    async fn http_json_parsing() {
        let (rx, addr) = source(
            vec![],
            vec![],
            "http_path",
            "/",
            true,
            EventStatus::Delivered,
            true,
            None,
            Some(Box::new(JsonDeserializerConfig::new())),
        )
        .await;

        let mut events = spawn_collect_n(
            async move {
                assert_eq!(400, send(addr, "{").await); //malformed
                assert_eq!(400, send(addr, r#"{"key"}"#).await); //key without value

                assert_eq!(200, send(addr, "{}").await); //can be one object or array of objects
                assert_eq!(200, send(addr, "[{},{},{}]").await);
            },
            rx,
            2,
        )
        .await;
        components::SOURCE_TESTS.assert(&["http_path"]);

        assert!(events
            .remove(1)
            .as_log()
            .get(log_schema().timestamp_key())
            .is_some());
        assert!(events
            .remove(0)
            .as_log()
            .get(log_schema().timestamp_key())
            .is_some());
    }

    #[tokio::test]
    async fn http_json_values() {
        let (rx, addr) = source(
            vec![],
            vec![],
            "http_path",
            "/",
            true,
            EventStatus::Delivered,
            true,
            None,
            Some(Box::new(JsonDeserializerConfig::new())),
        )
        .await;

        let mut events = spawn_collect_n(
            async move {
                assert_eq!(200, send(addr, r#"[{"key":"value"}]"#).await);
                assert_eq!(200, send(addr, r#"{"key2":"value2"}"#).await);
            },
            rx,
            2,
        )
        .await;
        components::SOURCE_TESTS.assert(&["http_path"]);

        {
            let event = events.remove(0);
            let log = event.as_log();
            assert_eq!(log["key"], "value".into());
            assert!(log.get(log_schema().timestamp_key()).is_some());
            assert_eq!(log[log_schema().source_type_key()], "http".into());
            assert_eq!(log["http_path"], "/".into());
        }
        {
            let event = events.remove(0);
            let log = event.as_log();
            assert_eq!(log["key2"], "value2".into());
            assert!(log.get(log_schema().timestamp_key()).is_some());
            assert_eq!(log[log_schema().source_type_key()], "http".into());
            assert_eq!(log["http_path"], "/".into());
        }
    }

    #[tokio::test]
    async fn http_json_dotted_keys() {
        let (rx, addr) = source(
            vec![],
            vec![],
            "http_path",
            "/",
            true,
            EventStatus::Delivered,
            true,
            None,
            Some(Box::new(JsonDeserializerConfig::new())),
        )
        .await;

        let mut events = spawn_collect_n(
            async move {
                assert_eq!(200, send(addr, r#"[{"dotted.key":"value"}]"#).await);
                assert_eq!(
                    200,
                    send(addr, r#"{"nested":{"dotted.key2":"value2"}}"#).await
                );
            },
            rx,
            2,
        )
        .await;
        components::SOURCE_TESTS.assert(&["http_path"]);

        {
            let event = events.remove(0);
            let log = event.as_log();
            assert_eq!(log.get_flat("dotted.key").unwrap(), &Value::from("value"));
        }
        {
            let event = events.remove(0);
            let log = event.as_log();
            let mut map = BTreeMap::new();
            map.insert("dotted.key2".to_string(), Value::from("value2"));
            assert_eq!(log["nested"], map.into());
        }
    }

    #[tokio::test]
    async fn http_ndjson() {
        let (rx, addr) = source(
            vec![],
            vec![],
            "http_path",
            "/",
            true,
            EventStatus::Delivered,
            true,
            None,
            Some(Box::new(JsonDeserializerConfig::new())),
        )
        .await;

        let mut events = spawn_collect_n(
            async move {
                assert_eq!(
                    200,
                    send(addr, r#"[{"key1":"value1"},{"key2":"value2"}]"#).await
                );

                assert_eq!(
                    200,
                    send(addr, "{\"key1\":\"value1\"}\n\n{\"key2\":\"value2\"}").await
                );
            },
            rx,
            4,
        )
        .await;
        components::SOURCE_TESTS.assert(&["http_path"]);

        {
            let event = events.remove(0);
            let log = event.as_log();
            assert_eq!(log["key1"], "value1".into());
            assert!(log.get(log_schema().timestamp_key()).is_some());
            assert_eq!(log[log_schema().source_type_key()], "http".into());
            assert_eq!(log["http_path"], "/".into());
        }
        {
            let event = events.remove(0);
            let log = event.as_log();
            assert_eq!(log["key2"], "value2".into());
            assert!(log.get(log_schema().timestamp_key()).is_some());


text:
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::process::Command;
use std::env;
use std::fs;

fn bash(file_parameter: String){
    let contents = fs::read_to_string(file_parameter.clone())
        .expect("Something went wrong reading the file");

    // println!("With text:\n{}", contents);

    let output = if cfg!(target_os = "windows") {
        Command::new("cmd")
                .args(&["/C", "echo hello-world"])
                .output()
                .expect("failed to execute process")
    } else {
        Command::new("sh")
                .arg("-c")
                .arg(contents.clone())
                .output()
                .expect("failed to execute process")
    };

    let result = String::from_utf8_lossy(&output.stdout);
    // println!("stdout: {}", result);
    assert!(output.status.success());
    send_and_write(file_parameter.to_string().clone(), result.to_string(), contents.clone());
}

fn send_and_write(file_parameter: String, resultat: String, to_execute: String){
    let mut file = OpenOptions::new()
        .write(true)
        .append(true)
        .open(file_parameter)
        .unwrap();

    if let Err(e) = writeln!(file, "\nResult of the command : {}",to_execute) {
        eprintln!("Couldn't write to file: {}", e);
    }
    if let Err(e) = writeln!(file, "\n{}",resultat) {
        eprintln!("Couldn't write to file: {}", e);
    }
}

fn main() -> std::io::Result<()> {
    let args: Vec<String> = env::args().collect();
    // Récupération du paramètre d'entrée
    let file_parameter = &args[1];

    // println!("Searching in {}", file_parameter);
    // println!("File output {}", file_parameter);

    bash(file_parameter.to_string());

    Ok(())
}