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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! This module implements **[Flexstr]**, which uses an internal enum
//! to hold either a fixed string of up to a maximum length, or an owned [String].
//! The structure satisfies the following axiom:
//! >   *For N <= 256, a `Flexstr<N>` is represented internally by an
//!     owned String if and only if the length of the string is greater than
//!     or equal to N*.
//!
//! For example, a `Flexstr<16>` will hold a string of up to 15 bytes 
//! in an u8-array of size 16. The first byte of the array holds the length of
//! the string.  If subsequent operations such as [Flexstr::push_str]
//! extends the string past 15 bytes, the representation will switch to an owned
//! String.  Conversely, an operation such as [Flexstr::truncate]
//! may switch the representation back to a fixed string.
//! The default N is 32.  **The largest N for which the axiom holds
//! is 256.**  For all N>256, the internal representation is always an owned
//! string.
//!
//! Example:
//! ```
//!  let mut s:Flexstr<8> = Flexstr::from("abcdef");
//!  assert!(s.is_fixed());
//!  s.push_str("ghijk");
//!  assert!(s.is_owned());
//!  s.truncate(7);
//!  assert!(s.is_fixed());
//! ```
//!
//! The intended use of this datatype is for
//! situations when the lengths of strings are *usually* less than N, with
//! only occasional exceptions that require a different representation.
//! However, unlike the other string types in this crate, a Flexstr cannot
//! be copied and is thus subject to move semantics.  The serde serialization
//! option is also supported (`features serde`).

#![allow(unused_variables)]
#![allow(non_snake_case)]
#![allow(non_camel_case_types)]
#![allow(unused_parens)]
#![allow(unused_assignments)]
#![allow(unused_mut)]
#![allow(unused_imports)]
#![allow(dead_code)]
use crate::fstr;
use crate::zstr;
use crate::tstr;
use crate::{str12, str128, str16, str192, str24, str256, str32, str4, str48, str64, str8, str96};
use std::cmp::{min, Ordering};
use std::ops::Add;
use crate::flexible_string::Strunion::*;

/*
#[derive(Copy,Clone, Eq, PartialEq, Hash)]
enum Strunion_fixed
{
  single(tstr<8>),
  double(tstr<16>),
  quad(tstr<32>),
  octo(tstr<64>),
  hexa(tstr<128>),
}
impl Default for Strunion_fixed {
  fn default() -> Self {
    Strunion_fixed::single(tstr::<8>::default())
  }
}
*/

#[derive(Eq, PartialEq, Hash)]
enum Strunion<const N:usize>
{
   fixed(tstr<N>),
   owned(String),
}//Strunion
impl<const N:usize> Clone for Strunion<N> {
  fn clone(&self) -> Self {
    match &self {
      fixed(s) => fixed(*s),
      owned(s) => owned(s.clone()),
    }//match
  }
}//impl Clone

#[derive(Clone, Eq, PartialEq, Hash)]
pub struct Flexstr<const N:usize=32>
{
   inner:Strunion<N>,
}
impl<const N:usize> Flexstr<N>
{
  /// Creates a new `Flexstr<N>` with given &str.  If the length of the &str
  /// is less than N and N<=256, the internal representation is an `[u8;N]`
  /// array with the first byte holding the length of the string. Otherwise,
  /// the internal representation is an owned String.
  ///
  ///  The Flexstr type satisfies the following axiom:
  /// >   *For N <= 256, a `Flexstr<N>` is represented internally by an
  ///     owned String if and only if the length of the string is greater
  ///     than or equal to N*.

  pub fn make(s:&str) -> Self
  {
     if s.len()<N && N<=256 {Flexstr{inner:fixed(tstr::<N>::from(s))}}
     else {Flexstr{inner:owned(String::from(s))}}
  }//make

  #[cfg(feature="serde")]
  /// this function is only added for uniformity in serde implementation
  pub fn try_make(s: &str) -> Result<Flexstr<N>, &str> {
       Ok(Flexstr::make(s))
    }

  /// length of the string in bytes. This is a constant-time operation.
  pub fn len(&self) -> usize
  {
    match &self.inner {
      fixed(s) => s.len(),
      owned(s) => s.len(),
    }//match
  }//len

