bio_seq/seq/
slice.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// Copyright 2021-2024 Jeff Knaggs
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

//use crate::codec::{Codec, Complement};
use crate::codec::{Codec, Complement};
use crate::error::ParseBioError;
//use crate::seq::array::SeqArray;
use crate::seq::ReverseComplement;
use crate::seq::Seq;

use crate::Bs;
use bitvec::field::BitField;
//use bitvec::prelude::*;

use core::fmt;
//use core::hash::{Hash, Hasher};
use core::marker::PhantomData;
use core::str;

use core::ops::{BitAnd, BitOr};

/// A lightweight, read-only window into part of a sequence
#[derive(Debug, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct SeqSlice<A: Codec> {
    pub(crate) _p: PhantomData<A>,
    pub(crate) bs: Bs,
}

impl<A: Codec> TryFrom<&SeqSlice<A>> for usize {
    type Error = ParseBioError;

    fn try_from(slice: &SeqSlice<A>) -> Result<usize, Self::Error> {
        if slice.bs.len() <= usize::BITS as usize {
            Ok(slice.bs.load_le::<usize>())
        } else {
            let len: usize = slice.bs.len() / A::BITS as usize;
            let expected: usize = usize::BITS as usize / A::BITS as usize;
            Err(ParseBioError::SequenceTooLong(len, expected))
        }
    }
}

impl<A: Codec> From<&SeqSlice<A>> for u8 {
    fn from(slice: &SeqSlice<A>) -> u8 {
        assert!(slice.bs.len() <= u8::BITS as usize);
        slice.bs.load_le::<u8>()
    }
}

impl<A: Codec + Complement> ReverseComplement for SeqSlice<A> {
    type Output = Seq<A>;

    /// The inefficient default complementation of reverse
    fn revcomp(&self) -> Seq<A> {
        let mut seq = Seq::<A>::with_capacity(self.len());
        seq.extend(self.rev().map(|base| base.comp()));
        seq
    }
}

impl<A: Codec> SeqSlice<A> {
    /// unsafely index into the `i`th position of a sequence
    pub fn nth(&self, i: usize) -> A {
        A::unsafe_from_bits(self[i].into())
    }

    pub fn len(&self) -> usize {
        self.bs.len() / A::BITS as usize
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<A: Codec> From<&SeqSlice<A>> for String {
    fn from(seq: &SeqSlice<A>) -> Self {
        seq.into_iter().map(Codec::to_char).collect()
    }
}

impl<A: Codec> PartialEq<&str> for SeqSlice<A> {
    fn eq(&self, other: &&str) -> bool {
        let bs = other.as_bytes();
        if bs.len() != self.len() {
            return false;
        }
        for (a, c) in self.iter().zip(bs) {
            match A::try_from_ascii(*c) {
                Some(b) => {
                    if a != b {
                        return false;
                    }
                }
                None => return false,
            }
        }
        true
    }
}

/*
impl<A: Codec> Hash for SeqSlice<A> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.bs.hash(state);
        // prepend length to make robust against matching prefixes
        // (automatic in nightly?)
        //self.len().hash(state);
    }
}
*/

/// Clone a borrowed slice of a sequence into an owned version.
///
/// ```
/// use bio_seq::prelude::*;
///
/// let seq = dna!("CATCGATCGATCG");
/// let slice = &seq[2..7]; // TCGAT
/// let owned = slice.to_owned();
///
/// assert_eq!(&owned, &seq[2..7]);
/// ```
///
impl<A: Codec> ToOwned for SeqSlice<A> {
    type Owned = Seq<A>;

    fn to_owned(&self) -> Self::Owned {
        Seq {
            _p: PhantomData,
            bv: self.bs.into(),
        }
    }
}

impl<A: Codec> AsRef<SeqSlice<A>> for SeqSlice<A> {
    fn as_ref(&self) -> &SeqSlice<A> {
        self
    }
}

impl<A: Codec> fmt::Display for SeqSlice<A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", String::from(self))
    }
}

impl<A: Codec> BitAnd for &SeqSlice<A> {
    type Output = Seq<A>;

    fn bitand(self, rhs: Self) -> Self::Output {
        let mut bv = self.bs.to_bitvec();
        bv &= &rhs.bs;
        Seq::<A> {
            bv,
            _p: PhantomData,
        }
    }
}

impl<A: Codec> BitOr for &SeqSlice<A> {
    type Output = Seq<A>;

    fn bitor(self, rhs: Self) -> Self::Output {
        let mut bv = self.bs.to_bitvec();
        bv |= &rhs.bs;

        Seq::<A> {
            bv,
            _p: PhantomData,
        }
    }
}