| 1 |
// Copyright 2024 Google LLC. |
| 2 |
// Use of this source code is governed by a BSD-style license that can be |
| 3 |
// found in the LICENSE file. |
| 4 |
|
| 5 |
//! Common FFI utilities for Rust codec integrations. |
| 6 |
//! |
| 7 |
//! This module provides the SkStreamAdapter type and its Read/Seek trait |
| 8 |
//! implementations. Codec modules should use a type alias to reference this type. |
| 9 |
|
| 10 |
use std::io::{ErrorKind, Read, Seek, SeekFrom}; |
| 11 |
use std::pin::Pin; |
| 12 |
|
| 13 |
#[cxx::bridge(namespace = "rust::stream")] |
| 14 |
mod ffi { |
| 15 |
unsafe extern "C++" { |
| 16 |
include!("rust/common/SkStreamAdapter.h"); |
| 17 |
|
| 18 |
// Declare SkStreamAdapter with rust::stream namespace for type unification |
| 19 |
#[namespace = "rust::stream"] |
| 20 |
type SkStreamAdapter; |
| 21 |
|
| 22 |
fn read(self: Pin<&mut SkStreamAdapter>, buffer: &mut [u8]) -> usize; |
| 23 |
|
| 24 |
fn seek_from_start( |
| 25 |
self: Pin<&mut SkStreamAdapter>, |
| 26 |
requested_pos: u64, |
| 27 |
final_pos: &mut u64, |
| 28 |
) -> bool; |
| 29 |
|
| 30 |
fn seek_from_end( |
| 31 |
self: Pin<&mut SkStreamAdapter>, |
| 32 |
requested_offset: i64, |
| 33 |
final_pos: &mut u64, |
| 34 |
) -> bool; |
| 35 |
|
| 36 |
fn seek_relative( |
| 37 |
self: Pin<&mut SkStreamAdapter>, |
| 38 |
requested_offset: i64, |
| 39 |
final_pos: &mut u64, |
| 40 |
) -> bool; |
| 41 |
} |
| 42 |
|
| 43 |
// Explicitly declare UniquePtr of the type so cxx bridge materializes |
| 44 |
// UniquePtr support |
| 45 |
impl UniquePtr<SkStreamAdapter> {} |
| 46 |
} |
| 47 |
|
| 48 |
// Re-export the SkStreamAdapter type for use in other modules |
| 49 |
pub use ffi::SkStreamAdapter; |
| 50 |
|
| 51 |
impl<'a> Read for Pin<&'a mut SkStreamAdapter> { |
| 52 |
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { |
| 53 |
let bytes_read = self.as_mut().read(buf); |
| 54 |
Ok(bytes_read) |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
impl<'a> Seek for Pin<&'a mut SkStreamAdapter> { |
| 59 |
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> { |
| 60 |
let mut final_pos: u64 = 0; |
| 61 |
let success = match pos { |
| 62 |
SeekFrom::Start(requested_pos) => { |
| 63 |
self.as_mut().seek_from_start(requested_pos, &mut final_pos) |
| 64 |
} |
| 65 |
SeekFrom::End(requested_offset) => self |
| 66 |
.as_mut() |
| 67 |
.seek_from_end(requested_offset, &mut final_pos), |
| 68 |
SeekFrom::Current(requested_offset) => self |
| 69 |
.as_mut() |
| 70 |
.seek_relative(requested_offset, &mut final_pos), |
| 71 |
}; |
| 72 |
if success { |
| 73 |
Ok(final_pos) |
| 74 |
} else { |
| 75 |
Err(ErrorKind::Other.into()) |
| 76 |
} |
| 77 |
} |
| 78 |
} |