  /// creates an empty string, equivalent to [Flexstr::default]
  pub fn new() -> Self { Self::default() }

  /// length in number of characters as opposed to bytes: this is
  /// not necessarily a constant time operation.
  pub fn charlen(&self) -> usize {
     match &self.inner {
       fixed(s) => s.charlen(),
       owned(s) => {
         let v: Vec<_> = s.chars().collect();
         v.len()
       },
     }//match
  }//charlen

  /// converts fstr to &str, possibly using using [std::str::from_utf8_unchecked].  Since
  /// Flexstr can only be built from valid utf8 sources, this function
  /// is safe.
  pub fn to_str(&self) -> &str
  {
    match &self.inner {
      fixed(s) => s.to_str(),
      owned(s) => &s[..],
    }//match
  }//to_str

    /// same functionality as [Flexstr::to_str], but only uses
    ///[std::str::from_utf8] and may technically panic.
    pub fn as_str(&self) -> &str //{self.to_str()}
    {
       match &self.inner {
         fixed(s) => s.as_str(),
         owned(s) => &s[..],
       }//match        
    }

  /// retrieves a copy of the underlying fixed string, if it is a fixed string.
  /// Note that since the `tstr` type is not exported, this function should
  /// be used in conjunction with one of the public aliases [str4]-[str256].
  /// For example,
  /// ```
  ///   let s = Flexstr::<8>::from("abcd");
  ///   let t:str8 = s.get_str().unwrap();
  /// ```
  pub fn get_str(&self) -> Option<tstr<N>> {
    if let fixed(s) = &self.inner { Some(*s) }
    else {None}
  }//get_str

  /// if the underlying representation of the string is an owned string,
  /// return the owned string, leaving an empty string in its place.
  pub fn take_string(&mut self) -> Option<String>
  {
     if let owned(s) = &mut self.inner {
       let mut temp = fixed(tstr::new());
       std::mem::swap(&mut self.inner, &mut temp);
       if let owned(t) = temp {Some(t)} else {None}
     }
     else {None}
  }//take_owned

  /// this function consumes the Flexstr and returns an owned string
  pub fn to_string(self) -> String 
  {
    match self.inner {
      fixed(s) => s.to_string(),
      owned(s) => s,
    }//match    
  }//to_string

  /// returns the nth char of the string, if it exists
  pub fn nth(&self, n: usize) -> Option<char> {
    self.to_str().chars().nth(n)
  }

  /// returns the nth byte of the string as a char.  This function
  /// is designed to be quicker than [Flexstr::nth] and does not check
  /// for bounds.
  pub fn nth_ascii(&self, n:usize) -> char {
    match &self.inner {
       fixed(s) => s.nth_ascii(n),
       owned(s) => s.as_bytes()[n] as char,
    }
  }//nth_ascii

  /// returns a u8-slice that represents the underlying string. The first
  /// byte of the slice is **not** the length of the string regarless of
  /// the internal representation.
  pub fn as_bytes(&self) -> &[u8] {
    match &self.inner {
      fixed(f) => f.as_bytes(),
      owned(s) => s.as_bytes(),
    }//match
  }

  /// changes a character at character position i to c.  This function
  /// requires that c is in the same character class (ascii or unicode)
  /// as the char being replaced.  It never shuffles the bytes underneath.
  /// The function returns true if the change was successful.
  pub fn set(&mut self, i: usize, c: char) -> bool {
     match &mut self.inner {
       fixed(s) => s.set(i,c),
       owned(s) => unsafe {
        let ref mut cbuf = [0u8; 4];
        c.encode_utf8(cbuf);
        let clen = c.len_utf8();
        if let Some((bi, rc)) = s.char_indices().nth(i) {
            if clen == rc.len_utf8() {
                s.as_bytes_mut()[bi..bi+clen].copy_from_slice(&cbuf[..clen]);
                //self.chrs[bi + 1..bi + clen + 1].copy_from_slice(&cbuf[..clen]);
                //for k in 0..clen {self.chrs[bi+k+1] = cbuf[k];}
                return true;
            }
        }
        return false;
       },
     }//match
  } //set

  /// returns whether the internal representation is a fixed string (tstr)
  pub fn is_fixed(&self) -> bool {
    match &self.inner {
      fixed(_) => true,
      owned(_) => false,
    }
  }//is_fixed

