bangla 0.1.1

A Rust crate for Bangla date, calendar, number conversion, currency, and Bangladeshi addresses.
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
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::geo_data::{DIVISIONS, DISTRICTS, UPAZILAS, UNIONS};

/// Errors for address operations.
#[derive(Debug, Error)]
pub enum AddressError {
    #[error("Division not found: {0}")]
    DivisionNotFound(String),
    #[error("District not found: {0}")]
    DistrictNotFound(String),
    #[error("Upazila not found: {0}")]
    UpazilaNotFound(String),
}

// ─────────────────────────────────────────────
//  Address structs
// ─────────────────────────────────────────────

/// A complete Bangladeshi postal address mapped for JSON serialization.
///
/// This struct aligns with the standard GeoCode-based JSON format:
/// ```json
/// {
///   "division": { "geoCode": "3", "name": "ঢাকা" },
///   "district": { "geoCode": "10", "name": "ঢাকা" },
///   "upazila": { "geoCode": "06", "name": "মিরপুর" }
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BanglaAddress {
    /// Division (বিভাগ)
    pub division: AddressComponent,
    /// District (জেলা)
    pub district: AddressComponent,
    /// Upazila / Thana (উপজেলা / থানা)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub upazila: Option<AddressComponent>,
    /// Union / Ward (ইউনিয়ন / ওয়ার্ড)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub union: Option<AddressComponent>,
    /// Village / Area / Road (গ্রাম / এলাকা / রোড)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub area: Option<String>,
    /// House/Flat number or identifier
    #[serde(skip_serializing_if = "Option::is_none")]
    pub house: Option<String>,
    /// Postal code
    #[serde(skip_serializing_if = "Option::is_none")]
    pub postal_code: Option<String>,
}

/// A name + geo-code pair for an administrative level.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AddressComponent {
    #[serde(rename = "geoCode")]
    pub geo_code: String,
    pub name: String,
}

impl BanglaAddress {
    /// Construct a new `BanglaAddress` using geo-codes for division and district.
    ///
    /// The builder automatically looks up the Bengali name for valid codes.
    /// If an unknown code is provided, it safely falls back to using the query string
    /// as both the `geoCode` and `name`.
    ///
    /// # Examples
    /// ```rust
    /// use bangla::address::BanglaAddress;
    ///
    /// // Code "3" is Dhaka Division, Code "10" is Dhaka District
    /// let addr = BanglaAddress::new("3", "10");
    /// assert_eq!(addr.division.name, "ঢাকা");
    /// assert_eq!(addr.district.name, "ঢাকা");
    /// ```
    pub fn new(
        division_code: &str,
        district_code: &str,
    ) -> Self {
        let division = DIVISIONS
            .iter()
            .find(|(code, _)| *code == division_code)
            .map(|(code, name)| AddressComponent {
                geo_code: code.to_string(),
                name: name.to_string(),
            })
            .unwrap_or_else(|| AddressComponent {
                geo_code: division_code.to_string(),
                name: division_code.to_string(),
            });

        let district = DISTRICTS
            .iter()
            .find(|(div, dc, _)| *div == division_code && *dc == district_code)
            .map(|(_, dc, bn)| AddressComponent {
                geo_code: dc.to_string(),
                name: bn.to_string(),
            })
            .unwrap_or_else(|| AddressComponent {
                geo_code: district_code.to_string(),
                name: district_code.to_string(),
            });

        Self {
            division,
            district,
            upazila: None,
            union: None,
            area: None,
            house: None,
            postal_code: None,
        }
    }

    /// Set the upazila by name or geo code. 
    /// 
    /// Automatically looks up the provided query against the internal upazila database for the
    /// currently set district. If a match is found, it populates both the geo-code and the exact name.
    ///
    /// # Examples
    /// ```rust
    /// use bangla::address::BanglaAddress;
    ///
    /// let addr = BanglaAddress::new("3", "10").with_upazila("মিরপুর");
    /// assert_eq!(addr.upazila.as_ref().unwrap().geo_code, "01");
    /// ```
    pub fn with_upazila(mut self, query: impl Into<String>) -> Self {
        let q = query.into();
        let district_code = &self.district.geo_code;
        
        let found = UPAZILAS.iter()
            .find(|(dist, code, name)| dist == district_code && (*code == q || *name == q));

        if let Some((_, code, name)) = found {
            self.upazila = Some(AddressComponent {
                geo_code: code.to_string(),
                name: name.to_string(),
            });
        } else {
            // Fallback
            self.upazila = Some(AddressComponent {
                geo_code: q.clone(),
                name: q,
            });
        }
        self
    }

