···11uniffi::setup_scaffolding!();
2233pub mod c2pa;
44+pub mod error;
45pub mod node_addr;
56pub mod public_key;
77+pub mod streams;
6879use std::sync::{LazyLock, Once};
810···1012pub use db::*;
1113#[cfg(test)]
1214mod tests;
1515+1616+#[cfg(test)]
1717+mod test_stream;
13181419/// Lazily initialized Tokio runtime for use in uniffi methods that need a runtime.
1520static RUNTIME: LazyLock<tokio::runtime::Runtime> =
+167
rust/iroh-streamplace/src/streams.rs
···11+// Copyright 2023 Adobe. All rights reserved.
22+// This file is licensed to you under the Apache License,
33+// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
44+// or the MIT license (http://opensource.org/licenses/MIT),
55+// at your option.
66+77+// Unless required by applicable law or agreed to in writing,
88+// this software is distributed on an "AS IS" BASIS, WITHOUT
99+// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
1010+// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
1111+// specific language governing permissions and limitations under
1212+// each license.
1313+1414+use crate::error::SPError;
1515+use std::io::{Read, Seek, SeekFrom, Write};
1616+use std::sync::Arc;
1717+1818+// #[repr(C)]
1919+// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2020+// pub enum SeekMode {
2121+// Start = 0,
2222+// End = 1,
2323+// Current = 2,
2424+// }
2525+2626+/// This allows for a callback stream over the Uniffi interface.
2727+/// Implement these stream functions in the foreign language
2828+/// and this will provide Rust Stream trait implementations
2929+/// This is necessary since the Rust traits cannot be implemented directly
3030+/// as uniffi callbacks
3131+#[uniffi::export(with_foreign)]
3232+pub trait Stream: Send + Sync {
3333+ /// Read a stream of bytes from the stream
3434+ fn read_stream(&self, length: u64) -> Result<Vec<u8>, SPError>;
3535+ /// Seek to a position in the stream
3636+ fn seek_stream(&self, pos: i64, mode: u64) -> Result<u64, SPError>;
3737+ /// Write a stream of bytes to the stream
3838+ fn write_stream(&self, data: Vec<u8>) -> Result<u64, SPError>;
3939+}
4040+4141+impl Stream for Arc<dyn Stream> {
4242+ fn read_stream(&self, length: u64) -> Result<Vec<u8>, SPError> {
4343+ (**self).read_stream(length)
4444+ }
4545+4646+ fn seek_stream(&self, pos: i64, mode: u64) -> Result<u64, SPError> {
4747+ (**self).seek_stream(pos, mode)
4848+ }
4949+5050+ fn write_stream(&self, data: Vec<u8>) -> Result<u64, SPError> {
5151+ (**self).write_stream(data)
5252+ }
5353+}
5454+5555+impl AsMut<dyn Stream> for dyn Stream {
5656+ fn as_mut(&mut self) -> &mut Self {
5757+ self
5858+ }
5959+}
6060+6161+pub struct StreamAdapter<'a> {
6262+ pub stream: &'a mut dyn Stream,
6363+}
6464+6565+impl<'a> StreamAdapter<'a> {
6666+ pub fn from_stream_mut(stream: &'a mut dyn Stream) -> Self {
6767+ Self { stream }
6868+ }
6969+}
7070+7171+impl<'a> From<&'a dyn Stream> for StreamAdapter<'a> {
7272+ #[allow(invalid_reference_casting)]
7373+ fn from(stream: &'a dyn Stream) -> Self {
7474+ let stream = &*stream as *const dyn Stream as *mut dyn Stream;
7575+ let stream = unsafe { &mut *stream };
7676+ Self { stream }
7777+ }
7878+}
7979+8080+// impl<'a> c2pa::CAIRead for StreamAdapter<'a> {}
8181+8282+// impl<'a> c2pa::CAIReadWrite for StreamAdapter<'a> {}
8383+8484+impl<'a> Read for StreamAdapter<'a> {
8585+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
8686+ let mut bytes = self
8787+ .stream
8888+ .read_stream(buf.len() as u64)
8989+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
9090+ let len = bytes.len();
9191+ buf.iter_mut().zip(bytes.drain(..)).for_each(|(dest, src)| {
9292+ *dest = src;
9393+ });
9494+ //println!("read: {:?}", len);
9595+ Ok(len)
9696+ }
9797+}
9898+9999+impl<'a> Seek for StreamAdapter<'a> {
100100+ fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
101101+ let (pos, mode) = match pos {
102102+ SeekFrom::Current(pos) => (pos, 2),
103103+ SeekFrom::Start(pos) => (pos as i64, 0),
104104+ SeekFrom::End(pos) => (pos, 1),
105105+ };
106106+ //println!("Stream Seek {}", pos);
107107+ self.stream
108108+ .seek_stream(pos, mode)
109109+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))
110110+ }
111111+}
112112+113113+impl<'a> Write for StreamAdapter<'a> {
114114+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
115115+ let len = self
116116+ .stream
117117+ .write_stream(buf.to_vec())
118118+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
119119+ Ok(len as usize)
120120+ }
121121+122122+ fn flush(&mut self) -> std::io::Result<()> {
123123+ Ok(())
124124+ }
125125+}
126126+127127+#[cfg(test)]
128128+mod tests {
129129+ use super::*;
130130+131131+ use crate::test_stream::TestStream;
132132+133133+ #[test]
134134+ fn test_stream_read() {
135135+ let mut test = TestStream::from_memory(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
136136+ let mut stream = StreamAdapter::from_stream_mut(&mut test);
137137+ let mut buf = [0u8; 5];
138138+ let len = stream.read(&mut buf).unwrap();
139139+ assert_eq!(len, 5);
140140+ assert_eq!(buf, [0, 1, 2, 3, 4]);
141141+ }
142142+143143+ #[test]
144144+ fn test_stream_seek() {
145145+ let mut test = TestStream::from_memory(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
146146+ let mut stream = StreamAdapter { stream: &mut test };
147147+ let pos = stream.seek(SeekFrom::Start(5)).unwrap();
148148+ assert_eq!(pos, 5);
149149+ let mut buf = [0u8; 5];
150150+ let len = stream.read(&mut buf).unwrap();
151151+ assert_eq!(len, 5);
152152+ assert_eq!(buf, [5, 6, 7, 8, 9]);
153153+ }
154154+155155+ #[test]
156156+ fn test_stream_write() {
157157+ let mut test = TestStream::new();
158158+ let mut stream = StreamAdapter { stream: &mut test };
159159+ let len = stream.write(&[0, 1, 2, 3, 4]).unwrap();
160160+ assert_eq!(len, 5);
161161+ stream.seek(SeekFrom::Start(0)).unwrap();
162162+ let mut buf = [0u8; 5];
163163+ let len = stream.read(&mut buf).unwrap();
164164+ assert_eq!(len, 5);
165165+ assert_eq!(buf, [0, 1, 2, 3, 4]);
166166+ }
167167+}
+80
rust/iroh-streamplace/src/test_stream.rs
···11+// Copyright 2023 Adobe. All rights reserved.
22+// This file is licensed to you under the Apache License,
33+// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
44+// or the MIT license (http://opensource.org/licenses/MIT),
55+// at your option.
66+77+// Unless required by applicable law or agreed to in writing,
88+// this software is distributed on an "AS IS" BASIS, WITHOUT
99+// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
1010+// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
1111+// specific language governing permissions and limitations under
1212+// each license.
1313+1414+use std::io::{Read, Seek, SeekFrom, Write};
1515+use std::sync::RwLock;
1616+1717+use crate::error::SPError;
1818+use crate::streams::Stream;
1919+use std::io::Cursor;
2020+2121+pub struct TestStream {
2222+ stream: RwLock<Cursor<Vec<u8>>>,
2323+}
2424+2525+impl TestStream {
2626+ pub fn new() -> Self {
2727+ Self {
2828+ stream: RwLock::new(Cursor::new(Vec::new())),
2929+ }
3030+ }
3131+ pub fn from_memory(data: Vec<u8>) -> Self {
3232+ Self {
3333+ stream: RwLock::new(Cursor::new(data)),
3434+ }
3535+ }
3636+}
3737+3838+impl Stream for TestStream {
3939+ fn read_stream(&self, length: u64) -> Result<Vec<u8>, SPError> {
4040+ if let Ok(mut stream) = RwLock::write(&self.stream) {
4141+ let mut data = vec![0u8; length as usize];
4242+ let bytes_read = stream
4343+ .read(&mut data)
4444+ .map_err(|e| SPError::IOError(e.to_string()))?;
4545+ data.truncate(bytes_read);
4646+ //println!("read_stream: {:?}, pos {:?}", data.len(), (*stream).position());
4747+ Ok(data)
4848+ } else {
4949+ Err(SPError::IOError("RwLock".to_string()))?
5050+ }
5151+ }
5252+5353+ fn seek_stream(&self, pos: i64, mode: u64) -> Result<u64, SPError> {
5454+ if let Ok(mut stream) = RwLock::write(&self.stream) {
5555+ //stream.seek(SeekFrom::Start(pos as u64)).map_err(|e| StreamError::Io{ reason: e.to_string()})?;
5656+ let whence = match mode {
5757+ 0 => SeekFrom::Start(pos as u64),
5858+ 1 => SeekFrom::End(pos as i64),
5959+ 2 => SeekFrom::Current(pos as i64),
6060+ 3_u64..=u64::MAX => unimplemented!(),
6161+ };
6262+ Ok(stream
6363+ .seek(whence)
6464+ .map_err(|e| SPError::IOError(e.to_string()))?)
6565+ } else {
6666+ Err(SPError::IOError("RwLock".to_string()))
6767+ }
6868+ }
6969+7070+ fn write_stream(&self, data: Vec<u8>) -> Result<u64, SPError> {
7171+ if let Ok(mut stream) = RwLock::write(&self.stream) {
7272+ let len = stream
7373+ .write(&data)
7474+ .map_err(|e| SPError::IOError(e.to_string()))?;
7575+ Ok(len as u64)
7676+ } else {
7777+ Err(SPError::IOError("RwLock".to_string()))?
7878+ }
7979+ }
8080+}