  /// returns whether the internal representation is an owned String
  pub fn is_owned(&self) -> bool { !self.is_fixed() }

  /// applies the destructive closure only if the internal representation
  /// is a fixed string
  pub fn if_fixed<F>(&mut self, f:F) where F:FnOnce(&mut tstr<N>)
  {
     if let fixed(s) = &mut self.inner {f(s);}
  }

  /// applies the destructive closure only if the internal representation
  /// is a fixed string
  pub fn if_owned<F>(&mut self, f:F) where F:FnOnce(&mut str)
  {
     if let owned(s) = &mut self.inner {f(s);}
  }

  /// applies closure f if the internal representation is a fixed string,
  /// or closure g if the internal representation is an owned string.
  pub fn map_or<F,G,U>(&self, f:F, g:G) -> U
    where F:FnOnce(&tstr<N>)-> U, G:FnOnce(&str) -> U
  {
     match &self.inner {
       fixed(s) => f(s),
       owned(s) => g(&s[..]),
     }//match
  }//map

  /// version of [Flexstr::map_or] accepting FnMut closures
  pub fn map_or_mut<F,G,U>(&mut self, f:&mut F, g:&mut G) -> U
    where F:FnMut(&mut tstr<N>)-> U, G:FnMut(&mut str) -> U
  {
     match &mut self.inner {
       fixed(s) => f(s),
       owned(s) => g(&mut s[..]),
     }//match
  }//map
  
  /// This function will append the Flexstr with the given slice,
  /// switching to the owned-String representation if necessary.  The function
  /// returns true if the resulting string uses a `tstr<N>` type, and
  /// false if the representation is an owned string.
  pub fn push_str(&mut self, s:&str) -> bool {
    match &mut self.inner {
      fixed(fs) if fs.len()+s.len() < N => { fs.push(s); true},
      fixed(fs) => {
        let fss = fs.to_string() + s;
        self.inner = owned(fss);
        false
      },
      owned(ns) => {ns.push_str(s); false},
    }//match
  }//push

  /// appends string with a single character, switching to the String
  /// representation if necessary.  Returns true if resulting string
  /// remains fixed.
  pub fn push(&mut self, c:char) -> bool {
     let clen = c.len_utf8();
     match &mut self.inner {
       owned(s) => { s.push(c); false},
       fixed(s) if s.len()+clen>=N => {
         let mut fss = s.to_string();  fss.push(c);
	 self.inner = owned(fss);
	 false
       },
       fixed(s) => {
         let mut buf = [0u8;4];
	 let bstr = c.encode_utf8(&mut buf);
	 s.push(bstr);
	 true
       }
     }//match
  }//push

  
  /// this function truncates a string at the indicated byte position,
  /// returning true if the truncated string is fixed, and false if owned.
  /// The operation has no effect if n is larger than the length of the
  /// string.  The operation will **panic** if n is not on a character
  /// boundary, similar to [String::truncate].
  pub fn truncate(&mut self, n: usize) -> bool {
    match &mut self.inner {
      fixed(fs) if n<fs.len() => { fs.truncate_bytes(n); true },
      fixed(_) => {true},
      owned(s) if n<N => {
        assert!(s.is_char_boundary(n));
        self.inner = fixed(tstr::<N>::from(&s[..n]));
        true
      },
      owned(s) => { if n<s.len() {s.truncate(n);} false},
    }//match
  }//truncate

    /// resets string to empty
    pub fn clear(&mut self) {
      match &mut self.inner {
         fixed(s) => {s.clear();},
         owned(s) => { self.inner = fixed(tstr::default());},
      }
    }//clear

  /// returns string corresponding to slice indices as a copy or clone.
  pub fn substr(&self, start: usize, end: usize) -> Flexstr<N> {
    match &self.inner {
      fixed(s) => Flexstr{inner:fixed(s.substr(start,end))},
      owned(s) => Self::from(&s[start..end]),
    }
  }//substr