    /// Set the union by name or geo code.
    /// 
    /// Automatically looks up the provided query against the internal union database for the
    /// currently set upazila.
    ///
    /// # Examples
    /// ```rust
    /// use bangla::address::BanglaAddress;
    ///
    /// let addr = BanglaAddress::new("3", "10")
    ///     .with_upazila("মিরপুর")
    ///     .with_union("পল্লবী");
    /// assert_eq!(addr.union.as_ref().unwrap().name, "পল্লবী");
    /// ```
    pub fn with_union(mut self, query: impl Into<String>) -> Self {
        let q = query.into();
        
        if let Some(upz) = &self.upazila {
            let upz_code = &upz.geo_code;
            let found = UNIONS.iter()
                .find(|(u_code, code, name)| u_code == upz_code && (*code == q || *name == q));

            if let Some((_, code, name)) = found {
                self.union = Some(AddressComponent {
                    geo_code: code.to_string(),
                    name: name.to_string(),
                });
                return self;
            }
        }
        
        // Fallback if upazila is not set or not found
        self.union = Some(AddressComponent {
            geo_code: q.clone(),
            name: q,
        });
        
        self
    }

    /// Set the local area, village, or road.
    pub fn with_area(mut self, area: impl Into<String>) -> Self {
        self.area = Some(area.into());
        self
    }

    /// Set the house number or apartment details.
    pub fn with_house(mut self, house: impl Into<String>) -> Self {
        self.house = Some(house.into());
        self
    }

    /// Set the postal code.
    pub fn with_postal_code(mut self, code: impl Into<String>) -> Self {
        self.postal_code = Some(code.into());
        self
    }

    /// Serializes this address to a JSON string.
    ///
    /// # Examples
    /// ```rust
    /// use bangla::address::BanglaAddress;
    ///
    /// let addr = BanglaAddress::new("3", "10").with_postal_code("১২১৬");
    /// let json = addr.to_json();
    /// assert!(json.contains("\"geoCode\": \"3\""));
    /// assert!(json.contains("১২১৬"));
    /// ```
    pub fn to_json(&self) -> String {
        serde_json::to_string_pretty(self).unwrap_or_default()
    }

    /// Formats as a single-line postal address in Bengali.
    /// 
    /// Order: House, Area, Union, Upazila, District, Division, Postal Code, Bangladesh
    ///
    /// # Examples
    /// ```rust
    /// use bangla::address::BanglaAddress;
    ///
    /// let addr = BanglaAddress::new("3", "10").with_upazila("মিরপুর");
    /// assert_eq!(addr.format(), "মিরপুর, ঢাকা, ঢাকা, বাংলাদেশ");
    /// ```
    pub fn format(&self) -> String {
        let mut parts = Vec::new();
        if let Some(ref h) = self.house   { parts.push(h.clone()); }
        if let Some(ref a) = self.area    { parts.push(a.clone()); }
        if let Some(ref u) = self.union   { parts.push(u.name.clone()); }
        if let Some(ref upz) = self.upazila { parts.push(upz.name.clone()); }
        parts.push(self.district.name.clone());
        parts.push(self.division.name.clone());
        if let Some(ref p) = self.postal_code { parts.push(p.clone()); }
        parts.push("বাংলাদেশ".to_string());
        parts.join(", ")
    }
}

// ─────────────────────────────────────────────
//  Lookup helpers
// ─────────────────────────────────────────────

/// Find a division by geo-code or Bengali name.
///
/// # Examples
/// ```rust
/// use bangla::address::find_division;
///
/// let div = find_division("ঢাকা").unwrap();
/// assert_eq!(div.geo_code, "3");
/// ```
pub fn find_division(query: &str) -> Option<AddressComponent> {
    DIVISIONS.iter().find(|(code, name)| *code == query || *name == query)
        .map(|(code, name)| AddressComponent {
            geo_code: code.to_string(),
            name: name.to_string(),
        })
}

