stdweb/webapi/storage.rs
1use webcore::value::Reference;
2use webcore::try_from::TryInto;
3use private::TODO;
4
5/// The `Storage` interface of the Web Storage API provides access to
6/// the session storage or local storage for a particular domain.
7///
8/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Storage)
9// https://html.spec.whatwg.org/#storage-2
10#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)]
11#[reference(instance_of = "Storage")]
12pub struct Storage( Reference );
13
14impl Storage {
15 /// Gets the number of data items stored in the `Storage` object.
16 ///
17 /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Storage/length)
18 // https://html.spec.whatwg.org/#the-storage-interface:dom-storage-length
19 pub fn len( &self ) -> u32 {
20 js!( return @{self}.length; ).try_into().unwrap()
21 }
22
23 /// Returns a value corresponding to the key.
24 ///
25 /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem)
26 // https://html.spec.whatwg.org/#the-storage-interface:dom-storage-getitem
27 pub fn get( &self, key: &str ) -> Option< String > {
28 js!( return @{self}.getItem( @{key} ); ).try_into().ok()
29 }
30
31 /// Inserts a key-value pair into the storage.
32 ///
33 /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem)
34 // https://html.spec.whatwg.org/#the-storage-interface:dom-storage-setitem
35 pub fn insert( &self, key: &str, value: &str ) -> Result< (), TODO > {
36 js!( @(no_return)
37 @{self}.setItem( @{key}, @{value} );
38 );
39
40 Ok(())
41 }
42
43 /// Removes a key from the storage.
44 ///
45 /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Storage/removeItem)
46 // https://html.spec.whatwg.org/#the-storage-interface:dom-storage-removeitem
47 pub fn remove( &self, key: &str ) {
48 js!( @(no_return)
49 @{self}.removeItem( @{key} );
50 );
51 }
52
53 /// When invoked, will empty all keys out of the storage.
54 ///
55 /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Storage/clear)
56 // https://html.spec.whatwg.org/#the-storage-interface:dom-storage-clear
57 pub fn clear( &self ) {
58 js!( @(no_return)
59 @{self}.clear();
60 );
61 }
62
63 /// Return the name of the nth key in the storage.
64 ///
65 /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/Storage/key)
66 // https://html.spec.whatwg.org/#the-storage-interface:dom-storage-key
67 pub fn key( &self, nth: u32 ) -> Option< String > {
68 js!( return @{self}.key( @{nth} ); ).try_into().ok()
69 }
70
71 /// Returns true if the storage contains a value for the specified key.
72 pub fn contains_key( &self, key: &str ) -> bool {
73 js!( return !!@{self}.getItem( @{key} ); ).try_into().unwrap()
74 }
75}