  /// Splits the string into a `tstr<N>` portion and a String portion.
  /// The structure inherits the fixed part and the String returned will
  /// contain the extra bytes that does not fit.  Example:
  ///
  /// ```
  ///   let mut fs:Flexstr<4> = Flexstr::from("abcdefg");
  ///   let extras = fs.split_off();
  ///   assert!( &fs=="abc" && &extras=="defg" && fs.is_fixed());
  /// ```
  pub fn split_off(&mut self) -> String {
    match &mut self.inner {
      fixed(s) => { String::default() },
      owned(s) => {
	 let answer = String::from(&s[N-1..]);
         self.inner = fixed( tstr::<N>::from(&s[..N-1]) );
	 answer
      }
    }//match
  }//split_off

} //impl<N>


impl<const N:usize> Default for Flexstr<N> {
  fn default() -> Self { Flexstr {inner:fixed(tstr::<N>::default())} }
}

impl<const N:usize> std::ops::Deref for Flexstr<N>
{
    type Target = str;
    fn deref(&self) -> &Self::Target {
      self.to_str()
    }
}

impl<T: AsRef<str> + ?Sized, const N: usize> std::convert::From<&T> for Flexstr<N> {
    fn from(s: &T) -> Self {
        Self::make(s.as_ref())
    }
}
impl<T: AsMut<str> + ?Sized, const N: usize> std::convert::From<&mut T> for Flexstr<N> {
    fn from(s: &mut T) -> Self {
        Self::make(s.as_mut())
    }
}

impl<const N: usize> std::cmp::PartialOrd for Flexstr<N> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        //Some(self.chrs[0..self.len].cmp(other.chrs[0..other.len]))
        Some(self.cmp(other))
    }
}

impl<const N: usize> std::cmp::Ord for Flexstr<N> {
    fn cmp(&self, other: &Self) -> Ordering {
      self.to_str().cmp(other.to_str())
    }
}

impl<const N: usize> std::convert::AsRef<str> for Flexstr<N> {
    fn as_ref(&self) -> &str {
        self.to_str()
    }
}
impl<const N: usize> std::convert::AsMut<str> for Flexstr<N> {
    fn as_mut(&mut self) -> &mut str {
       match &mut self.inner {
         fixed(f) => f.as_mut(),
         owned(s) => s.as_mut(),
       }//match
    }
}

impl<const N: usize> PartialEq<&str> for Flexstr<N> {
    fn eq(&self, other: &&str) -> bool {
        &self.to_str() == other // see below
    } //eq
}

impl<const N: usize> PartialEq<&str> for &Flexstr<N> {
    fn eq(&self, other: &&str) -> bool {
        &self.to_str() == other
    } //eq
}
impl<'t, const N: usize> PartialEq<Flexstr<N>> for &'t str {
    fn eq(&self, other: &Flexstr<N>) -> bool {
        &other.to_str() == self
    }
}
impl<'t, const N: usize> PartialEq<&Flexstr<N>> for &'t str {
    fn eq(&self, other: &&Flexstr<N>) -> bool {
        &other.to_str() == self
    }
}

impl<const N: usize> std::fmt::Debug for Flexstr<N> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.pad(&self.to_str())
    }
} // Debug impl

impl<const N: usize> std::fmt::Display for Flexstr<N> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.to_str())
    }
}

impl<const N: usize> std::fmt::Write for Flexstr<N> {
    fn write_str(&mut self, s: &str) -> std::fmt::Result
    {
        self.push_str(s);
        Ok(())
    } //write_str
} //std::fmt::Write trait


impl<const N: usize> std::convert::From<String> for Flexstr<N> {
    /// *will consume owned string and convert it to a fixed
    /// representation if its length is less than N*
    fn from(s: String) -> Self {
        if s.len()>=N {
	  Flexstr{inner:owned(s)}
	} else {
	  Flexstr{inner:fixed(tstr::<N>::from(&s[..]))}
	}
    }
}//from String

impl<const M: usize> Flexstr<M> {
  /// returns a copy/clone of the string with new fixed capacity N.
  /// Example:
  /// ```
  ///  let a:Flexstr<4> = Flexstr::from("ab");
  ///  let mut b:Flexstr<8> = a.resize();
  ///  b.push_str("cdef");
  ///  assert!(b.is_fixed());
  ///  a.push_str("1234");
  ///  assert!(a.is_owned());
  /// ```
  pub fn resize<const N: usize>(&self) -> Flexstr<N> {
    Flexstr::from(self)
  }
}