/// Returns all districts belonging to a division geo-code.
///
/// # Examples
/// ```rust
/// use bangla::address::districts_in_division;
///
/// // Get all districts in Dhaka Division (Code "3")
/// let dists = districts_in_division("3");
/// assert!(dists.iter().any(|d| d.name == "গাজীপুর"));
/// ```
pub fn districts_in_division(division_code: &str) -> Vec<AddressComponent> {
    DISTRICTS
        .iter()
        .filter(|(div, _, _)| *div == division_code)
        .map(|(_, dc, bn)| AddressComponent {
            geo_code: dc.to_string(),
            name: bn.to_string(),
        })
        .collect()
}

/// Find a district by its geo-code or name.
///
/// # Examples
/// ```rust
/// use bangla::address::find_district;
///
/// let dist = find_district("নরসিংদী").unwrap();
/// assert_eq!(dist.geo_code, "08");
/// ```
pub fn find_district(query: &str) -> Option<AddressComponent> {
    DISTRICTS.iter().find(|(_, dc, bn)| *dc == query || *bn == query)
        .map(|(_, dc, bn)| AddressComponent {
            geo_code: dc.to_string(),
            name: bn.to_string(),
        })
}

/// Returns all upazilas belonging to a district geo-code.
///
/// # Examples
/// ```rust
/// use bangla::address::upazilas_in_district;
///
/// let upz = upazilas_in_district("10"); // Dhaka District
/// assert!(!upz.is_empty());
/// ```
pub fn upazilas_in_district(district_code: &str) -> Vec<AddressComponent> {
    UPAZILAS
        .iter()
        .filter(|(dist, _, _)| *dist == district_code)
        .map(|(_, code, name)| AddressComponent {
            geo_code: code.to_string(),
            name: name.to_string(),
        })
        .collect()
}

/// Returns all unions belonging to an upazila geo-code.
///
/// # Examples
/// ```rust
/// use bangla::address::unions_in_upazila;
///
/// let unions = unions_in_upazila("06"); // Mirpur Upazila
/// assert!(!unions.is_empty());
/// ```
pub fn unions_in_upazila(upazila_code: &str) -> Vec<AddressComponent> {
    UNIONS
        .iter()
        .filter(|(upz, _, _)| *upz == upazila_code)
        .map(|(_, code, name)| AddressComponent {
            geo_code: code.to_string(),
            name: name.to_string(),
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_address_builder() {
        let addr = BanglaAddress::new("3", "10")
            .with_upazila("মিরপুর")
            .with_union("পল্লবী")
            .with_area("সেকশন-১১")
            .with_postal_code("১২১৬");

        assert_eq!(addr.division.name, "ঢাকা");
        assert_eq!(addr.district.name, "ঢাকা");
        assert_eq!(addr.upazila.as_ref().unwrap().name, "মিরপুর");
        assert_eq!(addr.postal_code.as_deref(), Some("১২১৬"));
    }

    #[test]
    fn test_format() {
        let addr = BanglaAddress::new("3", "10")
            .with_upazila("মিরপুর")
            .with_union("পল্লবী");
        let s = addr.format();
        assert!(s.contains("ঢাকা"));
        assert!(s.contains("বাংলাদেশ"));
    }

    #[test]
    fn test_json_output() {
        let addr = BanglaAddress::new("3", "10")
            .with_upazila("মিরপুর")
            .with_postal_code("1216");
        let json = addr.to_json();
        assert!(json.contains("\"geoCode\""));
        assert!(json.contains("1216"));
    }

    #[test]
    fn test_find_division() {
        let d = find_division("ঢাকা").unwrap();
        assert_eq!(d.geo_code, "3");
        let d2 = find_division("3").unwrap();
        assert_eq!(d2.geo_code, "3");
    }

    #[test]
    fn test_districts_in_division() {
        let dists = districts_in_division("3");
        assert!(dists.iter().any(|d| d.name == "ঢাকা"));
        assert!(dists.iter().any(|d| d.name == "গাজীপুর"));
    }

    #[test]
    fn test_find_district() {
        let d = find_district("নরসিংদী").unwrap();
        assert_eq!(d.geo_code, "08");
    }
}