msldap-ext 0.1.0-dev

Encoder/decoder for MS-ADTS LDAP extension controls (Paged Results, ExtendedDN, SDFlags, ShowDeleted, DirSync, VLV). Pure BER — no transport.
Documentation
//! Paged Results control — 1.2.840.113556.1.4.319 (RFC 2696).
//!
//! ```asn1
//! realSearchControlValue ::= SEQUENCE {
//!     size    INTEGER (0..maxInt),
//!     cookie  OCTET STRING
//! }
//! ```
//! First request: cookie empty. Server returns a new cookie in the response
//! control; caller passes it back until the returned cookie is empty.

use crate::ber;
use crate::Error;

/// OID for the Paged Results control (request and response share this OID).
pub const OID: &str = "1.2.840.113556.1.4.319";

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PagedResults {
    pub page_size: u32,
    /// `None` for the initial request; `Some(server_cookie)` on subsequent
    /// pages. The response also uses `Some(next)` / `Some(empty)` — an empty
    /// vec (len 0) is the server's end-of-results signal.
    pub cookie: Option<Vec<u8>>,
}

impl PagedResults {
    pub fn new(page_size: u32) -> Self {
        Self {
            page_size,
            cookie: None,
        }
    }

    pub fn with_cookie(page_size: u32, cookie: Vec<u8>) -> Self {
        Self {
            page_size,
            cookie: Some(cookie),
        }
    }

    /// Encode the control value (the OCTET STRING payload inside the LDAP
    /// Control SEQUENCE — callers wrap this with the OID + criticality bits).
    pub fn encode(&self) -> Vec<u8> {
        let mut body = Vec::with_capacity(16);
        ber::write_u32(&mut body, self.page_size);
        ber::write_octet_string(&mut body, self.cookie.as_deref().unwrap_or(&[]));
        ber::wrap_sequence(&body)
    }

    pub fn decode(buf: &[u8]) -> Result<Self, Error> {
        let (inner, _) = ber::read_sequence(buf)?;
        let (page_size, consumed) = ber::read_u32(inner)?;
        let (cookie, _) = ber::read_octet_string(&inner[consumed..])?;
        Ok(Self {
            page_size,
            cookie: if cookie.is_empty() {
                Some(Vec::new())
            } else {
                Some(cookie.to_vec())
            },
        })
    }

    /// Convenience: is this a response cookie signalling end-of-paging?
    pub fn is_end(&self) -> bool {
        matches!(&self.cookie, Some(c) if c.is_empty())
    }
}