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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
//! Utilities for dealing with annotated strings.
//!
//! This module contains the `split` and `join` function to destructure and recombine strings by
//! redaction remarks. This allows to quickly inspect modified sections of a string.
//!
//! ### Example
//!
//! ```
//! use relay_event_schema::processor;
//! use relay_protocol::{Meta, Remark, RemarkType};
//!
//! let remarks = vec![Remark::with_range(
//!     RemarkType::Substituted,
//!     "myrule",
//!     (7, 17),
//! )];
//!
//! let chunks = processor::split_chunks("Hello, [redacted]!", &remarks);
//! let (joined, join_remarks) = processor::join_chunks(chunks);
//!
//! assert_eq!(joined, "Hello, [redacted]!");
//! assert_eq!(join_remarks, remarks);
//! ```

use std::borrow::Cow;
use std::fmt;

use relay_protocol::{Meta, Remark, RemarkType};
use serde::{Deserialize, Serialize};

/// A type for dealing with chunks of annotated text.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Chunk<'a> {
    /// Unmodified text chunk.
    Text {
        /// The text value of the chunk
        text: Cow<'a, str>,
    },
    /// Redacted text chunk with a note.
    Redaction {
        /// The redacted text value
        text: Cow<'a, str>,
        /// The rule that crated this redaction
        rule_id: Cow<'a, str>,
        /// Type type of remark for this redaction
        #[serde(rename = "remark")]
        ty: RemarkType,
    },
}

impl<'a> Chunk<'a> {
    /// The text of this chunk.
    pub fn as_str(&self) -> &str {
        match self {
            Chunk::Text { text } => text,
            Chunk::Redaction { text, .. } => text,
        }
    }

    /// Effective length of the text in this chunk.
    pub fn len(&self) -> usize {
        self.as_str().len()
    }

    /// The number of UTF-8 encoded Unicode codepoints in this chunk.
    pub fn count(&self) -> usize {
        bytecount::num_chars(self.as_str().as_bytes())
    }

    /// Determines whether this chunk is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl fmt::Display for Chunk<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Chunks the given text based on remarks.
pub fn split_chunks<'a, I>(text: &'a str, remarks: I) -> Vec<Chunk<'a>>
where
    I: IntoIterator<Item = &'a Remark>,
{
    let mut rv = vec![];
    let mut pos = 0;

    for remark in remarks {
        let (from, to) = match remark.range() {
            Some(range) => *range,
            None => continue,
        };

        if from > pos {
            if let Some(piece) = text.get(pos..from) {
                rv.push(Chunk::Text {
                    text: Cow::Borrowed(piece),
                });
            } else {
                break;
            }
        }
        if let Some(piece) = text.get(from..to) {
            rv.push(Chunk::Redaction {
                text: Cow::Borrowed(piece),
                rule_id: remark.rule_id().into(),
                ty: remark.ty(),
            });
        } else {
            break;
        }
        pos = to;
    }

    if pos < text.len() {
        if let Some(piece) = text.get(pos..) {
            rv.push(Chunk::Text {
                text: Cow::Borrowed(piece),
            });
        }
    }

    rv
}

/// Concatenates chunks into a string and emits remarks for redacted sections.
pub fn join_chunks<'a, I>(chunks: I) -> (String, Vec<Remark>)
where
    I: IntoIterator<Item = Chunk<'a>>,
{
    let mut rv = String::new();
    let mut remarks = vec![];
    let mut pos = 0;

    for chunk in chunks {
        let new_pos = pos + chunk.len();
        rv.push_str(chunk.as_str());

        match chunk {
            Chunk::Redaction { rule_id, ty, .. } => {
                remarks.push(Remark::with_range(ty, rule_id.clone(), (pos, new_pos)))
            }
            Chunk::Text { .. } => {
                // Plain text segments do not need remarks
            }
        }

        pos = new_pos;
    }

    (rv, remarks)
}

/// Splits the string into chunks, maps each chunk and then joins chunks again, emitting
/// remarks along the process.
pub fn process_chunked_value<F>(value: &mut String, meta: &mut Meta, f: F)
where
    F: FnOnce(Vec<Chunk>) -> Vec<Chunk>,
{
    let chunks = split_chunks(value, meta.iter_remarks());
    let (new_value, remarks) = join_chunks(f(chunks));

    if new_value != *value {
        meta.clear_remarks();
        for remark in remarks.into_iter() {
            meta.add_remark(remark);
        }
        meta.set_original_length(Some(bytecount::num_chars(value.as_bytes())));
        *value = new_value;
    }
}

#[cfg(test)]
mod tests {
    use similar_asserts::assert_eq;

    use super::*;

    #[test]
    fn test_chunk_split() {
        let remarks = vec![Remark::with_range(
            RemarkType::Masked,
            "@email:strip",
            (33, 47),
        )];

        let text = "Hello Peter, my email address is ****@*****.com. See you";

        let chunks = vec![
            Chunk::Text {
                text: "Hello Peter, my email address is ".into(),
            },
            Chunk::Redaction {
                ty: RemarkType::Masked,
                text: "****@*****.com".into(),
                rule_id: "@email:strip".into(),
            },
            Chunk::Text {
                text: ". See you".into(),
            },
        ];

        assert_eq!(split_chunks(text, &remarks), chunks);
        assert_eq!(join_chunks(chunks), (text.into(), remarks));
    }
}