Live video on the AT Protocol
at natb/command-errors 80 lines 2.7 kB view raw
1// Copyright 2023 Adobe. All rights reserved. 2// This file is licensed to you under the Apache License, 3// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) 4// or the MIT license (http://opensource.org/licenses/MIT), 5// at your option. 6 7// Unless required by applicable law or agreed to in writing, 8// this software is distributed on an "AS IS" BASIS, WITHOUT 9// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or 10// implied. See the LICENSE-MIT and LICENSE-APACHE files for the 11// specific language governing permissions and limitations under 12// each license. 13 14use std::io::{Read, Seek, SeekFrom, Write}; 15use std::sync::RwLock; 16 17use crate::error::SPError; 18use crate::streams::Stream; 19use std::io::Cursor; 20 21pub struct TestStream { 22 stream: RwLock<Cursor<Vec<u8>>>, 23} 24 25impl TestStream { 26 pub fn new() -> Self { 27 Self { 28 stream: RwLock::new(Cursor::new(Vec::new())), 29 } 30 } 31 pub fn from_memory(data: Vec<u8>) -> Self { 32 Self { 33 stream: RwLock::new(Cursor::new(data)), 34 } 35 } 36} 37 38impl Stream for TestStream { 39 fn read_stream(&self, length: u64) -> Result<Vec<u8>, SPError> { 40 if let Ok(mut stream) = RwLock::write(&self.stream) { 41 let mut data = vec![0u8; length as usize]; 42 let bytes_read = stream 43 .read(&mut data) 44 .map_err(|e| SPError::IOError(e.to_string()))?; 45 data.truncate(bytes_read); 46 //println!("read_stream: {:?}, pos {:?}", data.len(), (*stream).position()); 47 Ok(data) 48 } else { 49 Err(SPError::IOError("RwLock".to_string()))? 50 } 51 } 52 53 fn seek_stream(&self, pos: i64, mode: u64) -> Result<u64, SPError> { 54 if let Ok(mut stream) = RwLock::write(&self.stream) { 55 //stream.seek(SeekFrom::Start(pos as u64)).map_err(|e| StreamError::Io{ reason: e.to_string()})?; 56 let whence = match mode { 57 0 => SeekFrom::Start(pos as u64), 58 1 => SeekFrom::End(pos as i64), 59 2 => SeekFrom::Current(pos as i64), 60 3_u64..=u64::MAX => unimplemented!(), 61 }; 62 Ok(stream 63 .seek(whence) 64 .map_err(|e| SPError::IOError(e.to_string()))?) 65 } else { 66 Err(SPError::IOError("RwLock".to_string())) 67 } 68 } 69 70 fn write_stream(&self, data: Vec<u8>) -> Result<u64, SPError> { 71 if let Ok(mut stream) = RwLock::write(&self.stream) { 72 let len = stream 73 .write(&data) 74 .map_err(|e| SPError::IOError(e.to_string()))?; 75 Ok(len as u64) 76 } else { 77 Err(SPError::IOError("RwLock".to_string()))? 78 } 79 } 80}