phonelib 0.3.0

A comprehensive library for phone number validation, formatting, parsing, and manipulation
Documentation
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
# Phonelib

[![Crates.io](https://img.shields.io/crates/v/phonelib.svg)](https://crates.io/crates/phonelib)
[![Documentation](https://docs.rs/phonelib/badge.svg)](https://docs.rs/phonelib)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Rust](https://img.shields.io/badge/rust-1.70%2B-blue.svg)](https://www.rust-lang.org)

Phonelib is a comprehensive Rust library for handling phone numbers. It provides functions for validation, formatting, type detection, text extraction, batch processing, and much more.

## Features

- โœ… **Phone Number Validation** - Check if phone numbers are valid
- ๐ŸŒ **Country Detection** - Extract country information from phone numbers  
- ๐Ÿ”ง **Normalization** - Clean and standardize phone number formats
- ๐ŸŽจ **Multiple Format Support** - E.164, International, National, RFC3966
- ๐Ÿ“ฑ **Type Detection** - Identify mobile, landline, toll-free, premium numbers
- ๐Ÿ“ **Text Extraction** - Parse phone numbers from free-form text
- โš–๏ธ **Comparison & Equality** - Compare numbers regardless of format with `PhoneNumber` struct
- ๐ŸŽฒ **Random Number Generation** - Generate valid random phone numbers
- ๐Ÿš€ **Batch Processing** - Process multiple numbers efficiently
- ๐Ÿ” **Smart Suggestions** - Get correction suggestions for invalid numbers
- ๐Ÿ”’ **Privacy Tools** - Redact phone numbers in text

## Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
phonelib = "0.3.0"
```

## Quick Start

```rust
use phonelib::*;

// Basic validation
let is_valid = is_valid_phone_number("+12025550173".to_string());

// Format a number
let formatted = format_phone_number(
    "12025550173".to_string(), 
    PhoneFormat::International
);

// Detect number type
let number_type = detect_phone_number_type("+442079460958".to_string());

// Extract phone numbers from text
let text = "Call me at +12025550173 or +442079460958";
let numbers = extract_phone_numbers_from_text(text);

// Compare phone numbers (PhoneNumber struct with Eq trait)
let num1 = PhoneNumber::parse("+12025550173").unwrap();
let num2 = PhoneNumber::parse("12025550173").unwrap();
assert_eq!(num1, num2); // Same number, different formats
```

## API Reference

### Core Types

```rust
pub struct Country {
    pub name: &'static str,
    pub code: &'static str,
    pub phone_lengths: &'static [u8],
    pub prefix: u32,
}

pub enum PhoneFormat {
    E164,          // +1234567890
    International, // +1 234 567-890
    National,      // (234) 567-890
    RFC3966,       // tel:+1-234-567-890
}

pub enum PhoneNumberType {
    Mobile, FixedLine, TollFree, PremiumRate, 
    SharedCost, Voip, PersonalNumber, Pager, 
    Uan, Emergency, Voicemail, Unknown,
}
```

### Basic Functions

#### Phone Number Validation

```rust
use phonelib::is_valid_phone_number;

let phone_number = "+1234567890".to_string();
if is_valid_phone_number(phone_number) {
    println!("Valid phone number!");
}
```

#### Country Extraction

```rust
use phonelib::extract_country;

let phone_number = "+1234567890".to_string();
match extract_country(phone_number) {
    Some(country) => println!("Country: {} ({})", country.name, country.code),
    None => println!("Country not found"),
}
```

#### Phone Number Normalization

```rust
use phonelib::{normalize_phone_number, normalize_phone_number_in_place};

// Returns normalized number without modifying input
let normalized = normalize_phone_number("+1 (234) 567-890".to_string());
println!("Normalized: {:?}", normalized); // Some("+1234567890")

// Modifies the input string in place
let mut phone = "+1 (234) 567-890".to_string();
normalize_phone_number_in_place(&mut phone);
println!("In-place normalized: {}", phone);
```

### Phone Number Formatting

```rust
use phonelib::{format_phone_number, PhoneFormat};

let number = "1234567890".to_string();

// E.164 format
let e164 = format_phone_number(number.clone(), PhoneFormat::E164);
// Result: Some("+1234567890")

// International format
let intl = format_phone_number(number.clone(), PhoneFormat::International);
// Result: Some("+1 234 567-890")

// National format
let national = format_phone_number(number.clone(), PhoneFormat::National);
// Result: Some("(234) 567-890")

// RFC3966 format
let rfc = format_phone_number(number.clone(), PhoneFormat::RFC3966);
// Result: Some("tel:+1-234-567-890")
```

### Phone Number Type Detection

```rust
use phonelib::{
    detect_phone_number_type, is_mobile_number, 
    is_landline_number, is_toll_free_number, PhoneNumberType
};

let mobile = "447123456789".to_string();
let landline = "442079460958".to_string();
let toll_free = "18001234567".to_string();

// Detect specific type
match detect_phone_number_type(mobile.clone()) {
    Some(PhoneNumberType::Mobile) => println!("It's a mobile number!"),
    Some(other_type) => println!("It's a {:?}", other_type),
    None => println!("Invalid or unknown type"),
}

// Quick type checks
if is_mobile_number(mobile) {
    println!("Mobile number detected");
}

if is_landline_number(landline) {
    println!("Landline number detected");
}

if is_toll_free_number(toll_free) {
    println!("Toll-free number detected");
}
```

### Random Phone Number Generation

```rust
use phonelib::{generate_random_phone_number, generate_random_phone_numbers};

// Generate a single random number
let random_us = generate_random_phone_number("US");
println!("Random US number: {:?}", random_us);

// Generate multiple random numbers
let random_numbers = generate_random_phone_numbers("GB", 5);
println!("5 random UK numbers: {:?}", random_numbers);
```

### Phone Number Comparison

```rust
use phonelib::{are_phone_numbers_equal, group_equivalent_phone_numbers};

// Compare two numbers
let num1 = "+1234567890".to_string();
let num2 = "(234) 567-890".to_string();

if are_phone_numbers_equal(num1, num2) {
    println!("Numbers are equivalent!");
}

// Group equivalent numbers
let numbers = vec![
    "+1234567890".to_string(),
    "(234) 567-890".to_string(),
    "+9876543210".to_string(),
    "987-654-3210".to_string(),
];

let groups = group_equivalent_phone_numbers(numbers);
for (i, group) in groups.iter().enumerate() {
    println!("Group {}: {:?}", i + 1, group);
}
```

### Batch Processing

```rust
use phonelib::{
    validate_phone_numbers_batch, 
    normalize_phone_numbers_batch,
    detect_phone_number_types_batch,
    analyze_phone_numbers_batch
};

let numbers = vec![
    "1234567890".to_string(),
    "invalid".to_string(),
    "447123456789".to_string(),
];

// Batch validation
let valid_results = validate_phone_numbers_batch(numbers.clone());
println!("Validation results: {:?}", valid_results);

// Batch normalization
let normalized_results = normalize_phone_numbers_batch(numbers.clone());
println!("Normalized results: {:?}", normalized_results);

// Batch type detection
let type_results = detect_phone_number_types_batch(numbers.clone());
println!("Type results: {:?}", type_results);

// Comprehensive batch analysis
let analyses = analyze_phone_numbers_batch(numbers);
for analysis in analyses {
    println!("Original: {}", analysis.original);
    println!("Valid: {}", analysis.is_valid);
    println!("Normalized: {:?}", analysis.normalized);
    println!("Country: {:?}", analysis.country.map(|c| c.name));
    println!("Type: {:?}", analysis.phone_type);
    println!("---");
}
```

### Smart Suggestions & Intelligence

```rust
use phonelib::{
    suggest_phone_number_corrections, 
    is_potentially_valid_phone_number,
    guess_country_from_number
};

// Get suggestions for invalid numbers
let invalid_number = "123456789".to_string();
let suggestions = suggest_phone_number_corrections(invalid_number, Some("US"));
println!("Suggestions: {:?}", suggestions);

// Check if a number might be valid with different formatting
let maybe_valid = "123-456-7890".to_string();
if is_potentially_valid_phone_number(maybe_valid) {
    println!("This number might be valid with proper formatting");
}

// Guess country from number patterns
let mystery_number = "442079460958".to_string();
match guess_country_from_number(mystery_number) {
    Some(country) => println!("Likely from: {}", country.name),
    None => println!("Cannot determine country"),
}
```

### Text Extraction

Extract phone numbers from free-form text:

```rust
use phonelib::{
    extract_phone_numbers_from_text,
    extract_valid_phone_numbers_from_text,
    extract_phone_numbers_with_country_hint,
    replace_phone_numbers_in_text,
    redact_phone_numbers,
    count_phone_numbers_in_text,
};

let text = "Contact us at +12025550173 or call our UK office at +442079460958";

// Extract all phone numbers
let numbers = extract_phone_numbers_from_text(text);
for num in &numbers {
    println!("Found: {} at position {}-{}", num.raw, num.start, num.end);
    println!("  Normalized: {:?}", num.normalized);
    println!("  Valid: {}", num.is_valid);
}

// Extract only valid numbers
let valid_numbers = extract_valid_phone_numbers_from_text(text);

// Extract with country hint for national numbers
let us_text = "Call (202) 555-0173 for assistance";
let numbers = extract_phone_numbers_with_country_hint(us_text, "US");

// Count phone numbers
let count = count_phone_numbers_in_text(text);
println!("Found {} phone numbers", count);

// Replace phone numbers
let replaced = replace_phone_numbers_in_text(text, |num| {
    format!("[PHONE: {}]", num.normalized.as_deref().unwrap_or(&num.raw))
});

// Redact for privacy (show last 4 digits)
let redacted = redact_phone_numbers(text, 4);
println!("{}", redacted); // "Contact us at ********0173 or..."
```

### PhoneNumber Struct with Equality

The `PhoneNumber` struct provides type-safe phone number handling with proper equality comparison:

```rust
use phonelib::{PhoneNumber, PhoneNumberSet, PhoneFormat};
use std::collections::HashSet;

// Parse phone numbers
let num1 = PhoneNumber::parse("+12025550173").unwrap();
let num2 = PhoneNumber::parse("12025550173").unwrap();
let num3 = PhoneNumber::parse("+442079460958").unwrap();

// Equality comparison (same number, different formats)
assert_eq!(num1, num2);
assert_ne!(num1, num3);

// Use in HashSet for deduplication
let mut set = HashSet::new();
set.insert(num1.clone());
set.insert(num2.clone()); // Won't be added - duplicate
assert_eq!(set.len(), 1);

// PhoneNumber methods
println!("E.164: {}", num1.e164());
println!("National: {}", num1.national_number());
println!("Country code: {:?}", num1.country_code());
println!("Is mobile: {}", num1.is_mobile());
println!("Formatted: {}", num1.format(PhoneFormat::International));

// Parse with country hint for national numbers
let national = PhoneNumber::parse_with_country("2025550173", "US");

// PhoneNumberSet for efficient deduplication
let mut phone_set = PhoneNumberSet::new();
phone_set.add("+12025550173");
phone_set.add("12025550173");     // Duplicate - not added
phone_set.add("+442079460958");
assert_eq!(phone_set.len(), 2);

// Check membership
assert!(phone_set.contains("12025550173"));

// Create from iterator
let numbers = vec!["+12025550173", "12025550173", "+442079460958"];
let set: PhoneNumberSet = numbers.into_iter().collect();
assert_eq!(set.len(), 2);
```

## Country Support

The library supports **246 countries** with accurate:
- Country codes and prefixes
- Valid phone number lengths
- Mobile vs. landline detection patterns
- Toll-free and premium number identification

### Supported Countries Include:
- ๐Ÿ‡บ๐Ÿ‡ธ United States & Canada (NANP)
- ๐Ÿ‡ฌ๐Ÿ‡ง United Kingdom
- ๐Ÿ‡ฉ๐Ÿ‡ช Germany
- ๐Ÿ‡ซ๐Ÿ‡ท France
- ๐Ÿ‡ฎ๐Ÿ‡ณ India
- ๐Ÿ‡ฆ๐Ÿ‡บ Australia
- And 240+ more countries worldwide

## Performance

The library is optimized for performance:
- โœ… Zero external dependencies
- โœ… Efficient string processing
- โœ… Batch processing capabilities
- โœ… In-place operations available

Benchmark results show excellent performance for validation and normalization operations.

## Examples

### Complete Example

```rust
use phonelib::*;

fn main() {
    let numbers = vec![
        "1234567890",
        "+44 7123 456789",
        "(555) 123-4567",
        "invalid-number",
    ];
    
    for number in numbers {
        let number = number.to_string();
        println!("\n--- Analyzing: {} ---", number);
        
        // Basic validation
        let is_valid = is_valid_phone_number(number.clone());
        println!("Valid: {}", is_valid);
        
        if is_valid {
            // Format in different styles
            if let Some(e164) = format_phone_number(number.clone(), PhoneFormat::E164) {
                println!("E.164: {}", e164);
            }
            
            if let Some(intl) = format_phone_number(number.clone(), PhoneFormat::International) {
                println!("International: {}", intl);
            }
            
            // Detect country
            if let Some(country) = extract_country(number.clone()) {
                println!("Country: {} ({})", country.name, country.code);
            }
            
            // Detect type
            if let Some(phone_type) = detect_phone_number_type(number.clone()) {
                println!("Type: {:?}", phone_type);
            }
        } else {
            // Suggest corrections
            let suggestions = suggest_phone_number_corrections(number, Some("US"));
            if !suggestions.is_empty() {
                println!("Suggestions: {:?}", suggestions);
            }
        }
    }
}
```

## Contributing

Contributions to the Phonelib library are welcome! Here's how you can help:

- ๐Ÿ› **Report bugs** - Open an issue if you find any problems
- ๐Ÿ’ก **Suggest features** - Share ideas for new functionality  
- ๐Ÿ”ง **Submit pull requests** - Help improve the code
- ๐Ÿ“– **Improve documentation** - Help make the docs better
- ๐Ÿงช **Add tests** - Increase test coverage

### Development Setup

```bash
# Clone the repository
git clone https://github.com/mohamadzoh/phonelib.git
cd phonelib

# Run tests
cargo test

# Run benchmarks
cargo bench

# Check code formatting
cargo fmt

# Run clippy for linting
cargo clippy
```

## Changelog

### v0.2.1 (Latest)

๐ŸŽ‰ **Text Extraction & Equality Release**

- ๐Ÿ“ **Text Extraction** - Extract phone numbers from free-form text
  - `extract_phone_numbers_from_text` - Find all phone numbers in text
  - `extract_valid_phone_numbers_from_text` - Find only valid numbers
  - `extract_phone_numbers_with_country_hint` - Parse with default country
  - `replace_phone_numbers_in_text` - Custom replacement function
  - `redact_phone_numbers` - Privacy-focused masking
  - `count_phone_numbers_in_text` - Quick count
- โš–๏ธ **PhoneNumber Struct** - Type-safe phone numbers with equality
  - Implements `Eq`, `PartialEq`, `Hash` for use in collections
  - Implements `Display`, `FromStr` for easy conversion
  - Methods: `e164()`, `national_number()`, `format()`, `is_mobile()`, etc.
- ๐Ÿ—‚๏ธ **PhoneNumberSet** - Efficient deduplication collection
- ๐Ÿ“š **Improved Documentation** - Complete rustdoc coverage
- ๐Ÿ”ง **Code Quality** - All clippy warnings resolved

### v0.2.0

๐ŸŽ‰ **Major Feature Release**

- โœจ **Phone Number Formatting** - Multiple format support (E.164, International, National, RFC3966)
- ๐Ÿ“ฑ **Type Detection** - Identify mobile, landline, toll-free, premium numbers
- ๐ŸŽฒ **Random Generation** - Generate valid random phone numbers by country
- โš–๏ธ **Number Comparison** - Compare numbers regardless of format
- ๐Ÿš€ **Batch Processing** - Process multiple numbers efficiently
- ๐Ÿ” **Smart Suggestions** - Get correction suggestions for invalid numbers
- ๐Ÿ“Š **Comprehensive Analysis** - Detailed phone number analysis
- ๐ŸŒ **Enhanced Country Support** - Better patterns for major countries

### v0.1.6

- ๐Ÿ› Bug fixes and performance improvements
- ๐Ÿ“š Documentation updates

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Rusty Rails Project

Phonelib is part of the larger **Rusty Rails** project, which aims to bridge the gap between Rust and Ruby/Ruby on Rails ecosystems. We're actively working on recreating Ruby libraries in Rust to make working with Rust more easy and fun for new developers.

### Related Projects

- ๐Ÿ”— More Rust libraries coming soon!
- ๐Ÿš€ Performance-focused Ruby alternatives
- ๐Ÿ“ฆ Easy-to-use APIs familiar to Ruby developers

---

**Made with โค๏ธ by the Rusty Rails team**