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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
use rstring_builder::StringBuilder;
use text_reader::TextReader;

fn remove_all_struct<S: AsRef<str>>(json: S) -> String {
  let json = json.as_ref();

  let mut builder = StringBuilder::new();
  let mut reader = TextReader::new(json);
  while reader.has_next() {
    match reader.next() {
      Some('"') => {
        let mut last_coma = false;
        if let Some(',') = reader.back().peek() {
          last_coma = true;
        }
        reader.next();
        let mut detector = reader.detector();
        if detector.next_text("@struct\"").no() {
          builder.append('"');
          continue;
        }

        let mut times = 0;
        while reader.has_next() {
          match reader.next() {
            Some('"') => {
              times += 1;
              if times == 2 {
                break;
              }
            },
            Some(ch) => {},
            None => {}
          }
        }

        let need_rm_last_coma = match reader.next() {
          Some(',') => false,
          Some('}') => {
            reader.back();
            true
          },
          Some(']') => {
            reader.back();
            true
          },
          _ => panic!("Json fail")
        };
        if need_rm_last_coma {
          builder.delete_at(builder.len() - 1);
        }
      }
      Some(ch) => {
        builder.append(ch);
        continue;
      }
      None => {}
    }
  }

  builder.string()
}


/// fill @struct key to json string.
pub fn fill_json_struct<S: AsRef<str>>(json: S) -> String {
  let json = self::remove_all_struct(json.as_ref());

  let mut builder = StringBuilder::new();
  let mut reader = TextReader::new(json);

  while reader.has_next() {
    match reader.next() {
      Some('"') => {
        builder.append('"');
        let mut detector = reader.detector();
        if detector.next_text("@type\"").no() {
          continue;
        }
        builder.append("@type\"");
        let mut fnbuilder = StringBuilder::new();
        let mut times = 0;

        while reader.has_next() {
          match reader.next() {
            Some(':') => {
              builder.append(':');
              while reader.has_next() {
                match reader.next() {
                  Some('"') => {
                    reader.back();
                    break
                  }
                  Some(ch) => {
                    builder.append(ch);
                    continue
                  },
                  None => continue
                }
              }
              continue;
            }
            Some('"') => {
              match times {
                0 => {
                  builder.append("\"");
                  times += 1;
                  continue;
                }
                1 => {
                  builder.append(fnbuilder.string())
                    .append("\",")
                    .append(r#""@struct":""#)
                    .append(uppercase_first_char(fnbuilder.string()))
                    .append('"');
                  break;
                }
                _ => {}
              }
              continue;
            }
            Some(ch) => {
              fnbuilder.append(ch);
              continue;
            }
            None => {}
          }
        }
      }
      Some(ch) => {
        builder.append(ch);
        continue;
      }
      None => {}
    }
  }

  builder.string()
}

pub fn extra_struct<S: AsRef<str>>(json: S) -> Option<String> {
  let json = self::fill_json_struct(json);

  let jve = serde_json::from_str::<serde_json::Value>(&json[..]);
  if let Err(e) = jve {
    eprintln!("{} => {:?}", json, e);
    return None;
  }
  let jve = jve.unwrap();
  match jve.get("@struct") {
    Some(t) => {
      if t.is_string() {
        return t.as_str().map(|v| v.to_string());
      }
      None
    }
    None => None
  }


  // Performance comparison

//  let mut builder = StringBuilder::new();
//  let mut reader = TextReader::new(json);
//  while reader.has_next() {
//    match reader.next() {
//      Some('"') => {
//        let mut detector = reader.detector();
//        if detector.next_text("@struct\"").no() {
//          continue;
//        }
//
//        let mut times = 0;
//        while reader.has_next() {
//          match reader.next() {
//            Some(':') => {}
//            Some('"') => {
//              times += 1;
//              if times == 1 {
//                continue;
//              }
//              if times == 2 {
//                return Some(builder.string())
//              }
//            },
//            Some(ch) => {
//              builder.append(ch);
//              continue;
//            },
//            None => {}
//          }
//        }
//      }
//      Some(_) => continue,
//      None => {}
//    }
//  }
//  None
}


pub(crate) fn uppercase_first_char<S: AsRef<str>>(s: S) -> String {
  let mut c = s.as_ref().chars();
  match c.next() {
    None => String::new(),
    Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
  }
}


#[cfg(test)]
mod rdtest {
  use crate::types::{RObject, UpdateAuthorizationState};

  #[test]
  fn test_fill_json_struct() {
    let json = r#"{"@type":"updateAuthorizationState","authorization_state":{"@type":"authorizationStateWaitTdlibParameters"}}"#;
    let json = super::fill_json_struct(json);
    assert_eq!(json, r#"{"@type":"updateAuthorizationState","@struct":"UpdateAuthorizationState","authorization_state":{"@type":"authorizationStateWaitTdlibParameters","@struct":"AuthorizationStateWaitTdlibParameters"}}"#);
    let state: UpdateAuthorizationState = serde_json::from_str(&json[..]).expect("Json fail");
    assert_eq!("updateAuthorizationState", state.td_name());
  }

  #[test]
  fn test_fill_lose_struct() {
    let json = r#"{"@type":"updateAuthorizationState","authorization_state":{"@struct":"AuthorizationStateWaitTdlibParameters","@type":"authorizationStateWaitTdlibParameters"}}"#;
    let ret = super::fill_json_struct(json);
    assert_eq!(ret, r#"{"@type":"updateAuthorizationState","@struct":"UpdateAuthorizationState","authorization_state":{"@type":"authorizationStateWaitTdlibParameters","@struct":"AuthorizationStateWaitTdlibParameters"}}"#)
  }

  #[test]
  fn test_extra_struct() {
    let json = r#"{"@type":"updateAuthorizationState","@struct":"UpdateAuthorizationState","authorization_state":{"@type":"authorizationStateWaitTdlibParameters","@struct":"AuthorizationStateWaitTdlibParameters"}}"#;
    let stname = super::extra_struct(json);
    assert!(stname.is_some());
    assert_eq!("UpdateAuthorizationState", stname.unwrap());
  }

  #[test]
  fn test_fill2() {
    let json = r#"{"@type":"updateOption","@struct":"UpdateOption","name":"version","value":{"@type":"optionValueString","@struct":"OptionValueString","value":"1.4.0"}}"#;
    //                  {"@type":"updateOption","@struct":"UpdateOption","name":"version","value":{"@type":"optionValueString","@struct":"OptionValueString","value":"1.4.0"}}
    let ret = super::fill_json_struct(json);
    assert_eq!(json, &ret[..])
  }
}